/
MechJebCore.cs
1322 lines (1112 loc) · 50.6 KB
/
MechJebCore.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.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using KSP.Localization;
using UnityEngine;
using UnityEngine.Profiling;
using UnityToolbag;
using Debug = UnityEngine.Debug;
using File = KSP.IO.File;
using Logger = MechJebLib.Utils.Logger;
namespace MuMech
{
public class MechJebCore : PartModule, IComparable<MechJebCore>
{
private readonly List<ComputerModule> _unorderedComputerModules = new List<ComputerModule>();
private readonly List<ComputerModule> _modulesToLoad = new List<ComputerModule>();
private readonly Dictionary<Type, List<ComputerModule>> _sortedModules = new Dictionary<Type, List<ComputerModule>>();
private readonly Dictionary<object, List<DisplayModule>> _sortedDisplayModules = new Dictionary<object, List<DisplayModule>>();
// Reference to the parts base config. See Onload for explanation
private static readonly Dictionary<string, ConfigNode> _savedConfig = new Dictionary<string, ConfigNode>();
private readonly List<Callback> _postDrawQueue = new List<Callback>();
private static List<Type> _moduleRegistry;
private bool _ready;
public MechJebModuleGuidanceController Guidance;
public MechJebModulePVGGlueBall Glueball;
public MechJebModuleAttitudeController Attitude;
public MechJebModuleStagingController Staging;
public MechJebModuleThrustController Thrust;
public MechJebModuleTargetController Target;
public MechJebModuleWarpController Warp;
public MechJebModuleRCSController RCS;
public MechJebModuleRCSBalancer Rcsbal;
public MechJebModuleRoverController Rover;
public MechJebModuleNodeExecutor Node;
public MechJebModuleSolarPanelController Solarpanel;
public MechJebModuleDeployableAntennaController AntennaControl;
public MechJebModuleLandingAutopilot Landing;
public MechJebModuleSettings Settings;
public MechJebModuleAirplaneAutopilot Airplane;
public MechJebModuleStageStats StageStats;
public MechJebModuleAscentSettings AscentSettings;
public MechJebModuleSpinupController Spinup;
public MechJebModuleAscentBaseAutopilot Ascent => AscentSettings.AscentAutopilot;
public readonly VesselState VesselState = new VesselState();
[KSPField(isPersistant = true, guiActive = true, guiActiveEditor = true, guiName = "MechJeb")]
[UI_Toggle(disabledText = "#MechJeb_Disabled", enabledText = "#MechJeb_Enabled")] //DisabledEnabled
public bool running = true;
private Vessel _controlledVessel; //keep track of which vessel we've added our onFlyByWire callback to
public string version = "";
private bool _deactivateControl;
private float _currentThrottle; // To maintain throttle when controls deactivated
[UsedImplicitly]
public MechJebCore MasterMechJeb => vessel.GetMasterMechJeb();
// Allow other mods to kill MJ ability to control vessel (RemoteTech, RO...)
[UsedImplicitly]
public bool DeactivateControl
{
get
{
MechJebCore mj = vessel.GetMasterMechJeb();
return !(mj is null) && vessel.GetMasterMechJeb()._deactivateControl;
}
set
{
MechJebCore mj = vessel.GetMasterMechJeb();
if (mj == null) return;
if (value && !mj._deactivateControl)
_controlledVessel.ctrlState.mainThrottle = _currentThrottle;
mj._deactivateControl = value;
}
}
[KSPField(isPersistant = false)]
public string blacklist = "";
[KSPField]
private ConfigNode _partSettings;
[KSPField(isPersistant = false)]
public bool eduMode;
public bool RssMode => Settings.rssMode;
public bool ShowGui { get; private set; } = true;
[KSPAction("#MechJeb_OrbitPrograde")] //Orbit Prograde
public void OnOrbitProgradeAction(KSPActionParam param)
{
EngageSmartASSOrbitalControl(MechJebModuleSmartASS.Target.PROGRADE);
}
[KSPAction("#MechJeb_OrbitRetrograde")] //Orbit Retrograde
public void OnOrbitRetrogradeAction(KSPActionParam param)
{
EngageSmartASSOrbitalControl(MechJebModuleSmartASS.Target.RETROGRADE);
}
[KSPAction("#MechJeb_OrbitNormal")] //Orbit Normal
public void OnOrbitNormalAction(KSPActionParam param)
{
EngageSmartASSOrbitalControl(MechJebModuleSmartASS.Target.NORMAL_PLUS);
}
[KSPAction("#MechJeb_OrbitAntinormal")] //Orbit Antinormal
public void OnOrbitAntinormalAction(KSPActionParam param)
{
EngageSmartASSOrbitalControl(MechJebModuleSmartASS.Target.NORMAL_MINUS);
}
[KSPAction("#MechJeb_OrbitRadialIn")] //Orbit Radial In
public void OnOrbitRadialInAction(KSPActionParam param)
{
EngageSmartASSOrbitalControl(MechJebModuleSmartASS.Target.RADIAL_MINUS);
}
[KSPAction("#MechJeb_OrbitRadialOut")] //Orbit Radial Out
public void OnOrbitRadialOutAction(KSPActionParam param)
{
EngageSmartASSOrbitalControl(MechJebModuleSmartASS.Target.RADIAL_PLUS);
}
[KSPAction("#MechJeb_OrbitKillRotation")] //Orbit Kill Rotation
public void OnKillRotationAction(KSPActionParam param)
{
EngageSmartASSOrbitalControl(MechJebModuleSmartASS.Target.KILLROT);
}
[KSPAction("#MechJeb_DeactivateSmartACS")] //Deactivate SmartACS
public void OnDeactivateSmartASSAction(KSPActionParam param)
{
EngageSmartASSOrbitalControl(MechJebModuleSmartASS.Target.OFF);
}
[KSPAction("#MechJeb_LandSomewhere")] //Land somewhere
public void OnLandsomewhereAction(KSPActionParam param)
{
LandSomewhere();
}
[KSPAction("#MechJeb_LandatKSC")] //Land at KSC
public void OnLandTargetAction(KSPActionParam param)
{
LandTarget();
}
private void LandTarget()
{
MechJebCore masterMechJeb = vessel.GetMasterMechJeb();
if (masterMechJeb == null) return;
MechJebModuleLandingGuidance moduleLandingGuidance = GetComputerModule<MechJebModuleLandingGuidance>();
moduleLandingGuidance?.SetAndLandTargetKSC();
}
private void LandSomewhere()
{
MechJebCore masterMechJeb = vessel.GetMasterMechJeb();
if (masterMechJeb == null) return;
MechJebModuleLandingGuidance moduleLandingGuidance = GetComputerModule<MechJebModuleLandingGuidance>();
moduleLandingGuidance?.LandSomewhere();
}
private void EngageSmartASSOrbitalControl(MechJebModuleSmartASS.Target smartassTarget)
{
MechJebCore masterMechJeb = vessel.GetMasterMechJeb();
if (masterMechJeb == null)
{
Debug.LogError(
Localizer.Format("#MechJeb_LogError_msg0")); //"MechJeb couldn't find the master MechJeb module for the current vessel."
return;
}
MechJebModuleSmartASS masterSmartASS = masterMechJeb.GetComputerModule<MechJebModuleSmartASS>();
if (masterSmartASS is { hidden: false })
{
masterSmartASS.mode = MechJebModuleSmartASS.Mode.ORBITAL;
masterSmartASS.target = smartassTarget;
masterSmartASS.Engage();
}
else
{
Debug.LogError(
Localizer.Format(
"#MechJeb_LogError_msg1")); //"MechJeb couldn't find MechJebModuleSmartASS for orbital control via action group."
}
}
[KSPAction("#MechJeb_PANIC")] //PANIC!
public void OnPanicAction(KSPActionParam param)
{
MechJebCore masterMechJeb = vessel.GetMasterMechJeb();
if (masterMechJeb == null) return;
MechJebModuleTranslatron moduleTranslatron = masterMechJeb.GetComputerModule<MechJebModuleTranslatron>();
if (moduleTranslatron is { hidden: false })
moduleTranslatron.PanicSwitch();
}
[KSPAction("#MechJeb_TranslatronOFF")] //Translatron OFF
public void OnTranslatronOffAction(KSPActionParam param)
{
EngageTranslatronControl(MechJebModuleThrustController.TMode.OFF);
}
[KSPAction("#MechJeb_TranslatronKeepVert")] //Translatron Keep Vert
public void OnTranslatronKeepVertAction(KSPActionParam param)
{
EngageTranslatronControl(MechJebModuleThrustController.TMode.KEEP_VERTICAL);
}
[KSPAction("#MechJeb_TranslatronZerospeed")] //Translatron Zero speed
public void OnTranslatronZeroSpeedAction(KSPActionParam param)
{
SetTranslatronSpeed(0);
}
[KSPAction("#MechJeb_TranslatronPlusspeed")] //Translatron +1 speed
public void OnTranslatronPlusOneSpeedAction(KSPActionParam param)
{
SetTranslatronSpeed(1, true);
}
[KSPAction("#MechJeb_TranslatronMinusspeed")] //Translatron -1 speed
public void OnTranslatronMinusOneSpeedAction(KSPActionParam param)
{
SetTranslatronSpeed(-1, true);
}
[KSPAction("#MechJeb_TranslatronToggleHS")] //Translatron Toggle H/S
public void OnTranslatronToggleHSAction(KSPActionParam param)
{
MechJebCore masterMechJeb = vessel.GetMasterMechJeb();
if (masterMechJeb != null)
{
MechJebModuleTranslatron moduleTranslatron = masterMechJeb.GetComputerModule<MechJebModuleTranslatron>();
if (moduleTranslatron is { hidden: false })
{
Thrust.trans_kill_h = !Thrust.trans_kill_h;
}
else
{
Debug.LogError(
Localizer.Format(
"#MechJeb_LogError_msg2")); //"MechJeb couldn't find MechJebModuleTranslatron for translatron control via action group."
}
}
else
{
Debug.LogError("MechJeb couldn't find the master MechJeb module for the current vessel.");
}
}
[KSPAction("#MechJeb_AscentAPtoggle")] //Ascent AP toggle
public void OnAscentAPToggleAction(KSPActionParam param)
{
MechJebCore masterMechJeb = vessel.GetMasterMechJeb();
MechJebModuleAscentBaseAutopilot autopilot = masterMechJeb.AscentSettings.AscentAutopilot;
MechJebModuleAscentMenu ascentMenu = GetComputerModule<MechJebModuleAscentMenu>();
if (autopilot == null || ascentMenu == null)
return;
if (autopilot.Enabled)
autopilot.aUsers.Remove(ascentMenu);
else
autopilot.Users.Add(ascentMenu);
}
private void EngageTranslatronControl(MechJebModuleThrustController.TMode mode)
{
MechJebCore masterMechJeb = vessel.GetMasterMechJeb();
if (masterMechJeb == null)
{
Debug.LogError("MechJeb couldn't find the master MechJeb module for the current vessel.");
return;
}
MechJebModuleTranslatron moduleTranslatron = masterMechJeb.GetComputerModule<MechJebModuleTranslatron>();
if (moduleTranslatron is { hidden: false })
{
if (Thrust.Users.Count > 1 && !Thrust.Users.Contains(moduleTranslatron))
return;
moduleTranslatron.SetMode(mode);
}
else
{
Debug.LogError("MechJeb couldn't find MechJebModuleTranslatron for translatron control via action group.");
}
}
private void SetTranslatronSpeed(float speed, bool relative = false)
{
MechJebCore masterMechJeb = vessel.GetMasterMechJeb();
if (masterMechJeb == null)
{
Debug.LogError("MechJeb couldn't find the master MechJeb module for the current vessel.");
return;
}
MechJebModuleTranslatron moduleTranslatron = masterMechJeb.GetComputerModule<MechJebModuleTranslatron>();
if (moduleTranslatron is { hidden: false })
Thrust.trans_spd_act = (relative ? Thrust.trans_spd_act : 0) + speed;
else
Debug.LogError("MechJeb couldn't find MechJebModuleTranslatron for translatron control via action group.");
}
private bool _weLockedInputs;
private float _lastSettingsSaveTime;
private bool _wasMasterAndFocus;
private static Vessel _lastFocus;
public bool someModuleAreLocked; // True if any module was locked by the R&D system
//Returns whether the vessel we've registered OnFlyByWire with is the correct one.
//If it isn't the correct one, fixes it before returning false
private bool CheckControlledVessel()
{
if (_controlledVessel == vessel) return true;
//else we have an onFlyByWire callback registered with the wrong vessel:
//handle vessel changes due to docking/undocking
if (_controlledVessel != null) _controlledVessel.OnFlyByWire -= OnFlyByWire;
if (vessel != null)
{
vessel.OnFlyByWire -= OnFlyByWire; //just a safety precaution to avoid duplicates
vessel.OnFlyByWire += OnFlyByWire;
}
_controlledVessel = vessel;
return false;
}
[UsedImplicitly]
public int GetImportance()
{
return part.State == PartStates.DEAD ? 0 : GetInstanceID();
}
public int CompareTo(MechJebCore other)
{
if (other == null) return 1;
return GetImportance().CompareTo(other.GetImportance());
}
public T GetComputerModule<T>() where T : ComputerModule
{
for (int i = 0; i < _unorderedComputerModules.Count; i++)
{
ComputerModule pm = _unorderedComputerModules[i];
if (pm is T module)
return module;
}
return null;
}
// The pure generic version was creating too much garbage
public List<ComputerModule> GetComputerModules<T>() where T : ComputerModule
{
Type key = typeof(T);
if (_sortedModules.TryGetValue(key, out List<ComputerModule> value))
return value;
_sortedModules[key] = value = _unorderedComputerModules.OfType<T>().Cast<ComputerModule>().OrderBy(m => m).ToList();
return value;
}
// Added because the generic version eats memory like candy when casting from ComputerModule to DisplayModule (.Cast<T>())
public List<DisplayModule> GetDisplayModules(IComparer<DisplayModule> comparer)
{
if (_sortedDisplayModules.TryGetValue(comparer, out List<DisplayModule> value))
return value;
_sortedDisplayModules[comparer] = value = _unorderedComputerModules.OfType<DisplayModule>().OrderBy(m => m, comparer).ToList();
return value;
}
[UsedImplicitly]
public ComputerModule GetComputerModule(string type)
{
return _unorderedComputerModules.FirstOrDefault(a => a.GetType().Name.ToLowerInvariant() == type.ToLowerInvariant()); //null if none
}
public void AddComputerModule(ComputerModule module)
{
_unorderedComputerModules.Add(module);
ClearModulesCache();
}
private void ClearModulesCache()
{
_sortedModules.Clear();
_sortedDisplayModules.Clear();
}
public void AddComputerModuleLater(ComputerModule module)
{
//The actual loading is delayed to FixedUpdate because AddComputerModule can get called inside a foreach loop
//over the modules, and modifying the list during the loop will cause an exception. Maybe there is a better
//way to deal with this?
_modulesToLoad.Add(module);
}
private void LoadDelayedModules()
{
if (_modulesToLoad.Count > 0)
{
_unorderedComputerModules.AddRange(_modulesToLoad);
_modulesToLoad.Clear();
ClearModulesCache();
}
}
public void RemoveComputerModule(ComputerModule module)
{
_unorderedComputerModules.Remove(module);
ClearModulesCache();
}
public void ReloadAllComputerModules()
{
//Dispose of all the existing computer modules
foreach (ComputerModule module in _unorderedComputerModules) module.OnDestroy();
_unorderedComputerModules.Clear();
ClearModulesCache();
if (vessel != null) vessel.OnFlyByWire -= OnFlyByWire;
_controlledVessel = null;
//Start fresh
OnLoad(null);
OnStart(HighLogic.LoadedSceneIsEditor ? StartState.Editor : StartState.Flying);
}
public override void OnStart(StartState state)
{
if (HighLogic.LoadedSceneIsEditor)
_ready = true;
if (state == StartState.None) return; //don't do anything when we start up in the loading screen
//OnLoad doesn't get called for parts created in editor, so do that manually so
//that we can load global settings.
//However, if you press ctrl-Z, a new PartModule object gets created, on which the
//game DOES call OnLoad, and then OnStart. So before calling OnLoad from OnStart,
//check whether we have loaded any computer modules.
//if (state == StartState.Editor && computerModules.Count == 0)
// Seems to happend when launching without coming from the VAB too.
if (_unorderedComputerModules.Count == 0)
{
OnLoad(null);
}
GameEvents.onShowUI.Add(OnShowGUI);
GameEvents.onHideUI.Add(OnHideGUI);
GameEvents.onVesselChange.Add(UnlockControl);
GameEvents.onVesselWasModified.Add(OnVesselWasModified);
GameEvents.onVesselStandardModification.Add(OnVesselStandardModification);
_lastSettingsSaveTime = Time.time;
foreach (ComputerModule module in GetComputerModules<ComputerModule>())
{
//especially important to wrap OnStart in a try-catch so that a failure in one module
//doesn't prevent others from initializing.
try
{
module.OnStart(state);
}
catch (Exception e)
{
Debug.LogError("MechJeb module " + module.GetType().Name + " threw an exception in OnStart: " + e);
}
}
if (vessel != null && this != vessel.GetMasterMechJeb())
{
vessel.OnFlyByWire -= OnFlyByWire; //just a safety precaution to avoid duplicates
vessel.OnFlyByWire += OnFlyByWire;
_controlledVessel = vessel;
}
Logger.Register(SafePrint);
}
public override void OnActive()
{
foreach (ComputerModule module in GetComputerModules<ComputerModule>())
{
try
{
module.OnActive();
}
catch (Exception e)
{
Debug.LogError("MechJeb module " + module.GetType().Name + " threw an exception in OnActive: " + e);
}
}
}
public override void OnInactive()
{
foreach (ComputerModule module in GetComputerModules<ComputerModule>())
{
try
{
module.OnInactive();
}
catch (Exception e)
{
Debug.LogError("MechJeb module " + module.GetType().Name + " threw an exception in OnInactive: " + e);
}
}
}
public override void OnAwake()
{
FuelFlowSimulation.FuelNode.DoReflection();
CachedLocalizer.Bootstrap();
Dispatcher.CreateDispatcher();
foreach (ComputerModule module in GetComputerModules<ComputerModule>())
{
try
{
module.OnAwake();
}
catch (Exception e)
{
Debug.LogError("MechJeb module " + module.GetType().Name + " threw an exception in OnAwake: " + e);
}
}
}
public void FixedUpdate()
{
if (!FlightGlobals.ready)
return;
LoadDelayedModules();
CheckControlledVessel(); //make sure our onFlyByWire callback is registered with the right vessel
if (this != vessel.GetMasterMechJeb() || (HighLogic.LoadedSceneIsFlight && !vessel.isActiveVessel))
{
_wasMasterAndFocus = false;
}
if (this != vessel.GetMasterMechJeb())
{
return;
}
Profiler.BeginSample("MechJebCore.FixedUpdate");
if (!_wasMasterAndFocus && (HighLogic.LoadedSceneIsEditor || vessel.isActiveVessel))
{
if (HighLogic.LoadedSceneIsFlight && _lastFocus != null && _lastFocus.loaded && _lastFocus.GetMasterMechJeb() != null)
{
Print("Focus changed! Forcing " + _lastFocus.vesselName + " to save");
_lastFocus.GetMasterMechJeb().OnSave(null);
}
// Clear the modules cache
ClearModulesCache();
OnLoad(null); // Force Global reload
_wasMasterAndFocus = true;
_lastFocus = vessel;
}
if (vessel == null)
{
Profiler.EndSample();
return; //don't run ComputerModules' OnFixedUpdate in editor
}
Profiler.BeginSample("vesselState");
_ready = VesselState.Update(vessel);
Profiler.EndSample();
foreach (ComputerModule module in GetComputerModules<ComputerModule>())
{
Profiler.BeginSample(module.ProfilerName);
try
{
if (module.Enabled)
{
module.OnFixedUpdate();
}
}
catch (Exception e)
{
Debug.LogError("MechJeb module " + module.GetType().Name + " threw an exception in OnFixedUpdate: " + e);
}
Profiler.EndSample();
}
Profiler.EndSample();
}
private bool NeedToSave()
{
bool needToSave = false;
foreach (ComputerModule module in GetComputerModules<ComputerModule>())
{
//if (module.dirty)
// print(module.profilerName + " is dirty");
needToSave |= module.Dirty;
}
return needToSave;
}
public void Update()
{
if (this != vessel.GetMasterMechJeb() || (!FlightGlobals.ready && HighLogic.LoadedSceneIsFlight) || !_ready)
{
return;
}
Profiler.BeginSample("MechJebCore.Update");
if (Input.GetKeyDown(KeyCode.V) && (Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl)))
{
MechJebModuleCustomWindowEditor windowEditor = GetComputerModule<MechJebModuleCustomWindowEditor>();
if (windowEditor != null) windowEditor.CreateWindowFromSharingString(MuUtils.SystemClipboard);
}
//periodically save settings in case we quit unexpectedly
Profiler.BeginSample("MechJebCore.Update.OnSave");
if (HighLogic.LoadedSceneIsEditor || (vessel != null && vessel.isActiveVessel))
{
if (Time.time > _lastSettingsSaveTime + 5)
{
if (NeedToSave())
{
//print("Periodic settings save");
OnSave(null);
}
_lastSettingsSaveTime = Time.time;
}
}
Profiler.EndSample();
if (ResearchAndDevelopment.Instance != null && _unorderedComputerModules.Any(a => !a.UnlockChecked))
{
foreach (ComputerModule module in GetComputerModules<ComputerModule>())
{
try
{
module.UnlockCheck();
}
catch (Exception e)
{
Debug.LogError("MechJeb module " + module.GetType().Name + " threw an exception in UnlockCheck: " + e);
}
}
}
Profiler.BeginSample("OnMenuUpdate");
GetComputerModule<MechJebModuleMenu>().OnMenuUpdate(); // Allow the menu movement, even while in Editor
Profiler.EndSample();
if (vessel == null)
{
Profiler.EndSample();
return; //don't run ComputerModules' OnUpdate in editor
}
foreach (ComputerModule module in GetComputerModules<ComputerModule>())
{
Profiler.BeginSample(module.ProfilerName);
try
{
if (module.Enabled) module.OnUpdate();
}
catch (Exception e)
{
Debug.LogError("MechJeb module " + module.GetType().Name + " threw an exception in OnUpdate: " + e);
}
Profiler.EndSample();
}
Profiler.EndSample();
}
private void LoadComputerModules()
{
if (_moduleRegistry == null)
{
_moduleRegistry = new List<Type>();
foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
foreach (Type module in (from t in ass.GetTypes() where t.IsSubclassOf(typeof(ComputerModule)) && !t.IsAbstract select t)
.ToList())
{
_moduleRegistry.Add(module);
}
}
catch (Exception e)
{
Debug.LogError("MechJeb moduleRegistry creation threw an exception in LoadComputerModules loading " + ass.FullName + ": " +
e);
}
}
}
var assembly = Assembly.GetExecutingAssembly();
var fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
// Mono compiler is stupid and use AssemblyVersion for the AssemblyFileVersion
// So we use an other field to store the dev build number ...
Attribute[] attributes = Attribute.GetCustomAttributes(assembly, typeof(AssemblyInformationalVersionAttribute));
string devVersion = "";
if (attributes.Length > 0)
devVersion = ((AssemblyInformationalVersionAttribute)attributes[0]).InformationalVersion;
version = devVersion == ""
? $"{fileVersionInfo.FileMajorPart}.{fileVersionInfo.FileMinorPart}.{fileVersionInfo.FileBuildPart}"
: devVersion;
if (HighLogic.LoadedSceneIsEditor || HighLogic.LoadedSceneIsFlight)
Print("Loading Mechjeb " + version);
try
{
foreach (Type t in _moduleRegistry)
{
if (t != typeof(ComputerModule) && t != typeof(DisplayModule) && t != typeof(MechJebModuleCustomInfoWindow)
&& t != typeof(AutopilotModule) && t != typeof(MechJebModuleAscentBaseAutopilot)
&& !blacklist.Contains(t.Name) && GetComputerModule(t.Name) == null)
{
ConstructorInfo constructorInfo = t.GetConstructor(new[] { typeof(MechJebCore) });
if (constructorInfo != null)
AddComputerModule((ComputerModule)constructorInfo.Invoke(new object[] { this }));
}
}
}
catch (Exception e)
{
Debug.LogError("MechJeb moduleRegistry loading threw an exception in LoadComputerModules: " + e);
}
Attitude = GetComputerModule<MechJebModuleAttitudeController>();
Staging = GetComputerModule<MechJebModuleStagingController>();
Thrust = GetComputerModule<MechJebModuleThrustController>();
Target = GetComputerModule<MechJebModuleTargetController>();
Warp = GetComputerModule<MechJebModuleWarpController>();
RCS = GetComputerModule<MechJebModuleRCSController>();
Rcsbal = GetComputerModule<MechJebModuleRCSBalancer>();
Rover = GetComputerModule<MechJebModuleRoverController>();
Node = GetComputerModule<MechJebModuleNodeExecutor>();
Solarpanel = GetComputerModule<MechJebModuleSolarPanelController>();
AntennaControl = GetComputerModule<MechJebModuleDeployableAntennaController>();
Landing = GetComputerModule<MechJebModuleLandingAutopilot>();
Settings = GetComputerModule<MechJebModuleSettings>();
Airplane = GetComputerModule<MechJebModuleAirplaneAutopilot>();
Guidance = GetComputerModule<MechJebModuleGuidanceController>();
Glueball = GetComputerModule<MechJebModulePVGGlueBall>();
StageStats = GetComputerModule<MechJebModuleStageStats>();
AscentSettings = GetComputerModule<MechJebModuleAscentSettings>();
Spinup = GetComputerModule<MechJebModuleSpinupController>();
}
public override void OnLoad(ConfigNode sfsNode)
{
if (GuiUtils.skin == null)
{
//GuiUtils.skin = new GUISkin();
// ReSharper disable once ObjectCreationAsStatement
new GameObject("zombieGUILoader", typeof(ZombieGUILoader));
}
try
{
bool generateDefaultWindows = false;
base.OnLoad(sfsNode); //is this necessary?
// With the Unity 4.6 upgrade of KSP 1.0 we inherited a serialization problem
// with object with high depth like config nodes
// so the partmodule config node passed was not ok.
// So we use a static dir to save the part config node.
if (!_savedConfig.ContainsKey(part.name))
{
if (HighLogic.LoadedScene == GameScenes.LOADING)
_savedConfig.Add(part.name, sfsNode);
}
else
{
_partSettings = _savedConfig[part.name];
}
LoadComputerModules();
var global = new ConfigNode("MechJebGlobalSettings");
if (File.Exists<MechJebCore>("mechjeb_settings_global.cfg"))
{
try
{
global = ConfigNode.Load(MuUtils.GetCfgPath("mechjeb_settings_global.cfg"));
}
catch (Exception e)
{
Debug.LogError("MechJebCore.OnLoad caught an exception trying to load mechjeb_settings_global.cfg: " + e);
generateDefaultWindows = true;
}
}
else
{
generateDefaultWindows = true;
}
var type = new ConfigNode("MechJebTypeSettings");
string vesselName =
vessel != null
? string.Join("_", vessel.vesselName.Split(Path.GetInvalidFileNameChars()))
: ""; // Strip illegal char from the filename
if (vessel != null && File.Exists<MechJebCore>("mechjeb_settings_type_" + vesselName + ".cfg"))
{
try
{
type = ConfigNode.Load(MuUtils.GetCfgPath("mechjeb_settings_type_" + vesselName + ".cfg"));
}
catch (Exception e)
{
Debug.LogError("MechJebCore.OnLoad caught an exception trying to load mechjeb_settings_type_" + vesselName + ".cfg: " + e);
}
}
var local = new ConfigNode("MechJebLocalSettings");
if (sfsNode != null && sfsNode.HasNode("MechJebLocalSettings"))
{
local = sfsNode.GetNode("MechJebLocalSettings");
}
else if (_partSettings != null && _partSettings.HasNode("MechJebLocalSettings"))
{
local = _partSettings.GetNode("MechJebLocalSettings");
}
else if (sfsNode == null) // capture current Local settings
{
foreach (ComputerModule module in GetComputerModules<ComputerModule>())
{
try
{
module.OnSave(local.AddNode(module.GetType().Name), null, null);
}
catch (Exception e)
{
Debug.LogError("MechJeb module " + module.GetType().Name + " threw an exception in OnLoad: " + e);
}
}
}
/*Debug.Log("OnLoad: loading from");
Debug.Log("Local:");
Debug.Log(local.ToString());
Debug.Log("Type:");
Debug.Log(type.ToString());
Debug.Log("Global:");
Debug.Log(global.ToString());*/
// Remove any currently loaded custom windows
while (GetComputerModule<MechJebModuleCustomInfoWindow>() is { } win)
{
RemoveComputerModule(win);
}
foreach (ComputerModule module in GetComputerModules<ComputerModule>())
{
try
{
string moduleTypeName = module.GetType().Name;
ConfigNode moduleLocal = local.HasNode(moduleTypeName) ? local.GetNode(moduleTypeName) : null;
ConfigNode moduleType = type.HasNode(moduleTypeName) ? type.GetNode(moduleTypeName) : null;
ConfigNode moduleGlobal = global.HasNode(moduleTypeName) ? global.GetNode(moduleTypeName) : null;
module.OnLoad(moduleLocal, moduleType, moduleGlobal);
}
catch (Exception e)
{
Debug.LogError("MechJeb module " + module.GetType().Name + " threw an exception in OnLoad: " + e);
}
}
LoadDelayedModules();
if (generateDefaultWindows)
{
GetComputerModule<MechJebModuleCustomWindowEditor>().AddDefaultWindows();
}
}
catch (ReflectionTypeLoadException ex)
{
Debug.LogError("MechJeb caught a ReflectionTypeLoadException. Those DLL are not built for this KSP version:");
IEnumerable<Assembly> brokenAssembly = ex.Types.Where(x => x != null).Select(x => x.Assembly).Distinct();
foreach (Assembly assembly in brokenAssembly)
{
Debug.LogError(assembly.GetName().Name + " " + assembly.GetName().Version + " " +
assembly.Location.Remove(0, Path.GetFullPath(KSPUtil.ApplicationRootPath).Length));
}
}
catch (Exception e)
{
Debug.LogError("MechJeb caught exception in core OnLoad: " + e);
}
}
public override void OnSave(ConfigNode sfsNode)
{
//we have nothing worth saving if we're outside the editor or flight scenes:
if (!(HighLogic.LoadedSceneIsEditor || HighLogic.LoadedSceneIsFlight)) return;
// Only Masters can save
if (this != vessel.GetMasterMechJeb()) return;
//KSP calls OnSave *before* OnLoad when the first command pod is created in the editor.
//Defend against saving empty settings.
if (_unorderedComputerModules.Count == 0) return;
// .23 added a call to OnSave for undocking/decoupling vessel before they are properly init ...
if (HighLogic.LoadedSceneIsFlight && vessel != null && vessel.vesselName == null)
return;
Profiler.BeginSample("MechJebCore.OnSave");
try
{
//Add any to-be-loaded modules so they get saved properly
Profiler.BeginSample("MechJebCore.OnSave.LoadDelayedModules");
LoadDelayedModules();
// base.OnSave(sfsNode); //is this necessary?
Profiler.EndSample();
Profiler.BeginSample("MechJebCore.OnSave.ConfigNode");
// We have 2 type of saves:
// - stock module save where sfsNode is provided and where we save the module inside the ship
// - MechJeb global/type save where we do not save the module but save MJ global/type configs
ConfigNode local = sfsNode == null ? null : new ConfigNode("MechJebLocalSettings");
ConfigNode type = sfsNode != null ? null : new ConfigNode("MechJebTypeSettings");
ConfigNode global = sfsNode != null ? null : new ConfigNode("MechJebGlobalSettings");
Profiler.EndSample();
Profiler.BeginSample("MechJebCore.OnSave.loop");
foreach (ComputerModule module in GetComputerModules<ComputerModule>())
{
Profiler.BeginSample(module.ProfilerName);
try
{
string moduleTypeName = module.GetType().Name;
module.OnSave(local?.AddNode(moduleTypeName), type?.AddNode(moduleTypeName), global?.AddNode(moduleTypeName));
}
catch (Exception e)
{
Debug.LogError("MechJeb module " + module.GetType().Name + " threw an exception in OnSave: " + e);
}
Profiler.EndSample();