-
Notifications
You must be signed in to change notification settings - Fork 81
/
TrainCar.cs
3486 lines (2993 loc) · 174 KB
/
TrainCar.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// COPYRIGHT 2009 - 2022 by the Open Rails project.
//
// This file is part of Open Rails.
//
// Open Rails is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Open Rails is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Open Rails. If not, see <http://www.gnu.org/licenses/>.
// Define this to log the wheel configurations on cars as they are loaded.
//#define DEBUG_WHEELS
// Debug car heat losses
// #define DEBUG_CAR_HEATLOSS
// Debug curve speed
// #define DEBUG_CURVE_SPEED
//Debug Tunnel Resistance
// #define DEBUG_TUNNEL_RESISTANCE
// Debug User SuperElevation
//#define DEBUG_USER_SUPERELEVATION
// Debug Brake Slide Calculations
//#define DEBUG_BRAKE_SLIDE
using Microsoft.Xna.Framework;
using Orts.Common;
using Orts.Formats.Msts;
using Orts.Parsers.Msts;
using Orts.Simulation.AIs;
using Orts.Simulation.Physics;
using Orts.Simulation.RollingStocks.Coupling;
using Orts.Simulation.RollingStocks.SubSystems;
using Orts.Simulation.RollingStocks.SubSystems.Brakes;
using Orts.Simulation.RollingStocks.SubSystems.PowerSupplies;
using Orts.Simulation.Signalling;
using Orts.Simulation.Timetables;
using ORTS.Common;
using ORTS.Scripting.Api;
using ORTS.Settings;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Event = Orts.Common.Event;
namespace Orts.Simulation.RollingStocks
{
public class ViewPoint
{
public Vector3 Location;
public Vector3 StartDirection;
public Vector3 RotationLimit;
public ViewPoint()
{
}
public ViewPoint(Vector3 location)
{
Location = location;
}
public ViewPoint(ViewPoint copy, bool rotate)
{
Location = copy.Location;
StartDirection = copy.StartDirection;
RotationLimit = copy.RotationLimit;
if (rotate)
{
Location.X *= -1;
Location.Z *= -1;
/*StartDirection.X += 180;
StartDirection.Z += 180;*/
}
}
}
public class PassengerViewPoint : ViewPoint
{
// Remember direction of passenger camera and apply when user returns to it.
public float RotationXRadians;
public float RotationYRadians;
}
public abstract class TrainCar
{
public readonly Simulator Simulator;
public readonly string WagFilePath;
public string RealWagFilePath; //we are substituting missing remote cars in MP, so need to remember this
public static int DbfEvalTravellingTooFast;//Debrief eval
public static int DbfEvalTravellingTooFastSnappedBrakeHose;//Debrief eval
public bool dbfEvalsnappedbrakehose = false;//Debrief eval
public bool ldbfevalcurvespeed = false;//Debrief eval
static float dbfmaxsafecurvespeedmps;//Debrief eval
public static int DbfEvalTrainOverturned;//Debrief eval
public bool ldbfevaltrainoverturned = false;
// original consist of which car was part (used in timetable for couple/uncouple options)
public string OrgConsist = string.Empty;
// sound related variables
public bool IsPartOfActiveTrain = true;
public List<int> SoundSourceIDs = new List<int>();
public IPowerSupply PowerSupply;
// Used to calculate Carriage Steam Heat Loss - ToDo - ctn_steamer - consolidate these parameters with other steam heat ones, also check as some now may be obsolete
public Interpolator TrainHeatBoilerWaterUsageGalukpH;
public Interpolator TrainHeatBoilerFuelUsageGalukpH;
// Input values to allow the water and fuel usage of steam heating boiler to be calculated based upon Spanner SwirlyFlo Mk111 Boiler
static float[] SteamUsageLbpH = new float[]
{
0.0f, 3000.0f
};
// Water Usage
static float[] WaterUsageGalukpH = new float[]
{
0.0f, 300.0f
};
// Fuel usage
static float[] FuelUsageGalukpH = new float[]
{
0.0f, 31.0f
};
public static Interpolator SteamHeatBoilerWaterUsageGalukpH()
{
return new Interpolator(SteamUsageLbpH, WaterUsageGalukpH);
}
public static Interpolator SteamHeatBoilerFuelUsageGalukpH()
{
return new Interpolator(SteamUsageLbpH, FuelUsageGalukpH);
}
public float MainSteamHeatPipeOuterDiaM = Me.FromIn(2.4f); // Steel pipe OD = 1.9" + 0.5" insulation (0.25" either side of pipe)
public float MainSteamHeatPipeInnerDiaM = Me.FromIn(1.50f); // Steel pipe ID = 1.5"
public float CarConnectSteamHoseOuterDiaM = Me.FromIn(2.05f); // Rubber hose OD = 2.05"
public float CarConnectSteamHoseInnerDiaM = Me.FromIn(1.50f); // Rubber hose ID = 1.5"
public bool IsSteamHeatBoilerLockedOut = false;
public float MaximumSteamHeatingBoilerSteamUsageRateLbpS;
public float MaximiumSteamHeatBoilerFuelTankCapacityL = 1500.0f; // Capacity of the fuel tank for the steam heating boiler
public float CurrentCarSteamHeatBoilerWaterCapacityL; // Current water level
public float CurrentSteamHeatBoilerFuelCapacityL; // Current fuel level - only on steam vans, diesels use main diesel tank
public float MaximumSteamHeatBoilerWaterTankCapacityL = L.FromGUK(800.0f); // Capacity of the water feed tank for the steam heating boiler
public float CompartmentHeatingPipeAreaFactor = 3.0f;
public float DesiredCompartmentTempSetpointC = C.FromF(55.0f); // This is the desired temperature for the passenger compartment heating
public float WindowDeratingFactor = 0.275f; // fraction of windows in carriage side - 27.5% of space are windows
public bool SteamHeatingBoilerOn = false;
public bool SteamHeatingCompartmentSteamTrapOn = false;
public float TotalCarCompartmentHeatLossW; // Transmission loss for the wagon
public float CarHeatCompartmentPipeAreaM2; // Area of surface of car pipe
public bool IsCarHeatingInitialized = false; // Allow steam heat to be initialised.
public float CarHeatSteamMainPipeHeatLossBTU; // BTU /hr
public float CarHeatConnectSteamHoseHeatLossBTU;
public float CarSteamHeatMainPipeCurrentHeatBTU;
public float CarSteamHeatMainPipeSteamPressurePSI;
public float CarCompartmentSteamPipeHeatConvW;
public float CarCompartmentSteamHeatPipeRadW;
public bool CarHeatCompartmentHeaterOn = false;
public float CarHeatSteamTrapUsageLBpS;
public float CarHeatConnectingSteamHoseLeakageLBpS;
public float SteamHoseLeakRateRandom;
public float CarNetHeatFlowRateW; // Net Steam loss - Loss in Cars vs Steam Pipe Heat
public float CarHeatCompartmentSteamPipeHeatW; // Heat generated by steam exchange area in compartment
public float CarHeatCurrentCompartmentHeatJ;
public float CarInsideTempC;
// some properties of this car
public float CarWidthM = 2.5f;
public float CarLengthM = 40; // derived classes must overwrite these defaults
public float CarHeightM = 4; // derived classes must overwrite these defaults
public float MassKG = 10000; // Mass in KG at runtime; coincides with InitialMassKG if there is no load and no ORTS freight anim
public float InitialMassKG = 10000;
public bool IsDriveable;
public bool HasFreightAnim = false;
public bool HasPassengerCapacity = false;
public bool HasInsideView = false;
public float CarHeightAboveSeaLevelM;
public float WagonNumBogies;
public float CarBogieCentreLengthM;
public float CarBodyLengthM;
public float CarCouplerFaceLengthM;
public float DerailmentCoefficient;
public float NadalDerailmentCoefficient;
public bool DerailmentCoefficientEnabled = true;
public float MaximumWheelFlangeAngleRad;
public float WheelFlangeLengthM;
public float AngleOfAttackRad;
public float DerailClimbDistanceM;
public bool DerailPossible = false;
public bool DerailExpected = false;
public float DerailElapsedTimeS;
public float MaxHandbrakeForceN;
public float MaxBrakeForceN = 89e3f;
public float InitialMaxHandbrakeForceN; // Initial force when agon initialised
public float InitialMaxBrakeForceN = 89e3f; // Initial force when agon initialised
// Coupler Animation
public AnimatedCoupler FrontCoupler = new AnimatedCoupler();
public AnimatedCoupler RearCoupler = new AnimatedCoupler();
// Air hose animation
public AnimatedAirHose FrontAirHose = new AnimatedAirHose();
public AnimatedAirHose RearAirHose = new AnimatedAirHose();
public float CarAirHoseLengthM;
public float CarAirHoseHorizontalLengthM;
// Used to calculate Carriage Steam Heat Loss
public const float BogieHeightM = 1.06f; // Height reduced by 1.06m to allow for bogies, etc
public const float CarCouplingPipeM = 1.2f; // Allow for connection between cars (assume 2' each end) - no heat is contributed to carriages.
public const float SpecificHeatCapacityAirKJpKgK = 1.006f; // Specific Heat Capacity of Air
public const float DensityAirKgpM3 = 1.247f; // Density of air - use a av value
public float CarHeatVolumeM3 { get => CarWidthM * (CarLengthM - CarCouplingPipeM) * (CarHeightM - BogieHeightM); } // Volume of car for heating purposes
public float CarHeatPipeAreaM2; // Area of surface of car pipe
public float CarOutsideTempC; // Ambient temperature outside of car
public float InitialCarOutsideTempC;
public bool IsTrainHeatingBoilerInitialised { get { return Train.TrainHeatingBoilerInitialised; } set { Train.TrainHeatingBoilerInitialised = value; } }
public float ConvectionFactor
{
get
{
const float LowSpeedMpS = 2.0f;
float ConvHeatTxfMinSpeed = 10.45f - LowSpeedMpS + (10.0f * (float)Math.Pow(LowSpeedMpS, 0.5));
float ConvHeatTxActualSpeed = 10.45f - AbsSpeedMpS + (10.0f * (float)Math.Pow(AbsSpeedMpS, 0.5));
float ConvFactor;
if (AbsSpeedMpS >= LowSpeedMpS)
{
ConvFactor = ConvHeatTxActualSpeed / ConvHeatTxfMinSpeed; // Calculate fraction
}
else
{
ConvFactor = 1.0f; // If speed less then 2m/s then set fraction to give stationary Kc value
}
ConvFactor = MathHelper.Clamp(ConvFactor, 1.0f, 1.6f); // Keep Conv Factor ratio within bounds - should not exceed 1.6.
return ConvFactor;
}
}
// Used to calculate wheel sliding for locked brake
public bool WheelBrakeSlideProtectionFitted = false;
public bool WheelBrakeSlideProtectionActive = false;
public bool WheelBrakeSlideProtectionLimitDisabled = false;
public float wheelBrakeSlideTimerResetValueS = 7.0f; // Set wsp time to 7 secs
public float WheelBrakeSlideProtectionTimerS = 7.0f;
public bool WheelBrakeSlideProtectionDumpValveLockout = false;
public bool BrakeSkid = false;
public bool BrakeSkidWarning = false;
public bool HUDBrakeSkid = false;
public float BrakeShoeCoefficientFriction = 1.0f; // Brake Shoe coefficient - for simple adhesion model set to 1
public float BrakeShoeCoefficientFrictionAdjFactor = 1.0f; // Factor to adjust Brake force by - based upon changing friction coefficient with speed, will change when wheel goes into skid
public float BrakeShoeRetardCoefficientFrictionAdjFactor = 1.0f; // Factor of adjust Retard Brake force by - independent of skid
float DefaultBrakeShoeCoefficientFriction; // A default value of brake shoe friction is no user settings are present.
float BrakeWheelTreadForceN; // The retarding force apparent on the tread of the wheel
float WagonBrakeAdhesiveForceN; // The adhesive force existing on the wheels of the wagon
public float SkidFriction = 0.08f; // Friction if wheel starts skidding - based upon wheel dynamic friction of approx 0.08
public float AuxTenderWaterMassKG; // Water mass in auxiliary tender
public string AuxWagonType; // Store wagon type for use with auxilary tender calculations
public LightCollection Lights;
public FreightAnimations FreightAnimations;
public int Headlight;
// instance variables set by train physics when it creates the traincar
public Train Train; // the car is connected to this train
// public bool IsPlayerTrain { get { return Train.TrainType == ORTS.Train.TRAINTYPE.PLAYER ? true : false; } set { } }
public bool IsPlayerTrain { get { return Train.IsPlayerDriven; } set { } }
public bool Flipped; // the car is reversed in the consist
public int UiD;
public string CarID = "AI"; //CarID = "0 - UID" if player train, "ActivityID - UID" if loose consist, "AI" if AI train
// status of the traincar - set by the train physics after it calls TrainCar.Update()
public WorldPosition WorldPosition = new WorldPosition(); // current position of the car
public float DistanceM; // running total of distance travelled - always positive, updated by train physics
public float _SpeedMpS; // meters per second; updated by train physics, relative to direction of car 50mph = 22MpS
public float _PrevSpeedMpS;
public float AbsSpeedMpS; // Math.Abs(SpeedMps) expression is repeated many times in the subclasses, maybe this deserves a class variable
public float CouplerSlackM; // extra distance between cars (calculated based on relative speeds)
public int HUDCouplerForceIndication = 0; // Flag to indicate whether coupler is 1 - pulling, 2 - pushing or 0 - neither
public float CouplerSlack2M; // slack calculated using draft gear force
public bool IsAdvancedCoupler = false; // Flag to indicate that coupler is to be treated as an advanced coupler
public float FrontCouplerSlackM; // Slack in car front coupler
public float RearCouplerSlackM; // Slack in rear coupler
public TrainCar CarAhead;
public TrainCar CarBehind;
public Vector3 RearCouplerLocation;
public int RearCouplerLocationTileX;
public int RearCouplerLocationTileZ;
public float AdvancedCouplerDynamicTensionSlackLimitM; // Varies as coupler moves
public float AdvancedCouplerDynamicCompressionSlackLimitM; // Varies as coupler moves
public bool WheelSlip; // true if locomotive wheels slipping
public bool WheelSlipWarning;
public bool WheelSkid; // True if wagon wheels lock up.
public float _AccelerationMpSS;
protected IIRFilter AccelerationFilter = new IIRFilter(IIRFilter.FilterTypes.Butterworth, 1, 1.0f, 0.1f);
// Wheel Bearing Temperature parameters
public float WheelBearingTemperatureDegC = 40.0f;
public string DisplayWheelBearingTemperatureStatus;
public float WheelBearingTemperatureRiseTimeS = 0;
public float HotBoxTemperatureRiseTimeS = 0;
public float WheelBearingTemperatureDeclineTimeS = 0;
public float InitialWheelBearingDeclineTemperatureDegC;
public float InitialWheelBearingRiseTemperatureDegC;
public float InitialHotBoxRiseTemperatureDegS;
public bool WheelBearingFailed = false;
public bool WheelBearingHot = false;
public bool HotBoxActivated = false;
public bool HotBoxHasBeenInitialized = false;
public bool HotBoxSoundActivated = false;
public float HotBoxDelayS;
public float ActivityHotBoxDurationS;
public float ActivityElapsedDurationS;
public float HotBoxStartTimeS;
// Setup for ambient temperature dependency
Interpolator OutsideWinterTempbyLatitudeC; // Interploator to calculate ambient Winter temperature based upon the latitude of the route
Interpolator OutsideAutumnTempbyLatitudeC; // Interploator to calculate ambient Autumn temperature based upon the latitude of the route
Interpolator OutsideSpringTempbyLatitudeC; // Interploator to calculate ambient Spring temperature based upon the latitude of the route
Interpolator OutsideSummerTempbyLatitudeC; // Interploator to calculate ambient Summer temperature based upon the latitude of the route
public bool AmbientTemperatureInitialised; // Flag to indicate that ambient temperature has been initialised
// Input values to allow the temperature for different values of latitude to be calculated
static float[] WorldLatitudeDeg = new float[]
{
-50.0f, -40.0f, -30.0f, -20.0f, -10.0f, 0.0f, 10.0f, 20.0f, 30.0f, 40.0f, 50.0f, 60.0f
};
// Temperature in deg Celcius
static float[] WorldTemperatureWinter = new float[]
{
0.9f, 8.7f, 12.4f, 17.2f, 20.9f, 25.9f, 22.8f, 18.2f, 11.1f, 1.1f, -10.2f, -18.7f
};
static float[] WorldTemperatureAutumn = new float[]
{
7.5f, 13.7f, 18.8f, 22.0f, 24.0f, 26.0f, 25.0f, 21.6f, 21.0f, 14.3f, 6.0f, 3.8f
};
static float[] WorldTemperatureSpring = new float[]
{
8.5f, 13.1f, 17.6f, 18.6f, 24.6f, 25.9f, 26.8f, 23.4f, 18.5f, 12.6f, 6.1f, 1.7f
};
static float[] WorldTemperatureSummer = new float[]
{
13.4f, 18.3f, 22.8f, 24.3f, 24.4f, 25.0f, 25.2f, 22.5f, 26.6f, 24.8f, 19.4f, 14.3f
};
public static Interpolator WorldWinterLatitudetoTemperatureC()
{
return new Interpolator(WorldLatitudeDeg, WorldTemperatureWinter);
}
public static Interpolator WorldAutumnLatitudetoTemperatureC()
{
return new Interpolator(WorldLatitudeDeg, WorldTemperatureAutumn);
}
public static Interpolator WorldSpringLatitudetoTemperatureC()
{
return new Interpolator(WorldLatitudeDeg, WorldTemperatureSpring);
}
public static Interpolator WorldSummerLatitudetoTemperatureC()
{
return new Interpolator(WorldLatitudeDeg, WorldTemperatureSummer);
}
public bool AcceptMUSignals = true; //indicates if the car accepts multiple unit signals; no more used
/// <summary>
/// Indicates which remote control group the car is in.
/// -1: unconnected, 0: sync/front group, 1: async/rear group
/// </summary>
public int RemoteControlGroup;
public bool IsMetric;
public bool IsUK;
public float prevElev = -100f;
public float SpeedMpS
{
get
{
return _SpeedMpS;
}
set
{
_SpeedMpS = value;
}
}
public float AccelerationMpSS
{
get { return _AccelerationMpSS; }
}
public float LocalThrottlePercent;
// represents the MU line travelling through the train. Uncontrolled locos respond to these commands.
public float ThrottlePercent
{
get
{
if (RemoteControlGroup == 0 && Train != null)
{
if (Train.LeadLocomotive is MSTSLocomotive locomotive)
{
if (!locomotive.TrainControlSystem.TractionAuthorization
|| Train.MUThrottlePercent <= 0)
{
return 0;
}
else if (Train.MUThrottlePercent > locomotive.TrainControlSystem.MaxThrottlePercent)
{
return Math.Max(locomotive.TrainControlSystem.MaxThrottlePercent, 0);
}
}
return Train.MUThrottlePercent;
}
else if (RemoteControlGroup == 1 && Train != null)
{
return Train.DPThrottlePercent;
}
else
{
return LocalThrottlePercent;
}
}
set
{
if (RemoteControlGroup == 0 && Train != null)
Train.MUThrottlePercent = value;
else
LocalThrottlePercent = value;
}
}
public int LocalGearboxGearIndex;
public int GearboxGearIndex
{
get
{
if (RemoteControlGroup >= 0)
return Train.MUGearboxGearIndex;
else
return LocalGearboxGearIndex;
}
set
{
if (RemoteControlGroup >= 0)
Train.MUGearboxGearIndex = value;
else
LocalGearboxGearIndex = value;
}
}
public float LocalDynamicBrakePercent = -1;
public float DynamicBrakePercent
{
get
{
if (RemoteControlGroup == 0 && Train != null)
{
if (Train.LeadLocomotive is MSTSLocomotive locomotive)
{
if (locomotive.TrainControlSystem.FullDynamicBrakingOrder)
{
return 100;
}
}
return Train.MUDynamicBrakePercent;
}
else if (RemoteControlGroup == 1 && Train != null)
{
return Train.DPDynamicBrakePercent;
}
else
{
return LocalDynamicBrakePercent;
}
}
set
{
if (RemoteControlGroup != -1 && Train != null)
Train.MUDynamicBrakePercent = value;
else
LocalDynamicBrakePercent = value;
if (Train != null && this == Train.LeadLocomotive)
LocalDynamicBrakePercent = value;
}
}
public Direction Direction
{
//TODO: following code lines have been modified to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab.
// To achieve the same result with other means, without flipping trainset physics, the code lines probably should be changed
get
{
if (IsDriveable && Train.IsActualPlayerTrain)
{
var loco = this as MSTSLocomotive;
return Flipped ^ loco.UsingRearCab ? DirectionControl.Flip(Train.MUDirection) : Train.MUDirection;
}
else
{
return Flipped ? DirectionControl.Flip(Train.MUDirection) : Train.MUDirection;
}
}
set
{
var loco = this as MSTSLocomotive;
Train.MUDirection = Flipped ^ loco.UsingRearCab ? DirectionControl.Flip(value) : value;
}
}
public BrakeSystem BrakeSystem;
public float PreviousSteamBrakeCylinderPressurePSI;
// TrainCar.Update() must set these variables
public float MotiveForceN; // ie motor power in Newtons - signed relative to direction of car -
public float TractiveForceN = 0f; // Raw tractive force for electric sound variable2
public SmoothedData MotiveForceSmoothedN = new SmoothedData(0.5f);
public float PrevMotiveForceN;
// Gravity forces have negative values on rising grade.
// This means they have the same sense as the motive forces and will push the train downhill.
public float GravityForceN; // Newtons - signed relative to direction of car.
public float CurveForceN; // Resistive force due to curve, in Newtons
public float WindForceN; // Resistive force due to wind
public float DynamicBrakeForceN = 0f; // Raw dynamic brake force for diesel and electric locomotives
// Derailment variables
public float TotalWagonVerticalDerailForceN; // Vertical force of wagon/car - essentially determined by the weight
public float TotalWagonLateralDerailForceN;
public float LateralWindForceN;
public float WagonFrontCouplerAngleRad;
public float WagonFrontCouplerBuffAngleRad;
public float WagonRearCouplerAngleRad;
public float WagonRearCouplerBuffAngleRad;
public float CarTrackPlayM = Me.FromIn(2.0f);
public float AdjustedWagonFrontCouplerAngleRad;
public float AdjustedWagonRearCouplerAngleRad;
public float WagonFrontCouplerCurveExtM;
public float WagonRearCouplerCurveExtM;
public float WagonCouplerAngleDerailRad;
public bool BuffForceExceeded;
// filter curve force for audio to prevent rapid changes.
//private IIRFilter CurveForceFilter = new IIRFilter(IIRFilter.FilterTypes.Butterworth, 1, 1.0f, 0.9f);
protected SmoothedData CurveForceFilter = new SmoothedData(0.75f);
public float CurveForceNFiltered;
public float TunnelForceN; // Resistive force due to tunnel, in Newtons
public float FrictionForceN; // in Newtons ( kg.m/s^2 ) unsigned, includes effects of curvature
public float BrakeForceN; // brake force applied to slow train (Newtons) - will be impacted by wheel/rail friction
public float BrakeRetardForceN; // brake force applied to wheel by brakeshoe (Newtons) independent of friction wheel/rail friction
// Sum of all the forces acting on a Traincar in the direction of driving.
// MotiveForceN and GravityForceN act to accelerate the train. The others act to brake the train.
public float TotalForceN; //
public string CarBrakeSystemType;
public float CurrentElevationPercent;
public bool CurveSpeedDependent;
protected float MaxDurableSafeCurveSpeedMpS;
// temporary values used to compute coupler forces
public float CouplerForceA; // left hand side value below diagonal
public float CouplerForceB; // left hand side value on diagonal
public float CouplerForceC; // left hand side value above diagonal
public float CouplerForceG; // temporary value used by solver
public float CouplerForceR; // right hand side value
public float CouplerForceU; // result
public float ImpulseCouplerForceUN;
public SmoothedData CouplerForceUSmoothed = new SmoothedData(1.0f);
public float PreviousCouplerSlackM;
public float SmoothedCouplerForceUN;
public bool CouplerExceedBreakLimit; //true when coupler force is higher then Break limit (set by 2nd parameter in Break statement)
public bool CouplerOverloaded; //true when coupler force is higher then Proof limit, thus overloaded, but not necessarily broken (set by 1nd parameter in Break statement)
public bool BrakesStuck; //true when brakes stuck
// set when model is loaded
public List<WheelAxle> WheelAxles = new List<WheelAxle>();
public bool WheelAxlesLoaded;
public List<TrainCarPart> Parts = new List<TrainCarPart>();
// For use by cameras, initialized in MSTSWagon class and its derived classes
public List<PassengerViewPoint> PassengerViewpoints = new List<PassengerViewPoint>();
public List<PassengerViewPoint> CabViewpoints; //three dimensional cab view point
public List<ViewPoint> HeadOutViewpoints = new List<ViewPoint>();
// Used by Curve Speed Method
protected float TrackGaugeM = 1.435f; // Track gauge - read in MSTSWagon
protected Vector3 InitialCentreOfGravityM = new Vector3(0, 1.8f, 0); // get centre of gravity - read in MSTSWagon
protected Vector3 CentreOfGravityM = new Vector3(0, 1.8f, 0); // get centre of gravity after adjusted for freight animation
protected float SuperelevationM; // Super elevation on the curve
protected float UnbalancedSuperElevationM; // Unbalanced superelevation, read from MSTS Wagon File
protected float SuperElevationTotalM; // Total superelevation
public float SuperElevationAngleRad;
protected bool IsMaxSafeCurveSpeed = false; // Has equal loading speed around the curve been exceeded, ie are all the wheesl still on the track?
public bool IsCriticalMaxSpeed = false; // Has the critical maximum speed around the curve been reached, is the wagon about to overturn?
public bool IsCriticalMinSpeed = false; // Is the speed less then the minimum required for the wagon to travel around the curve
protected float MaxCurveEqualLoadSpeedMps; // Max speed that rolling stock can do whist maintaining equal load on track
protected float StartCurveResistanceFactor = 2.0f; // Set curve friction at Start = 200%
protected float RouteSpeedMpS; // Max Route Speed Limit
protected const float GravitationalAccelerationMpS2 = 9.80665f; // Acceleration due to gravity 9.80665 m/s2
protected int WagonNumAxles; // Number of axles on a wagon
protected int InitWagonNumAxles; // Initial read of number of axles on a wagon
protected float MSTSWagonNumWheels; // Number of axles on a wagon - used to read MSTS value as default
protected int LocoNumDrvAxles; // Number of drive axles on locomotive
protected float MSTSLocoNumDrvWheels; // Number of drive axles on locomotive - used to read MSTS value as default
public float DriverWheelRadiusM = Me.FromIn(30.0f); // Drive wheel radius of locomotive wheels - Wheel radius of loco drive wheels can be anywhere from about 10" to 40".
public enum SteamEngineTypes
{
Unknown,
Simple,
Geared,
Compound,
}
public SteamEngineTypes SteamEngineType;
public enum WagonTypes
{
Unknown,
Engine,
Tender,
Passenger,
Freight,
EOT,
}
public WagonTypes WagonType;
public enum EngineTypes
{
Steam,
Diesel,
Electric,
Control,
}
public EngineTypes EngineType;
public enum WagonSpecialTypes
{
Unknown,
HeatingBoiler,
Heated,
PowerVan,
}
public WagonSpecialTypes WagonSpecialType;
protected float CurveResistanceZeroSpeedFactor = 0.5f; // Based upon research (Russian experiments - 1960) the older formula might be about 2x actual value
protected float RigidWheelBaseM; // Vehicle rigid wheelbase, read from MSTS Wagon file
protected float TrainCrossSectionAreaM2; // Cross sectional area of the train
protected float DoubleTunnelCrossSectAreaM2;
protected float SingleTunnelCrossSectAreaM2;
protected float DoubleTunnelPerimeterM;
protected float SingleTunnelPerimeterAreaM;
protected float TunnelCrossSectionAreaM2 = 0.0f;
protected float TunnelPerimeterM = 0.0f;
// used by tunnel processing
public struct CarTunnelInfoData
{
public float? FrontPositionBeyondStartOfTunnel; // position of front of wagon wrt start of tunnel
public float? LengthMOfTunnelAheadFront; // Length of tunnel remaining ahead of front of wagon (negative if front of wagon out of tunnel)
public float? LengthMOfTunnelBehindRear; // Length of tunnel behind rear of wagon (negative if rear of wagon has not yet entered tunnel)
public int numTunnelPaths; // Number of paths through tunnel
}
public CarTunnelInfoData CarTunnelData;
public virtual void Initialize()
{
CurveSpeedDependent = Simulator.Settings.CurveSpeedDependent;
//CurveForceFilter.Initialize();
// Initialize tunnel resistance values
DoubleTunnelCrossSectAreaM2 = (float)Simulator.TRK.Tr_RouteFile.DoubleTunnelAreaM2;
SingleTunnelCrossSectAreaM2 = (float)Simulator.TRK.Tr_RouteFile.SingleTunnelAreaM2;
DoubleTunnelPerimeterM = (float)Simulator.TRK.Tr_RouteFile.DoubleTunnelPerimeterM;
SingleTunnelPerimeterAreaM = (float)Simulator.TRK.Tr_RouteFile.SingleTunnelPerimeterM;
// get route speed limit
RouteSpeedMpS = (float)Simulator.TRK.Tr_RouteFile.SpeedLimit;
// if no values are in TRK file, calculate default values.
// Single track Tunnels
if (SingleTunnelCrossSectAreaM2 == 0)
{
if (RouteSpeedMpS >= 97.22) // if route speed greater then 350km/h
{
SingleTunnelCrossSectAreaM2 = 70.0f;
SingleTunnelPerimeterAreaM = 32.0f;
}
else if (RouteSpeedMpS >= 69.4 && RouteSpeedMpS < 97.22) // Route speed greater then 250km/h and less then 350km/h
{
SingleTunnelCrossSectAreaM2 = 70.0f;
SingleTunnelPerimeterAreaM = 32.0f;
}
else if (RouteSpeedMpS >= 55.5 && RouteSpeedMpS < 69.4) // Route speed greater then 200km/h and less then 250km/h
{
SingleTunnelCrossSectAreaM2 = 58.0f;
SingleTunnelPerimeterAreaM = 28.0f;
}
else if (RouteSpeedMpS >= 44.4 && RouteSpeedMpS < 55.5) // Route speed greater then 160km/h and less then 200km/h
{
SingleTunnelCrossSectAreaM2 = 50.0f;
SingleTunnelPerimeterAreaM = 25.5f;
}
else if (RouteSpeedMpS >= 33.3 && RouteSpeedMpS < 44.4) // Route speed greater then 120km/h and less then 160km/h
{
SingleTunnelCrossSectAreaM2 = 42.0f;
SingleTunnelPerimeterAreaM = 22.5f;
}
else // Route speed less then 120km/h
{
SingleTunnelCrossSectAreaM2 = 21.0f; // Typically older slower speed designed tunnels
SingleTunnelPerimeterAreaM = 17.8f;
}
}
// Double track Tunnels
if (DoubleTunnelCrossSectAreaM2 == 0)
{
if (RouteSpeedMpS >= 97.22) // if route speed greater then 350km/h
{
DoubleTunnelCrossSectAreaM2 = 100.0f;
DoubleTunnelPerimeterM = 37.5f;
}
else if (RouteSpeedMpS >= 69.4 && RouteSpeedMpS < 97.22) // Route speed greater then 250km/h and less then 350km/h
{
DoubleTunnelCrossSectAreaM2 = 100.0f;
DoubleTunnelPerimeterM = 37.5f;
}
else if (RouteSpeedMpS >= 55.5 && RouteSpeedMpS < 69.4) // Route speed greater then 200km/h and less then 250km/h
{
DoubleTunnelCrossSectAreaM2 = 90.0f;
DoubleTunnelPerimeterM = 35.0f;
}
else if (RouteSpeedMpS >= 44.4 && RouteSpeedMpS < 55.5) // Route speed greater then 160km/h and less then 200km/h
{
DoubleTunnelCrossSectAreaM2 = 80.0f;
DoubleTunnelPerimeterM = 34.5f;
}
else if (RouteSpeedMpS >= 33.3 && RouteSpeedMpS < 44.4) // Route speed greater then 120km/h and less then 160km/h
{
DoubleTunnelCrossSectAreaM2 = 76.0f;
DoubleTunnelPerimeterM = 31.0f;
}
else // Route speed less then 120km/h
{
DoubleTunnelCrossSectAreaM2 = 41.8f; // Typically older slower speed designed tunnels
DoubleTunnelPerimeterM = 25.01f;
}
}
#if DEBUG_TUNNEL_RESISTANCE
Trace.TraceInformation("================================== TrainCar.cs - Tunnel Resistance Initialisation ==============================================================");
Trace.TraceInformation("Tunnel 1 tr perimeter {0} Tunnel 1 tr area {1}", SingleTunnelPerimeterAreaM, SingleTunnelPerimeterAreaM);
Trace.TraceInformation("Tunnel 2 tr perimeter {0} Tunnel 2 tr area {1}", DoubleTunnelPerimeterM, DoubleTunnelCrossSectAreaM2);
#endif
}
// called when it's time to update the MotiveForce and FrictionForce
public virtual void Update(float elapsedClockSeconds)
{
// Initialise ambient temperatures on first initial loop, then ignore
if (!AmbientTemperatureInitialised)
{
InitializeCarTemperatures();
AmbientTemperatureInitialised = true;
}
// Update temperature variation for height of car above sea level
// Typically in clear conditions there is a 9.8 DegC variation for every 1000m (1km) rise, in snow/rain there is approx 5.5 DegC variation for every 1000m (1km) rise
float TemperatureHeightVariationDegC = 0;
const float DryLapseTemperatureC = 9.8f;
const float WetLapseTemperatureC = 5.5f;
if (Simulator.WeatherType == WeatherType.Rain || Simulator.WeatherType == WeatherType.Snow) // Apply snow/rain height variation
{
TemperatureHeightVariationDegC = Me.ToKiloM(CarHeightAboveSeaLevelM) * WetLapseTemperatureC;
}
else // Apply dry height variation
{
TemperatureHeightVariationDegC = Me.ToKiloM(CarHeightAboveSeaLevelM) * DryLapseTemperatureC;
}
TemperatureHeightVariationDegC = MathHelper.Clamp(TemperatureHeightVariationDegC, 0.00f, 30.0f);
CarOutsideTempC = InitialCarOutsideTempC - TemperatureHeightVariationDegC;
// gravity force, M32 is up component of forward vector
GravityForceN = MassKG * GravitationalAccelerationMpS2 * WorldPosition.XNAMatrix.M32;
CurrentElevationPercent = 100f * WorldPosition.XNAMatrix.M32;
AbsSpeedMpS = Math.Abs(_SpeedMpS);
//TODO: next if block has been inserted to flip trainset physics in order to get viewing direction coincident with loco direction when using rear cab.
// To achieve the same result with other means, without flipping trainset physics, the block should be deleted
//
if (IsDriveable && Train != null & Train.IsPlayerDriven && (this as MSTSLocomotive).UsingRearCab)
{
GravityForceN = -GravityForceN;
CurrentElevationPercent = -CurrentElevationPercent;
}
UpdateCurveSpeedLimit(); // call this first as it will provide inputs for the curve force.
UpdateCurveForce(elapsedClockSeconds);
UpdateTunnelForce();
UpdateBrakeSlideCalculation();
UpdateTrainDerailmentRisk(elapsedClockSeconds);
// acceleration
if (elapsedClockSeconds > 0.0f)
{
_AccelerationMpSS = (_SpeedMpS - _PrevSpeedMpS) / elapsedClockSeconds;
if (Simulator.UseAdvancedAdhesion && !Simulator.Settings.SimpleControlPhysics)
_AccelerationMpSS = AccelerationFilter.Filter(_AccelerationMpSS, elapsedClockSeconds);
_PrevSpeedMpS = _SpeedMpS;
}
}
/// <summary>
/// update position of discrete freight animations (e.g. containers)
/// </summary>
public void UpdateFreightAnimationDiscretePositions()
{
if (FreightAnimations?.Animations != null)
{
foreach (var freightAnim in FreightAnimations.Animations)
{
if (freightAnim is FreightAnimationDiscrete)
{
var discreteFreightAnim = freightAnim as FreightAnimationDiscrete;
if (discreteFreightAnim.Loaded && discreteFreightAnim.Container != null)
{
var container = discreteFreightAnim.Container;
container.WorldPosition.XNAMatrix = Matrix.Multiply(container.RelativeContainerMatrix, discreteFreightAnim.Wagon.WorldPosition.XNAMatrix);
container.WorldPosition.TileX = WorldPosition.TileX;
container.WorldPosition.TileZ = WorldPosition.TileZ;
}
}
}
}
}
/// <summary>
/// Initialise Train Temperatures
/// <\summary>
public void InitializeCarTemperatures()
{
OutsideWinterTempbyLatitudeC = WorldWinterLatitudetoTemperatureC();
OutsideAutumnTempbyLatitudeC = WorldAutumnLatitudetoTemperatureC();
OutsideSpringTempbyLatitudeC = WorldSpringLatitudetoTemperatureC();
OutsideSummerTempbyLatitudeC = WorldSummerLatitudetoTemperatureC();
// Find the latitude reading and set outside temperature
double latitude = 0;
double longitude = 0;
new WorldLatLon().ConvertWTC(WorldPosition.TileX, WorldPosition.TileZ, WorldPosition.Location, ref latitude, ref longitude);
float LatitudeDeg = MathHelper.ToDegrees((float)latitude);
// Sets outside temperature dependent upon the season
if (Simulator.Season == SeasonType.Winter)
{
// Winter temps
InitialCarOutsideTempC = OutsideWinterTempbyLatitudeC[LatitudeDeg];
}
else if (Simulator.Season == SeasonType.Autumn)
{
// Autumn temps
InitialCarOutsideTempC = OutsideAutumnTempbyLatitudeC[LatitudeDeg];
}
else if (Simulator.Season == SeasonType.Spring)
{
// Spring temps
InitialCarOutsideTempC = OutsideSpringTempbyLatitudeC[LatitudeDeg];
}
else
{
// Summer temps
InitialCarOutsideTempC = OutsideSummerTempbyLatitudeC[LatitudeDeg];
}
// If weather is freezing. Snow will only be produced when temp is between 0 and 2 Deg C. Adjust temp as appropriate
const float SnowTemperatureC = 2;
if (Simulator.WeatherType == WeatherType.Snow && InitialCarOutsideTempC > SnowTemperatureC)
{
InitialCarOutsideTempC = 0; // Weather snowing - freezing conditions.
}
// Initialise wheel bearing temperature to ambient temperature
WheelBearingTemperatureDegC = InitialCarOutsideTempC;
InitialWheelBearingRiseTemperatureDegC = InitialCarOutsideTempC;
InitialWheelBearingDeclineTemperatureDegC = InitialCarOutsideTempC;
}
#region Calculate Brake Skid
/// <summary>
/// This section calculates:
/// i) Changing brake shoe friction coefficient due to changes in speed
/// ii) force on the wheel due to braking, and whether sliding will occur.
///
/// </summary>
public virtual void UpdateBrakeSlideCalculation()
{
// Only apply slide, and advanced brake friction, if advanced adhesion is selected, simplecontrolphysics is not set, and it is a Player train
if (Simulator.UseAdvancedAdhesion && !Simulator.Settings.SimpleControlPhysics && IsPlayerTrain)
{
// Get user defined brake shoe coefficient if defined in WAG file
float UserFriction = GetUserBrakeShoeFrictionFactor();
float ZeroUserFriction = GetZeroUserBrakeShoeFrictionFactor();
float AdhesionMultiplier = Simulator.Settings.AdhesionFactor / 100.0f; // User set adjustment factor - convert to a factor where 100% = no change to adhesion
// This section calculates an adjustment factor for the brake force dependent upon the "base" (zero speed) friction value.
//For a user defined case the base value is the zero speed value from the curve entered by the user.
// For a "default" case where no user data has been added to the WAG file, the base friction value has been assumed to be 0.2, thus maximum value of 20% applied.
if (UserFriction != 0) // User defined friction has been applied in WAG file - Assume MaxBrakeForce is correctly set in the WAG, so no adjustment required
{
BrakeShoeCoefficientFrictionAdjFactor = UserFriction / ZeroUserFriction * AdhesionMultiplier; // Factor calculated by normalising zero speed value on friction curve applied in WAG file
BrakeShoeRetardCoefficientFrictionAdjFactor = UserFriction / ZeroUserFriction * AdhesionMultiplier;
BrakeShoeCoefficientFriction = UserFriction * AdhesionMultiplier; // For display purposes on HUD
}
else
// User defined friction NOT applied in WAG file - Assume MaxBrakeForce is incorrectly set in the WAG, so adjustment is required
{
DefaultBrakeShoeCoefficientFriction = (7.6f / (MpS.ToKpH(AbsSpeedMpS) + 17.5f) + 0.07f) * AdhesionMultiplier; // Base Curtius - Kniffler equation - u = 0.50, all other values are scaled off this formula
BrakeShoeCoefficientFrictionAdjFactor = DefaultBrakeShoeCoefficientFriction / 0.2f * AdhesionMultiplier; // Assuming that current MaxBrakeForce has been set with an existing Friction Coff of 0.2f, an adjustment factor needs to be developed to reduce the MAxBrakeForce by a relative amount
BrakeShoeRetardCoefficientFrictionAdjFactor = DefaultBrakeShoeCoefficientFriction / 0.2f * AdhesionMultiplier;
BrakeShoeCoefficientFriction = DefaultBrakeShoeCoefficientFriction * AdhesionMultiplier; // For display purposes on HUD
}
// Clamp adjustment factor to a value of 1.0 - i.e. the brakeforce can never exceed the Brake Force value defined in the WAG file
BrakeShoeCoefficientFrictionAdjFactor = MathHelper.Clamp(BrakeShoeCoefficientFrictionAdjFactor, 0.01f, 1.0f);
BrakeShoeRetardCoefficientFrictionAdjFactor = MathHelper.Clamp(BrakeShoeRetardCoefficientFrictionAdjFactor, 0.01f, 1.0f);
// ************ Check if diesel or electric - assumed already be cover by advanced adhesion model *********
if (this is MSTSDieselLocomotive || this is MSTSElectricLocomotive)
{
// If advanced adhesion model indicates wheel slip warning, then check other conditions (throttle and brake force) to determine whether it is a wheel slip or brake skid
if (WheelSlipWarning && ThrottlePercent < 0.1f && BrakeRetardForceN > 25.0)
{
BrakeSkidWarning = true; // set brake skid flag true
}
else
{
BrakeSkidWarning = false;
}