/
VesselState.cs
2080 lines (1675 loc) · 93.6 KB
/
VesselState.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using KSP.Localization;
using Smooth.Pools;
using UnityEngine;
namespace MuMech
{
public class VesselState
{
public static bool isLoadedPrincipia;
public static bool isLoadedProceduralFairing;
public static bool isLoadedRealFuels;
// RealFuels.ModuleEngineRF ullageSet field to call via reflection
public static FieldInfo RFullageSetField;
// RealFuels.ModuleEngineRF ignitions field to call via reflection
public static FieldInfo RFignitionsField;
// RealFuels.ModuleEngineRF ignited field to call via reflection
public static FieldInfo RFignitedField;
// RealFuels.ModuleEngineRF ullage field to call via reflection
public static FieldInfo RFullageField;
// RealFuels.Ullage.UllageSet GetUllageStability method to call via reflection
public static MethodInfo RFGetUllageStabilityMethod;
// RealFuels.Ullage.UllageSimulator fields to determine ullage status
public static double RFveryStableValue;
private static double RFstableValue;
private static double RFriskyValue;
private static double RFveryRiskyValue;
private static double RFunstableValue;
public enum UllageState
{
VeryUnstable,
Unstable,
VeryRisky,
Risky,
Stable,
VeryStable // "Nominal" also winds up here
}
// lowestUllage is always VeryStable without RealFuels installed
public UllageState lowestUllage => einfo.lowestUllage;
public static bool isLoadedFAR;
private delegate double FARVesselDelegate(Vessel v);
private static FARVesselDelegate FARVesselDragCoeff;
private static FARVesselDelegate FARVesselRefArea;
private static FARVesselDelegate FARVesselTermVelEst;
private static FARVesselDelegate FARVesselDynPres;
private delegate void FARCalculateVesselAeroForcesDelegate(Vessel vessel, out Vector3 aeroForce, out Vector3 aeroTorque,
Vector3 velocityWorldVector, double altitude);
private static FARCalculateVesselAeroForcesDelegate FARCalculateVesselAeroForces;
private Vessel vesselRef;
private readonly EngineInfo einfo = new EngineInfo();
private readonly IntakeInfo iinfo = new IntakeInfo();
public readonly List<EngineWrapper> enginesWrappers = new List<EngineWrapper>();
[ValueInfoItem("#MechJeb_UniversalTime", InfoItem.Category.Recorder, format = ValueInfoItem.TIME)] //Universal Time
public double time; //planetarium time
public double deltaT; //TimeWarp.fixedDeltaTime
public Vector3d CoM;
public Vector3d MoI; //Diagonal components of the inertia tensor (almost always the dominant components)
public Vector3d up;
public Vector3d north;
public Vector3d east;
public Vector3d forward; //the direction the vessel is pointing
public Vector3d horizontalOrbit; //unit vector in the direction of horizontal component of orbit velocity
public Vector3d horizontalSurface; //unit vector in the direction of horizontal component of surface velocity
public Vector3d rootPartPos;
public Quaternion rotationSurface;
public Quaternion rotationVesselSurface;
public Vector3d velocityMainBodySurface;
public Vector3d orbitalVelocity;
public Vector3d orbitalPosition;
public Vector3d surfaceVelocity;
public Vector3d angularVelocity;
public Vector3d angularMomentum;
public Vector3d radialPlus; //unit vector in the plane of up and velocityVesselOrbit and perpendicular to velocityVesselOrbit
public Vector3d radialPlusSurface; //unit vector in the plane of up and velocityVesselSurface and perpendicular to velocityVesselSurface
public Vector3d normalPlus; //unit vector perpendicular to up and velocityVesselOrbit
public Vector3d normalPlusSurface; //unit vector perpendicular to up and velocityVesselSurface
public Vector3d gravityForce;
[ValueInfoItem("#MechJeb_LocalGravity", InfoItem.Category.Misc, format = ValueInfoItem.SI, units = "m/s²")] //Local gravity
public double localg; //magnitude of gravityForce
//How about changing these so we store the instantaneous values and *also*
//the smoothed MovingAverages? Sometimes we need the instantaneous value.
[ValueInfoItem("#MechJeb_OrbitalSpeed", InfoItem.Category.Orbit, format = ValueInfoItem.SI, units = "m/s")] //Orbital speed
public MovingAverage speedOrbital = new MovingAverage();
[ValueInfoItem("#MechJeb_SurfaceSpeed", InfoItem.Category.Surface, format = ValueInfoItem.SI, units = "m/s")] //Surface speed
public MovingAverage speedSurface = new MovingAverage();
[ValueInfoItem("#MechJeb_VerticalSpeed", InfoItem.Category.Surface, format = ValueInfoItem.SI, units = "m/s")] //Vertical speed
public MovingAverage speedVertical = new MovingAverage();
[ValueInfoItem("#MechJeb_SurfaceHorizontalSpeed", InfoItem.Category.Surface, format = ValueInfoItem.SI,
units = "m/s")] //Surface horizontal speed
public MovingAverage speedSurfaceHorizontal = new MovingAverage();
[ValueInfoItem("#MechJeb_OrbitHorizontalSpeed", InfoItem.Category.Orbit, format = ValueInfoItem.SI, units = "m/s")] //Orbit horizontal speed
public double speedOrbitHorizontal;
[ValueInfoItem("#MechJeb_Heading", InfoItem.Category.Surface, format = "F1", units = "º")] //Heading
public MovingAverage vesselHeading = new MovingAverage();
[ValueInfoItem("#MechJeb_Pitch", InfoItem.Category.Surface, format = "F1", units = "º")] //Pitch
public MovingAverage vesselPitch = new MovingAverage();
[ValueInfoItem("#MechJeb_Roll", InfoItem.Category.Surface, format = "F1", units = "º")] //Roll
public MovingAverage vesselRoll = new MovingAverage();
[ValueInfoItem("#MechJeb_Altitude_ASL", InfoItem.Category.Surface, format = ValueInfoItem.SI, siSigFigs = 6, units = "m")] //Altitude (ASL)
public MovingAverage altitudeASL = new MovingAverage();
[ValueInfoItem("#MechJeb_Altitude_true", InfoItem.Category.Surface, format = ValueInfoItem.SI, siSigFigs = 6, units = "m")] //Altitude (true)
public MovingAverage altitudeTrue = new MovingAverage();
[ValueInfoItem("#MechJeb_SurfaceAltitudeASL", InfoItem.Category.Surface, format = ValueInfoItem.SI, siSigFigs = 4,
units = "m")] //Surface altitude ASL
public double surfaceAltitudeASL;
[ValueInfoItem("#MechJeb_Apoapsis", InfoItem.Category.Orbit, units = "m", format = ValueInfoItem.SI, siSigFigs = 6,
category = InfoItem.Category.Orbit)] //Apoapsis
public MovingAverage orbitApA = new MovingAverage();
[ValueInfoItem("#MechJeb_Periapsis", InfoItem.Category.Orbit, units = "m", format = ValueInfoItem.SI, siSigFigs = 6,
category = InfoItem.Category.Orbit)] //Periapsis
public MovingAverage orbitPeA = new MovingAverage();
[ValueInfoItem("#MechJeb_OrbitalPeriod", InfoItem.Category.Orbit, format = ValueInfoItem.TIME, timeDecimalPlaces = 2,
category = InfoItem.Category.Orbit)] //Orbital period
public MovingAverage orbitPeriod = new MovingAverage();
[ValueInfoItem("#MechJeb_TimeToApoapsis", InfoItem.Category.Orbit, format = ValueInfoItem.TIME, timeDecimalPlaces = 1)] //Time to apoapsis
public MovingAverage orbitTimeToAp = new MovingAverage();
[ValueInfoItem("#MechJeb_TimeToPeriapsis", InfoItem.Category.Orbit, format = ValueInfoItem.TIME, timeDecimalPlaces = 1)] //Time to periapsis
public MovingAverage orbitTimeToPe = new MovingAverage();
[ValueInfoItem("#MechJeb_LAN", InfoItem.Category.Orbit, format = ValueInfoItem.ANGLE)] //LAN
public MovingAverage orbitLAN = new MovingAverage();
[ValueInfoItem("#MechJeb_ArgumentOfPeriapsis", InfoItem.Category.Orbit, format = "F1", units = "º")] //Argument of periapsis
public MovingAverage orbitArgumentOfPeriapsis = new MovingAverage();
[ValueInfoItem("#MechJeb_Inclination", InfoItem.Category.Orbit, format = "F3", units = "º")] //Inclination
public MovingAverage orbitInclination = new MovingAverage();
[ValueInfoItem("#MechJeb_Eccentricity", InfoItem.Category.Orbit, format = "F3")] //Eccentricity
public MovingAverage orbitEccentricity = new MovingAverage();
[ValueInfoItem("#MechJeb_SemiMajorAxis", InfoItem.Category.Orbit, format = ValueInfoItem.SI, siSigFigs = 6, units = "m")] //Semi-major axis
public MovingAverage orbitSemiMajorAxis = new MovingAverage();
[ValueInfoItem("Celestial Longitude", InfoItem.Category.Orbit, format = "F3")]
public MovingAverage celestialLongitude = new MovingAverage();
[ValueInfoItem("#MechJeb_Latitude", InfoItem.Category.Surface, format = ValueInfoItem.ANGLE_NS)] //Latitude
public MovingAverage latitude = new MovingAverage();
[ValueInfoItem("#MechJeb_Longitude", InfoItem.Category.Surface, format = ValueInfoItem.ANGLE_EW)] //Longitude
public MovingAverage longitude = new MovingAverage();
[ValueInfoItem("#MechJeb_AngleOfAttack", InfoItem.Category.Misc, format = "F2", units = "º")] //Angle of Attack
public MovingAverage AoA = new MovingAverage();
[ValueInfoItem("#MechJeb_AngleOfSideslip", InfoItem.Category.Misc, format = "F2", units = "º")] //Angle of Sideslip
public MovingAverage AoS = new MovingAverage();
[ValueInfoItem("#MechJeb_DisplacementAngle", InfoItem.Category.Misc, format = "F2", units = "º")] //Displacement Angle
public MovingAverage displacementAngle = new MovingAverage();
public MovingAverage3d angularVelocityAvg = new MovingAverage3d(5);
// instantaneous values
public double currentPitch => rotationVesselSurface.eulerAngles.x > 180
? 360.0 - rotationVesselSurface.eulerAngles.x
: -rotationVesselSurface.eulerAngles.x;
public double currentRoll => rotationVesselSurface.eulerAngles.z > 180
? rotationVesselSurface.eulerAngles.z - 360.0
: rotationVesselSurface.eulerAngles.z;
public double currentHeading => rotationVesselSurface.eulerAngles.y;
public double radius; //distance from planet center
public double mass;
// Thrust is a vector. These are in the same frame of reference as forward and other vectors.
public Vector3d thrustVectorLastFrame;
public Vector3d thrustVectorMaxThrottle;
public Vector3d thrustVectorMinThrottle;
// Thrust in the forward direction (for historical reasons).
public double thrustAvailable => Vector3d.Dot(thrustVectorMaxThrottle, forward);
public double thrustMinimum => Vector3d.Dot(thrustVectorMinThrottle, forward);
public double thrustCurrent => Vector3d.Dot(thrustVectorLastFrame, forward);
// Forward direction of thrust (CoT-CoM).normalized
public Vector3d thrustForward;
// Acceleration in the forward direction, for when dividing by mass is too complicated.
public double maxThrustAccel => thrustAvailable / mass;
public double minThrustAccel => thrustMinimum / mass;
public double currentThrustAccel => thrustCurrent / mass;
public double maxEngineResponseTime;
public bool rcsThrust;
/* the current throttle limit, this may include transient condition such as limiting to zero due to unstable propellants in RF */
public float throttleLimit = 1;
/* the fixed throttle limit (i.e. user limited in the GUI), does not include transient conditions as limiting to zero due to unstable propellants in RF */
public float throttleFixedLimit = 1;
public double limitedMaxThrustAccel => maxThrustAccel * throttleFixedLimit + minThrustAccel * (1 - throttleFixedLimit);
public Vector3d CoT;
public Vector3d DoT;
public double CoTScalar;
public Vector3d pureDragV;
[ValueInfoItem("#MechJeb_PureDrag", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "m/s²")] //Pure Drag
public double pureDrag;
public Vector3d pureLiftV;
[ValueInfoItem("#MechJeb_PureLift", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "m/s²")] //Pure Lift
public double pureLift;
// Drag is the force (pureDrag + PureLift) applied opposite of the surface vel
public double drag;
// Drag is the force (pureDrag + PureLift) applied in the "Up" direction
public double dragUp;
// Lift is the force (pureDrag + PureLift) applied in the "Lift" direction
public double lift;
// Lift is the force (pureDrag + PureLift) applied in the "Up" direction
public double liftUp;
public Vector3d CoL;
public double CoLScalar;
[ValueInfoItem("#MechJeb_Mach", InfoItem.Category.Vessel, format = "F2")] //Mach
public double mach;
[ValueInfoItem("#MechJeb_SpeedOfSound", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "m/s")] //Speed of sound
public double speedOfSound;
[ValueInfoItem("#MechJeb_DragCoefficient", InfoItem.Category.Vessel, format = "F2")] //Drag Coefficient
public double dragCoef;
// Product of the drag surface area, drag coefficient and the physic multiplers
public double areaDrag;
public double atmosphericDensity;
[ValueInfoItem("#MechJeb_AtmosphereDensity", InfoItem.Category.Misc, format = ValueInfoItem.SI, units = "g/m³")] //Atmosphere density
public double atmosphericDensityGrams;
[ValueInfoItem("#MechJeb_MaxDynamicPressure", InfoItem.Category.Misc, format = ValueInfoItem.SI, units = "Pa")] //Max dynamic pressure
public double maxDynamicPressure;
[ValueInfoItem("#MechJeb_DynamicPressure", InfoItem.Category.Misc, format = ValueInfoItem.SI, units = "Pa")] //Dynamic pressure
public double dynamicPressure;
[ValueInfoItem("#MechJeb_IntakeAir", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "kg/s")] //Intake air
public double intakeAir;
[ValueInfoItem("#MechJeb_IntakeAirAllIntakes", InfoItem.Category.Vessel, format = ValueInfoItem.SI,
units = "kg/s")] //Intake air (all intakes open)
public double intakeAirAllIntakes;
[ValueInfoItem("#MechJeb_IntakeAirNeeded", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "kg/s")] //Intake air needed
public double intakeAirNeeded;
[ValueInfoItem("#MechJeb_intakeAirAtMax", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "kg/s")] //Intake air needed (max)
public double intakeAirAtMax;
[ValueInfoItem("#MechJeb_AngleToPrograde", InfoItem.Category.Orbit, format = "F2", units = "º")] //Angle to prograde
public double angleToPrograde;
[ValueInfoItem("#MechJeb_AerothermalFlux", InfoItem.Category.Vessel, format = ValueInfoItem.SI, units = "W/m²")] //Aerothermal flux
public double freeMolecularAerothermalFlux;
public Vector6 rcsThrustAvailable = new Vector6(); // thrust available from RCS thrusters
public Vector6 rcsTorqueAvailable = new Vector6(); // torque available from RCS thrusters
// Total torque
public Vector3d torqueAvailable;
public Vector3d torqueReactionSpeed;
// Torque from different components
public Vector6 torqueReactionWheel = new Vector6(); // torque available from Reaction wheels
//public Vector6 torqueRcs = new Vector6(); // torque available from RCS from stock code (not working properly ATM)
public Vector6 torqueControlSurface = new Vector6(); // torque available from Aerodynamic control surfaces
public Vector6 torqueGimbal = new Vector6(); // torque available from Gimbaled engines
public Vector6 torqueOthers = new Vector6(); // torque available from Mostly FAR
// Variable part of torque related to differential throttle
public Vector3d torqueDiffThrottle;
// List of parachutes
public List<ModuleParachute> parachutes = new List<ModuleParachute>();
public bool parachuteDeployed;
// Resource information keyed by resource Id.
public Dictionary<int, ResourceInfo> resources = new Dictionary<int, ResourceInfo>();
public CelestialBody mainBody;
// A convenient debug message to display in the UI
public static string message;
[GeneralInfoItem("#MechJeb_DebugString", InfoItem.Category.Misc, showInEditor = true)] //Debug String
public void DebugString()
{
GUILayout.BeginVertical();
GUILayout.Label(message);
GUILayout.EndVertical();
}
// Callbacks for external module
public delegate void VesselStatePartExtension(Part p);
public delegate void VesselStatePartModuleExtension(PartModule pm);
private readonly Dictionary<ModuleEngines, ModuleGimbal> engines = new Dictionary<ModuleEngines, ModuleGimbal>();
public List<VesselStatePartExtension> vesselStatePartExtensions = new List<VesselStatePartExtension>();
public List<VesselStatePartModuleExtension> vesselStatePartModuleExtensions = new List<VesselStatePartModuleExtension>();
public delegate double DTerminalVelocity();
private static bool reflectionInitDone;
public void InitReflection()
{
FARVesselDragCoeff = null;
FARVesselRefArea = null;
FARVesselTermVelEst = null;
FARVesselDynPres = null;
isLoadedProceduralFairing = ReflectionUtils.IsAssemblyLoaded("ProceduralFairings");
isLoadedRealFuels = ReflectionUtils.IsAssemblyLoaded("RealFuels");
isLoadedPrincipia = ReflectionUtils.IsAssemblyLoaded("principia.ksp_plugin_adapter");
if (isLoadedRealFuels)
{
Debug.Log("MechJeb: RealFuels Assembly is loaded");
RFullageSetField = ReflectionUtils.GetFieldByReflection("RealFuels", "RealFuels.ModuleEnginesRF", "ullageSet");
if (RFullageSetField == null)
{
Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.ModuleEnginesRF has no ullageSet field, disabling RF");
isLoadedRealFuels = false;
}
RFGetUllageStabilityMethod = ReflectionUtils.GetMethodByReflection("RealFuels", "RealFuels.Ullage.UllageSet", "GetUllageStability",
BindingFlags.Public | BindingFlags.Instance);
if (RFGetUllageStabilityMethod == null)
{
Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.Ullage.UllageSet has no GetUllageStability method, disabling RF");
isLoadedRealFuels = false;
}
RFignitionsField = ReflectionUtils.GetFieldByReflection("RealFuels", "RealFuels.ModuleEnginesRF", "ignitions");
if (RFignitionsField == null)
{
Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.ModuleEnginesRF has no ignitions field, disabling RF");
isLoadedRealFuels = false;
}
RFignitedField = ReflectionUtils.GetFieldByReflection("RealFuels", "RealFuels.ModuleEnginesRF", "ignited",
BindingFlags.NonPublic | BindingFlags.Instance);
if (RFignitedField == null)
{
Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.ModuleEnginesRF has no ignited field, disabling RF");
isLoadedRealFuels = false;
}
RFullageField = ReflectionUtils.GetFieldByReflection("RealFuels", "RealFuels.ModuleEnginesRF", "ullage");
if (RFullageField == null)
{
Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.ModuleEnginesRF has no ullage field, disabling RF");
isLoadedRealFuels = false;
}
FieldInfo RFveryStableField = ReflectionUtils.GetFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "veryStable",
BindingFlags.NonPublic | BindingFlags.Static);
if (RFveryStableField == null)
{
Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.Ullage.UllageSimulator has no veryStable field, disabling RF");
isLoadedRealFuels = false;
}
try
{
RFveryStableValue = (double)RFveryStableField.GetValue(null);
}
catch (Exception e1)
{
Debug.Log(
"MechJeb BUG Exception thrown while getting veryStable value from RealFuels, ullage integration disabled: " + e1.Message);
isLoadedRealFuels = false;
return;
}
FieldInfo RFstableField = ReflectionUtils.GetFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "stable",
BindingFlags.NonPublic | BindingFlags.Static);
if (RFstableField == null)
{
Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.Ullage.UllageSimulator has no stable field, disabling RF");
isLoadedRealFuels = false;
}
try
{
RFstableValue = (double)RFstableField.GetValue(null);
}
catch (Exception e2)
{
Debug.Log("MechJeb BUG Exception thrown while getting stable value from RealFuels, ullage integration disabled: " + e2.Message);
isLoadedRealFuels = false;
return;
}
FieldInfo RFriskyField = ReflectionUtils.GetFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "risky",
BindingFlags.NonPublic | BindingFlags.Static);
if (RFriskyField == null)
{
Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.Ullage.UllageSimulator has no risky field, disabling RF");
isLoadedRealFuels = false;
}
try
{
RFriskyValue = (double)RFriskyField.GetValue(null);
}
catch (Exception e3)
{
Debug.Log("MechJeb BUG Exception thrown while getting risky value from RealFuels, ullage integration disabled: " + e3.Message);
isLoadedRealFuels = false;
return;
}
FieldInfo RFveryRiskyField = ReflectionUtils.GetFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "veryRisky",
BindingFlags.NonPublic | BindingFlags.Static);
if (RFveryRiskyField == null)
{
Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.Ullage.UllageSimulator has no veryRisky field, disabling RF");
isLoadedRealFuels = false;
}
try
{
RFveryRiskyValue = (double)RFveryRiskyField.GetValue(null);
}
catch (Exception e4)
{
Debug.Log("MechJeb BUG Exception thrown while getting veryRisky value from RealFuels, ullage integration disabled: " +
e4.Message);
isLoadedRealFuels = false;
return;
}
FieldInfo RFunstableField = ReflectionUtils.GetFieldByReflection("RealFuels", "RealFuels.Ullage.UllageSimulator", "unstable",
BindingFlags.NonPublic | BindingFlags.Static);
if (RFunstableField == null)
{
Debug.Log("MechJeb BUG: RealFuels loaded, but RealFuels.Ullage.UllageSimulator has no unstable field, disabling RF");
isLoadedRealFuels = false;
}
try
{
RFunstableValue = (double)RFunstableField.GetValue(null);
}
catch (Exception e5)
{
Debug.Log("MechJeb BUG Exception thrown while getting unstable value from RealFuels, ullage integration disabled: " + e5.Message);
isLoadedRealFuels = false;
return;
}
if (isLoadedRealFuels)
{
Debug.Log("MechJeb: RealFuels Assembly is wired up properly");
}
}
isLoadedFAR = ReflectionUtils.IsAssemblyLoaded("FerramAerospaceResearch");
if (isLoadedFAR)
{
var farNames = new List<string> { "VesselDragCoeff", "VesselRefArea", "VesselTermVelEst", "VesselDynPres" };
foreach (string name in farNames)
{
MethodInfo methodInfo = ReflectionUtils.GetMethodByReflection(
"FerramAerospaceResearch",
"FerramAerospaceResearch.FARAPI",
name,
BindingFlags.Public | BindingFlags.Static,
new[] { typeof(Vessel) }
);
if (methodInfo == null)
{
Debug.Log("MJ BUG: FAR loaded, but FerramAerospaceResearch.FARAPI has no " + name + " method. Disabling FAR");
isLoadedFAR = false;
}
else
{
typeof(VesselState).GetField("FAR" + name, BindingFlags.NonPublic | BindingFlags.Static).SetValue(null,
(FARVesselDelegate)Delegate.CreateDelegate(typeof(FARVesselDelegate), methodInfo));
}
}
MethodInfo FARCalculateVesselAeroForcesMethodInfo = ReflectionUtils.GetMethodByReflection(
"FerramAerospaceResearch",
"FerramAerospaceResearch.FARAPI",
"CalculateVesselAeroForces",
BindingFlags.Public | BindingFlags.Static,
new[] { typeof(Vessel), typeof(Vector3).MakeByRefType(), typeof(Vector3).MakeByRefType(), typeof(Vector3), typeof(double) }
);
if (FARCalculateVesselAeroForcesMethodInfo == null)
{
Debug.Log("MJ BUG: FAR loaded, but FerramAerospaceResearch.FARAPI has no CalculateVesselAeroForces method, disabling FAR");
isLoadedFAR = false;
}
else
{
FARCalculateVesselAeroForces =
(FARCalculateVesselAeroForcesDelegate)Delegate.CreateDelegate(typeof(FARCalculateVesselAeroForcesDelegate),
FARCalculateVesselAeroForcesMethodInfo);
}
}
reflectionInitDone = true;
}
public VesselState()
{
if (!reflectionInitDone && HighLogic.LoadedSceneIsGame)
InitReflection();
if (isLoadedFAR)
{
TerminalVelocityCall = TerminalVelocityFAR;
}
else
{
TerminalVelocityCall = TerminalVelocityStockKSP;
}
}
//public static bool SupportsGimbalExtension<T>() where T : PartModule
//{
// return gimbalExtDict.ContainsKey(typeof(T));
//}
//
//public static void AddGimbalExtension<T>(GimbalExt gimbalExtension) where T : PartModule
//{
// gimbalExtDict[typeof(T)] = gimbalExtension;
//}
public bool Update(Vessel vessel)
{
if (time == Planetarium.GetUniversalTime())
return true;
if (vessel.rootPart.rb == null)
return false; //if we try to update before rigidbodies exist we spam the console with NullPointerExceptions.
TestStuff(vessel);
UpdateVelocityAndCoM(vessel);
UpdateBasicInfo(vessel);
UpdateRCSThrustAndTorque(vessel);
enginesWrappers.Clear();
einfo.Update(CoM, vessel);
iinfo.Update();
AnalyzeParts(vessel, einfo, iinfo);
UpdateResourceRequirements(einfo, iinfo);
ToggleRCSThrust(vessel);
UpdateMoIAndAngularMom(vessel);
return true;
}
private void TestStuff(Vessel vessel)
{
//int partCount = vessel.parts.Count;
//for (int index = 0; index < partCount; ++index)
//{
// if (!vessel.parts[index].DragCubes.None)
// vessel.parts[index].DragCubes.SetDragWeights();
//}
//for (int index = 0; index < partCount; ++index)
//{
// if (!vessel.parts[index].DragCubes.None)
// vessel.parts[index].DragCubes.SetPartOcclusion();
//}
//for (int index = 0; index < partCount; ++index)
//{
// Part part = vessel.parts[index];
// if (!part.DragCubes.None)
// part.DragCubes.SetDrag(part.dragVectorDirLocal, 0.1f);
//}
//cube = new DragCubeList();
//cube.ClearCubes();
//for (int index = 0; index < partCount; ++index)
//{
// Part part = vessel.parts[index];
// if (!part.DragCubes.None)
// {
// for (int face = 0; face < 6; face++)
// {
// //cube.WeightedArea[face] += part.DragCubes.WeightedArea[face];
// cube.WeightedDrag[face] += part.DragCubes.WeightedDrag[face];
// cube.AreaOccluded[face] += part.DragCubes.AreaOccluded[face];
// }
// }
//}
//
//cube.SetDrag(vessel.srf_velocity, (float)vessel.mach);
//
//double dragScale = cube.AreaDrag * PhysicsGlobals.DragCubeMultiplier;
//SimulatedVessel simVessel = SimulatedVessel.New(vessel);
//MechJebCore.print("KPA " + vessel.dynamicPressurekPa.ToString("F9"));
//Vector3 localVel = vessel.GetTransform().InverseTransformDirection( vessel.srf_velocity );
//Vector3 localVel = vessel.GetTransform().InverseTransformDirection( vessel.rigidbody.velocity + Krakensbane.GetFrameVelocity());
//MechJebCore.print(MuUtils.PrettyPrint(localVel));
//Vector3 simDrag = simVessel.Drag(localVel,
// (float)(0.0005 * vessel.atmDensity * vessel.srf_velocity.sqrMagnitude),
// (float)vessel.mach);
//
//
//Vector3 simLift = simVessel.Lift(vessel.rigidbody.velocity + Krakensbane.GetFrameVelocity(),
// (float)(0.0005 * vessel.atmDensity * vessel.srf_velocity.sqrMagnitude),
// (float)vessel.mach);
//
//dragScalar = simDrag.magnitude;
//
//liftScalar = simLift.magnitude;
//double exposedArea = 0;
//double skinExposedArea = 0;
//double radiativeArea = 0;
//foreach (Part part in vessel.Parts)
//{
// exposedArea += part.exposedArea;
// skinExposedArea += part.skinExposedArea;
// radiativeArea += part.radiativeArea;
// //MechJebCore.print(part.name + " " + part.exposedArea.ToString("F4") + " " + part.skinExposedArea.ToString("F4"));
//}
//MechJebCore.print(exposedArea.ToString("F2") + " " + skinExposedArea.ToString("F2") + " " + radiativeArea.ToString("F2"));
//message = "\nPools :\n" +
// SimulatedVessel.PoolSize + " SimulatedVessel\n" +
// SimulatedPart.PoolSize + " SimulatedPart\n" +
// SimulatedParachute.PoolSize + " SimulatedParachute\n" +
// ListPool<AbsoluteVector>.Instance.Size + " AbsoluteVector\n" +
// ReentrySimulation.PoolSize + " ReentrySimulation\n" +
// ReentrySimulation.Result.PoolSize + " Result\n" +
// SimulatedPart.DragCubePool.Instance.Size + " DragCubePool\n" +
// FuelNode.PoolSize + " FuelNode\n";
//ListPool<AbsoluteVector>.Instance.
}
// TODO memo for later. egg found out that vessel.pos is actually 1 frame in the future while vessel.obt_vel is not.
// This should have changed in 1.1
// This most likely has some impact on the code.
private void UpdateVelocityAndCoM(Vessel vessel)
{
mass = vessel.totalMass;
CoM = vessel.CoMD;
orbitalVelocity = vessel.obt_velocity;
orbitalPosition = CoM - vessel.mainBody.position;
}
// Calculate a bunch of simple quantities each frame.
private void UpdateBasicInfo(Vessel vessel)
{
time = Planetarium.GetUniversalTime();
deltaT = TimeWarp.fixedDeltaTime;
//CoM = °;
up = orbitalPosition.normalized;
Rigidbody rigidBody = vessel.rootPart.rb;
if (rigidBody != null) rootPartPos = rigidBody.position;
north = vessel.north;
east = vessel.east;
forward = vessel.GetTransform().up;
rotationSurface = Quaternion.LookRotation(north, up);
rotationVesselSurface =
Quaternion.Inverse(Quaternion.Euler(90, 0, 0) * Quaternion.Inverse(vessel.GetTransform().rotation) * rotationSurface);
surfaceVelocity = orbitalVelocity - vessel.mainBody.getRFrmVel(CoM);
velocityMainBodySurface = rotationSurface * surfaceVelocity;
horizontalOrbit = Vector3d.Exclude(up, orbitalVelocity).normalized;
horizontalSurface = Vector3d.Exclude(up, surfaceVelocity).normalized;
angularVelocity = vessel.angularVelocity;
radialPlusSurface = Vector3d.Exclude(surfaceVelocity, up).normalized;
radialPlus = Vector3d.Exclude(orbitalVelocity, up).normalized;
normalPlusSurface = -Vector3d.Cross(radialPlusSurface, surfaceVelocity.normalized);
normalPlus = -Vector3d.Cross(radialPlus, orbitalVelocity.normalized);
mach = vessel.mach;
gravityForce = FlightGlobals.getGeeForceAtPosition(CoM); // TODO vessel.gravityForPos or vessel.gravityTrue
localg = gravityForce.magnitude;
speedOrbital.Value = orbitalVelocity.magnitude;
speedSurface.Value = surfaceVelocity.magnitude;
speedVertical.Value = Vector3d.Dot(surfaceVelocity, up);
speedSurfaceHorizontal.Value =
Vector3d.Exclude(up, surfaceVelocity).magnitude; //(velocityVesselSurface - (speedVertical * up)).magnitude;
speedOrbitHorizontal = (orbitalVelocity - speedVertical * up).magnitude;
// Angle of Attack, angle between surface velocity and the ship-nose vector (KSP "up" vector) in the plane that has no ship-right/left in it
var srfProj = Vector3.ProjectOnPlane(surfaceVelocity.normalized, vessel.ReferenceTransform.right);
double tmpAoA = UtilMath.Rad2Deg * Math.Atan2(Vector3.Dot(srfProj.normalized, vessel.ReferenceTransform.forward),
Vector3.Dot(srfProj.normalized, vessel.ReferenceTransform.up));
AoA.Value = double.IsNaN(tmpAoA) || speedSurface.Value < 0.01 ? 0 : tmpAoA;
// Angle of Sideslip, angle between surface velocity and the ship-nose vector (KSP "up" vector) in the plane that has no ship-top/bottom in it (KSP "forward"/"back")
srfProj = Vector3.ProjectOnPlane(surfaceVelocity.normalized, vessel.ReferenceTransform.forward);
double tmpAoS = UtilMath.Rad2Deg * Math.Atan2(Vector3.Dot(srfProj.normalized, vessel.ReferenceTransform.right),
Vector3.Dot(srfProj.normalized, vessel.ReferenceTransform.up));
AoS.Value = double.IsNaN(tmpAoS) || speedSurface.Value < 0.01 ? 0 : tmpAoS;
// Displacement Angle, angle between surface velocity and the ship-nose vector (KSP "up" vector) -- ignores roll of the craft (0 to 180 degrees)
double tempAoD = UtilMath.Rad2Deg *
Math.Acos(MuUtils.Clamp(Vector3.Dot(vessel.ReferenceTransform.up, surfaceVelocity.normalized), -1, 1));
displacementAngle.Value = double.IsNaN(tempAoD) || speedSurface.Value < 0.01 ? 0 : tempAoD;
vesselHeading.Value = currentHeading;
vesselPitch.Value = currentPitch;
vesselRoll.Value = currentRoll;
altitudeASL.Value = vessel.mainBody.GetAltitude(CoM);
surfaceAltitudeASL = vessel.mainBody.pqsController != null ? vessel.pqsAltitude : 0d;
if (vessel.mainBody.ocean && surfaceAltitudeASL < 0) surfaceAltitudeASL = 0;
altitudeTrue.Value = altitudeASL - surfaceAltitudeASL;
// altitudeBottom will be recomputed if someone requests it.
altitudeBottomIsCurrent = false;
double atmosphericPressure = FlightGlobals.getStaticPressure(altitudeASL, vessel.mainBody);
//if (atmosphericPressure < vessel.mainBody.atmosphereMultiplier * 1e-6) atmosphericPressure = 0;
double temperature = FlightGlobals.getExternalTemperature(altitudeASL);
atmosphericDensity = FlightGlobals.getAtmDensity(atmosphericPressure, temperature);
atmosphericDensityGrams = atmosphericDensity * 1000;
if (isLoadedFAR)
{
dynamicPressure = FARVesselDynPres(vessel) * 1000;
}
else
{
dynamicPressure = vessel.dynamicPressurekPa * 1000;
}
if (dynamicPressure > maxDynamicPressure)
maxDynamicPressure = dynamicPressure;
freeMolecularAerothermalFlux = 0.5 * atmosphericDensity * speedSurface * speedSurface * speedSurface;
speedOfSound = vessel.speedOfSound;
orbitApA.Value = vessel.orbit.ApA;
orbitPeA.Value = vessel.orbit.PeA;
orbitPeriod.Value = vessel.orbit.period;
orbitTimeToAp.Value = vessel.orbit.timeToAp;
orbitTimeToPe.Value = vessel.orbit.timeToPe;
orbitLAN.Value = vessel.orbit.LAN;
orbitArgumentOfPeriapsis.Value = vessel.orbit.argumentOfPeriapsis;
orbitInclination.Value = vessel.orbit.inclination;
orbitEccentricity.Value = vessel.orbit.eccentricity;
orbitSemiMajorAxis.Value = vessel.orbit.semiMajorAxis;
celestialLongitude.Value = Planetarium.right.AngleInPlane(-Planetarium.up, orbitalPosition);
latitude.Value = vessel.mainBody.GetLatitude(CoM);
longitude.Value = MuUtils.ClampDegrees180(vessel.mainBody.GetLongitude(CoM));
if (vessel.mainBody != Planetarium.fetch.Sun)
{
Vector3d prograde = vessel.mainBody.orbit.getOrbitalVelocityAtUT(time).xzy;
Vector3d normal = vessel.mainBody.orbit.GetOrbitNormal().xzy;
angleToPrograde = MuUtils.ClampDegrees360((vessel.orbit.inclination > 90 || vessel.orbit.inclination < -90 ? 1 : -1) *
orbitalPosition.AngleInPlane(normal, prograde));
}
else
{
angleToPrograde = 0;
}
mainBody = vessel.mainBody;
radius = orbitalPosition.magnitude;
vesselRef = vessel;
}
private void UpdateRCSThrustAndTorque(Vessel vessel)
{
rcsThrustAvailable.Reset();
rcsTorqueAvailable.Reset();
//torqueRcs.Reset();
if (!vessel.ActionGroups[KSPActionGroup.RCS])
return;
MechJebModuleRCSBalancer rcsbal = vessel.GetMasterMechJeb().Rcsbal;
if (rcsbal.Enabled)
{
Vector3d rot = Vector3d.zero;
for (int i = 0; i < Vector6.Values.Length; i++)
{
Vector6.Direction dir6 = Vector6.Values[i];
Vector3d dir = Vector6.Directions[(int)dir6];
double[] throttles;
List<RCSSolver.Thruster> thrusters;
rcsbal.GetThrottles(dir, out throttles, out thrusters);
if (throttles != null)
{
for (int j = 0; j < throttles.Length; j++)
{
if (throttles[j] > 0)
{
Vector3d force = thrusters[j].GetThrust(dir, rot);
rcsThrustAvailable.Add(
vessel.GetTransform().InverseTransformDirection(dir * Vector3d.Dot(force * throttles[j], dir)));
// Are we missing an rcsTorqueAvailable calculation here?
}
}
}
}
}
Vector3d movingCoM = vessel.CurrentCoM;
for (int i = 0; i < vessel.parts.Count; i++)
{
Part p = vessel.parts[i];
for (int m = 0; m < p.Modules.Count; m++)
{
var rcs = p.Modules[m] as ModuleRCS;
if (rcs == null)
continue;
//Vector3 pos;
//Vector3 neg;
//rcs.GetPotentialTorque(out pos, out neg);
//torqueRcs.Add(pos);
//torqueRcs.Add(neg);
//if (rcsbal.enabled)
// continue;
if (!p.ShieldedFromAirstream && rcs.rcsEnabled && rcs.isEnabled && !rcs.isJustForShow && !rcs.flameout && rcs.rcs_active)
{
var attitudeControl = new Vector3(rcs.enablePitch ? 1 : 0, rcs.enableRoll ? 1 : 0, rcs.enableYaw ? 1 : 0);
var translationControl = new Vector3(rcs.enableX ? 1 : 0f, rcs.enableZ ? 1 : 0, rcs.enableY ? 1 : 0);
for (int j = 0; j < rcs.thrusterTransforms.Count; j++)
{
Transform t = rcs.thrusterTransforms[j];
// Borrowed from kOS: As of KSP 1.11.x, RCS parts now use part variants. To prevent
// counting torque as if the superset of all variant nozzles were present, the ones not
// currently active have to be culled out here, since KSP isn't culling them out itself when
// it populates ModuleRCS.thrusterTransforms:
if (!t.gameObject.activeInHierarchy)
continue;
Vector3d thrusterPosition = t.position - movingCoM;
Vector3d thrustDirection = rcs.useZaxis ? -t.forward : -t.up;
float power = rcs.thrusterPower * rcs.thrustPercentage * 0.01f;
if (FlightInputHandler.fetch.precisionMode)
{
if (rcs.useLever)
{
float lever = rcs.GetLeverDistance(t, thrustDirection, movingCoM);
if (lever > 1)
{
power = power / lever;
}
}
else
{
power *= rcs.precisionFactor;
}
}
Vector3d thrusterThrust = thrustDirection * power;
// This is a cheap hack to get rcsTorque with the RCS balancer active.
if (!rcsbal.Enabled)
{
rcsThrustAvailable.Add(Vector3.Scale(vessel.GetTransform().InverseTransformDirection(thrusterThrust),
translationControl));
}
Vector3d thrusterTorque = Vector3.Cross(thrusterPosition, thrusterThrust);
// Convert in vessel local coordinate
rcsTorqueAvailable.Add(Vector3.Scale(vessel.GetTransform().InverseTransformDirection(thrusterTorque), attitudeControl));
//rcsThrustAvailable.Add(Vector3.Scale(vessel.GetTransform().InverseTransformDirection(thrusterThrust), translationControl));
}
}
}
}
}
[GeneralInfoItem("#MechJeb_RCSTranslation", InfoItem.Category.Vessel, showInEditor = true)] //RCS Translation
public void RCSTranslation()
{
GUILayout.BeginVertical();
GUILayout.Label(Localizer.Format("#MechJeb_RCSTranslation")); //"RCS Translation"
GUILayout.BeginHorizontal();
GUILayout.Label("Pos", GUILayout.ExpandWidth(true)); //
GUILayout.Label(MuUtils.PrettyPrint(rcsThrustAvailable.Positive), GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("Neg", GUILayout.ExpandWidth(true)); //
GUILayout.Label(MuUtils.PrettyPrint(rcsThrustAvailable.Negative), GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal();
GUILayout.EndVertical();
}
[GeneralInfoItem("#MechJeb_RCSTorque", InfoItem.Category.Vessel, showInEditor = true)] //RCS Torque
public void RCSTorque()
{
GUILayout.BeginVertical();
GUILayout.Label(Localizer.Format("#MechJeb_RCSTorque")); //"RCS Torque"
GUILayout.BeginHorizontal();
GUILayout.Label("Pos", GUILayout.ExpandWidth(true));
GUILayout.Label(MuUtils.PrettyPrint(rcsTorqueAvailable.Positive), GUILayout.ExpandWidth(false));
//GUILayout.Label(MuUtils.PrettyPrint(torqueRcs.positive), GUILayout.ExpandWidth(false));
GUILayout.EndHorizontal();