forked from SodiumEyes/AmpYear
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathAYController.cs
More file actions
1676 lines (1523 loc) · 73.8 KB
/
AYController.cs
File metadata and controls
1676 lines (1523 loc) · 73.8 KB
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
/**
* AYController.cs
*
* AmpYear power management.
* (C) Copyright 2015, Jamie Leighton
* The original code and concept of AmpYear rights go to SodiumEyes on the Kerbal Space Program Forums, which was covered by GNU License GPL (no version stated).
* As such this code continues to be covered by GNU GPL license.
* Parts of this code were copied from Fusebox by the user ratzap on the Kerbal Space Program Forums, which is covered by GNU License GPLv2.
* Concepts which are common to the Game Kerbal Space Program for which there are common code interfaces as such some of those concepts used
* by this program were based on:
* Thunder Aerospace Corporation's Life Support for Kerbal Space Program.
* Written by Taranis Elsu.
* (C) Copyright 2013, Taranis Elsu
* Which is licensed under the Attribution-NonCommercial-ShareAlike 3.0 (CC BY-NC-SA 3.0)
* creative commons license. See <http://creativecommons.org/licenses/by-nc-sa/3.0/legalcode>
* for full details.
*
* Thanks go to both ratzap and Taranis Elsu for their code.
* Kerbal Space Program is Copyright (C) 2013 Squad. See http://kerbalspaceprogram.com/. This
* project is in no way associated with nor endorsed by Squad.
*
* This file is part of AmpYear.
*
* AmpYear 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.
*
* AmpYear 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 AmpYear. If not, see <http://www.gnu.org/licenses/>.
*
*/
using System;
using System.Collections.Generic;
using KSP.Localization;
using KSP.UI;
using KSP.UI.Screens;
using UnityEngine;
using RSTUtils;
namespace AY
{
public partial class AYController : MonoBehaviour, ISavable
{
#region Iayaddon
public List<Part> CrewablePartList
{
get
{
return crewablePartList;
}
}
public bool[] SubsystemToggle
{
get
{
return _subsystemToggle;
}
}
public bool HasPower
{
get
{
return hasPower;
}
}
public bool ManagerisActive
{
get
{
return ManagerIsActive;
}
}
public bool DeBugging
{
get
{
return AYsettings.debugging;
}
}
#endregion Iayaddon
public static AYController Instance { get; private set; }
public AYController()
{
Utilities.Log("AYController Constructor");
Instance = this;
}
//AmpYear Properties
internal List<Part> crewablePartList = new List<Part>();
internal List<string> PartsToDelete = new List<string>();
internal List<Part> PartsModuleCommand = new List<Part>();
internal List<ProtoCrewMember> VslRstr = new List<ProtoCrewMember>();
internal double TotalElectricCharge = 0.0;
internal double TotalElectricChargeFlowOff = 0.0;
internal double TotalElectricChargeCapacity = 0.0;
internal double TotalReservePower = 0.0;
internal double TotalReservePowerFlowOff = 0.0;
internal double TotalReservePowerCapacity = 0.0;
internal double TotalPowerDrain = 0.0;
internal double TotalPowerProduced = 0.0;
internal bool hasPower = true;
internal bool HasReservePower = true;
internal bool HasRcs = false;
private float currentRCSThrust = 0.0f;
internal float currentPoweredRCSDrain = 0.0f;
internal double _sasPwrDrain = 0;
internal Guid Currentvesselid;
internal int TotalClimateParts = 0;
internal int MaxCrew = 0;
internal int CurrentCrewCount = 0;
private bool TACLSProcessedforVessel = false;
private uint rootPartID;
internal bool RT2UnderControl = true;
private bool outhasAlternator = false;
private bool outcurrentEngActive = false;
private double outaltRate = 0f;
private bool wasStockModule = false;
private double altRate = 0f;
private bool currentEngActive = false;
private bool hasAlternator = false;
private Vessel currentVessel;
private double manager_drain, subsystem_drain, total_manager_drain;
private double deltaTime,
desiredElectricity,
desiredElectricity2,
minimumSufficientCharge,
totalElecreceived,
totalElecreceived2;
private string prtName, prtPower;
private bool prtActive;
private double tmpPower;
private List<Part> vesselparts = new List<Part>();
private double currentTime, checkVesselUpdateTime;
private List<Vessel> allVessels = new List<Vessel>();
private List<Guid> vesselsToDelete = new List<Guid>();
private VesselInfo currvesselInfo;
private bool _reenableRcs = false; //When RCS is disabled by ESP this flag is set to true once it is ok to re-activate.
private bool _reenableSas = false; //When SAS is disabled by ESP this flag is set to true once it is ok to re-activate.
//ESP Processing vars
internal static bool Emergencypowerdownactivated = false; //Set to true if ESP power down has been triggered.
internal bool Emergencypowerdownprevactivated = false; //Set to true if ESP power down has been previously triggered and reset has not.
internal static bool Emergencypowerdownreset = false; //Set to true if ESP power down has previously been triggered and it is now ok to reset.
internal bool Emergencypowerdownresetprevactivated = false; //Set to true if ESP power reset has been previously triggered and power down has not.
internal ESPPriority _espPriority = ESPPriority.LOW; //The current ESP Part Priority setting.
internal bool ESPPriorityHighProcessed = false; //True if High Priority parts have been processed by ESP during a power down.
internal bool ESPPriorityMediumProcessed = false; //True if Medium Priority parts have been processed by ESP during a power down.
internal bool ESPPriorityLowProcessed = false; //True if Low Priority parts have been processed by ESP during a power down.
internal bool ESPPriorityHighResetProcessed = false; //True if High Priority parts have been processed by ESP during a power reset.
internal bool ESPPriorityMediumResetProcessed = false; //True if Medium Priority parts have been processed by ESP during a power reset.
internal bool ESPPriorityLowResetProcessed = false; //True if Low Priority parts have been processed by ESP during a power reset.
internal PowerState PowerState; //Stores the current power state
PartResourceDefinition definition = PartResourceLibrary.Instance.GetDefinition(MAIN_POWER_NAME);
//Constants
public const double MANAGER_ACTIVE_DRAIN = 1.0 / 60.0;
public const double RCS_DRAIN = 1.0 / 60.0;
public const float POWER_UP_DELAY = 10f;
public const double SAS_BASE_DRAIN = 1.0 / 60.0;
public const float CLIMATE_HEAT_RATE = 1f;
public const double CLIMATE_CAPACITY_DRAIN_FACTOR = 0.5;
public const double RECHARGE_RESERVE_RATE = 30.0 / 60.0;
public const double RECHARGE_OVERFLOW_AVOID_FACTOR = 1.0;
public const String MAIN_POWER_NAME = "ElectricCharge";
public const String RESERVE_POWER_NAME = "ReservePower";
public const String SUBSYS_STATE_LABEL = "Subsys";
public const String GUI_SECTION_LABEL = "Section";
//AmpYear Savable settings
internal AYSettings AYsettings;
internal AYGameSettings AYgameSettings;
//GuiVisibility
private bool _mouseDownResize;
private bool _mouseDownHorizScl1;
private bool _mouseDownHorizScl2;
public void Awake()
{
Utilities.Log("AYController Awake in {0}" , HighLogic.LoadedScene.ToString());
AYsettings = AmpYear.Instance.AYsettings;
AYgameSettings = AmpYear.Instance.AYgameSettings;
_fwindowId = Utilities.getnextrandomInt();
_ewindowId = _fwindowId + 1;
_wwindowId = _ewindowId + 1;
_swindowId = _wwindowId + 1;
_dwindowId = _swindowId + 1;
_eplPartName = Mathf.Round((_epLwindowPos.width - 28f) * .3f);
_eplPartModuleName = Mathf.Round((_epLwindowPos.width - 28f) * .4f);
_eplec = Mathf.Round((_epLwindowPos.width - 28f) * .17f);
_eplProdListHeight = _eplConsListHeight = Mathf.Round((_epLwindowPos.height - 170) * .5f);
AYMenuAppLToolBar = new AppLauncherToolBar("AmpYear", "AmpYear",
Textures.PathToolbarIconsPath + "/AYGreenOffTB",
ApplicationLauncher.AppScenes.VAB | ApplicationLauncher.AppScenes.SPH | ApplicationLauncher.AppScenes.FLIGHT | ApplicationLauncher.AppScenes.MAPVIEW,
(Texture)Textures.IconGreenOn, (Texture)Textures.IconGreenOff,
GameScenes.FLIGHT, GameScenes.EDITOR);
Utilities.Log_Debug("AYController Awake complete");
}
public void Start()
{
Utilities.Log_Debug("AYController Start");
//If Settings wants to use ToolBar mod, check it is installed and available. If not set the Setting to use Stock.
if (!ToolbarManager.ToolbarAvailable && !AYsettings.UseAppLauncher)
{
AYsettings.UseAppLauncher = true;
}
AYMenuAppLToolBar.Start(AYsettings.UseAppLauncher);
Utilities.setScaledScreen();
// Find out which mods are present
ALPresent = Utilities.IsModInstalled("AviationLights");
NFEPresent = Utilities.IsModInstalled("NearFutureElectrical");
NFSPresent = Utilities.IsModInstalled("NearFutureSolar");
NFPPresent = Utilities.IsModInstalled("NearFuturePropulsion");
KASPresent = Utilities.IsModInstalled("KAS");
_rt2Present = Utilities.IsModInstalled("RemoteTech");
ScSPresent = Utilities.IsModInstalled("SCANsat");
TelPresent = Utilities.IsModInstalled("Telemachus");
TACLPresent = Utilities.IsModInstalled("TacLifeSupport");
AntRPresent = Utilities.IsModInstalled("AntennaRange");
KISEPresent = Utilities.IsModInstalled("Interstellar");
TFCPresent = Utilities.IsModInstalled("ToggleFuelCell");
KKPresent = Utilities.IsModInstalled("KabinKraziness");
DFPresent = Utilities.IsModInstalled("DeepFreeze");
KPBSPresent = Utilities.IsModInstalled("PlanetarySurfaceStructures");
USILSPresent = Utilities.IsModInstalled("USILifeSupport");
IONRCSPresent = Utilities.IsModInstalled("IONRCS");
KERBALISMPresent = Utilities.IsModInstalled("Kerbalism");
KopernicusPresent = Utilities.IsModInstalled("Kopernicus");
DSEVPresent = Utilities.IsModInstalled("DSEVUtils");
Utilities.Log_Debug(KKPresent ? "KabinKraziness present" : "KabinKraziness NOT present");
//if (KKPresent) //Moved to FixedUpdate
//{
// Utilities.Log_Debug("KabinKraziness present");
// KKWrapper.InitKKWrapper();
// if (!KKWrapper.APIReady)
// {
// KKPresent = false;
// }
//}
if (DFPresent)
{
Utilities.Log_Debug("DeepFreeze present");
DFWrapper.InitDFWrapper();
if (!DFWrapper.APIReady)
{
DFPresent = false;
Utilities.Log("Ampyear - Near Future Solar Interface Failed");
}
}
if (ALPresent)
{
Utilities.Log_Debug("Aviation Lights present");
ALWrapper.InitTALWrapper();
if (!ALWrapper.APIReady)
{
ALPresent = false;
Utilities.Log("Ampyear - Aviation Lights Interface Failed");
}
}
if (NFEPresent)
Utilities.Log_Debug("Near Future Electric present");
if (NFSPresent)
{
Utilities.Log_Debug("Near Future Solar present");
NFSWrapper.InitNFSWrapper();
if (!NFSWrapper.APIReady)
{
NFSPresent = false;
Utilities.Log("Ampyear - Near Future Electric Interface Failed");
}
}
if (NFPPresent)
{
Utilities.Log_Debug("Near Future Propulsion present");
NFPWrapper.InitNFPWrapper();
if (!NFPWrapper.APIReady)
{
NFPPresent = false;
Utilities.Log("Ampyear - Near Future Propulsion Interface Failed");
}
}
if (KASPresent)
{
Utilities.Log_Debug("KAS present");
KASWrapper.InitKASWrapper();
if (!KASWrapper.APIReady)
{
KASPresent = false;
Utilities.Log("Ampyear - KAS Interface Failed");
}
}
if (_rt2Present)
{
Utilities.Log_Debug("RT2 present");
RTWrapper.InitTRWrapper();
if (!RTWrapper.APIReady)
{
_rt2Present = false;
Utilities.Log("Ampyear - RT2 Interface Failed");
}
}
if (ScSPresent)
{
Utilities.Log_Debug("SCANSat present");
ScanSatWrapper.InitSCANsatWrapper();
if (!ScanSatWrapper.APIReady)
{
ScSPresent = false;
Utilities.Log("Ampyear - SCANSat Interface Failed");
}
}
if (TelPresent)
{
Utilities.Log_Debug("Telemachus present");
TeleWrapper.InitTALWrapper();
if (!TeleWrapper.APIReady)
{
TelPresent = false;
Utilities.Log("Ampyear - Telemachus Interface Failed");
}
}
if (TACLPresent)
{
Utilities.Log_Debug("TAC LS present");
TACLSWrapper.InitTACLSWrapper();
if (!TACLSWrapper.APIReady)
{
TACLPresent = false;
Utilities.Log("Ampyear - TAC LS Interface Failed");
}
}
if (USILSPresent)
{
Utilities.Log_Debug("USI LS present");
USILSWrapper.InitUSILSWrapper();
if (!USILSWrapper.APIReady)
{
USILSPresent = false;
Utilities.Log("Ampyear - USI LS Interface Failed");
}
}
if (KPBSPresent)
{
Utilities.Log_Debug("KPBS present");
KPBSWrapper.InitKPBSWrapper();
if (!KPBSWrapper.APIReady)
{
KPBSPresent = false;
Utilities.Log("Ampyear - KPBS Interface Failed");
}
}
if (AntRPresent)
Utilities.Log_Debug("AntennaRange present");
if (KISEPresent)
{
Utilities.Log_Debug("Interstellar present");
KSPIEWrapper.InitKSPIEWrapper();
if (!KSPIEWrapper.APIReady)
{
KISEPresent = false;
Utilities.Log("Ampyear - Interstellar Interface Failed");
}
}
if (TFCPresent)
Utilities.Log_Debug("ToggleFuelCell present");
if (IONRCSPresent)
{
Utilities.Log_Debug("IONRCS present");
IONRCSWrapper.InitIONRCSWrapper();
if (!IONRCSWrapper.APIReady)
{
IONRCSPresent = false;
Utilities.Log("Ampyear - IONRCS Interface Failed");
}
}
if (DSEVPresent)
{
Utilities.Log_Debug("DSEV present");
DSEVWrapper.InitDSEVWrapper();
if (!DSEVWrapper.APIReady)
{
DSEVPresent = false;
Utilities.Log("Ampyear - DSEV Interface Failed");
}
}
//check if inflight and active vessel set currentvesselid and load config settings for this vessel
if (FlightGlobals.fetch != null && FlightGlobals.ActiveVessel != null)
{
currvesselInfo = new VesselInfo(FlightGlobals.ActiveVessel.vesselName, currentTime);
Currentvesselid = FlightGlobals.ActiveVessel.id;
OnVesselLoad(FlightGlobals.ActiveVessel);
}
//Create DarkBodies list
_darkBodies.Clear();
for (int i = 0; i < FlightGlobals.Bodies.Count; i++)
{
_darkBodies.Add(FlightGlobals.Bodies[i]);
}
//Set the default SolarPanel SOI Target and DarkSide Target to HomeBody Index (can be changed in the GUI by the user)
_selectedDarkTarget = FlightGlobals.GetHomeBodyIndex();
_bodyTarget = FlightGlobals.Bodies[_selectedDarkTarget];
// add callbacks for vessel load and change
GameEvents.onVesselChange.Add(OnVesselChange);
GameEvents.onVesselLoaded.Add(OnVesselLoad);
GameEvents.onCrewBoardVessel.Add(OnCrewBoardVessel);
GameEvents.onGameSceneSwitchRequested.Add(OnGameSceneSwitch);
GameEvents.onGameSceneLoadRequested.Add(OnGameSceneLoad);
GameEvents.onGUIEngineersReportReady.Add(AddTests);
GameEvents.OnVesselRollout.Add(OnVesselRollout);
GameEvents.onVesselCreate.Add(OnVesselCreate);
GameEvents.onVesselDestroy.Add(onVesselDestroy);
GameEvents.onVesselRecovered.Add(onVesselRecovered);
//Clean up the known vessels dictionary for any that don't exist any more on startup.
RemoveUnknownVessels();
Utilities.Log_Debug("AYController Start complete");
}
internal void AddTests()
{
Utilities.Log_Debug("Adding AY Engineer Test");
PreFlightTests.IDesignConcern AYtest = new AYEngReport();
EngineersReport.Instance.AddTest(AYtest);
}
public void OnDestroy()
{
AYMenuAppLToolBar.Destroy();
GameEvents.onVesselChange.Remove(OnVesselChange);
GameEvents.onVesselLoaded.Remove(OnVesselLoad);
GameEvents.onCrewBoardVessel.Remove(OnCrewBoardVessel);
GameEvents.onGameSceneSwitchRequested.Remove(OnGameSceneSwitch);
GameEvents.onGameSceneLoadRequested.Remove(OnGameSceneLoad);
GameEvents.onGUIEngineersReportReady.Remove(AddTests);
GameEvents.OnVesselRollout.Remove(OnVesselRollout);
GameEvents.onVesselCreate.Remove(OnVesselCreate);
GameEvents.onVesselDestroy.Remove(onVesselDestroy);
GameEvents.onVesselRecovered.Remove(onVesselRecovered);
InputLock = false;
}
private void OnVesselRollout(ShipConstruct Ship)
{
Utilities.Log("OnVesselRollout");
}
private void OnVesselCreate(Vessel Vessel)
{
Utilities.Log("OnVesselCreate");
}
public void FixedUpdate()
{
if (Time.timeSinceLevelLoad < 3.0f) // Check not loading level
{
return;
}
if (!Utilities.GameModeisFlight && !Utilities.GameModeisEditor) return; // Only execute Update in Flight or Editor Scene
if ((FlightGlobals.ready && FlightGlobals.ActiveVessel != null) || HighLogic.LoadedSceneIsEditor)
{
currentTime = Planetarium.GetUniversalTime();
//Timing for KabinKraziness must be here not in Start.
if (KKPresent && !KKWrapper.APIReady)
{
Utilities.Log_Debug("KabinKraziness present");
KKWrapper.InitKKWrapper();
if (!KKWrapper.APIReady)
{
KKPresent = false;
Utilities.Log("Ampyear - KabinKraziness Interface Failed");
}
}
//Set Remote Tech connection status if installed
if (_rt2Present)
{
if (RTWrapper.APIReady && FlightGlobals.ActiveVessel != null)
{
RT2UnderControl = RTWrapper.RTactualAPI.HasLocalControl(FlightGlobals.ActiveVessel.id) ||
RTWrapper.RTactualAPI.HasAnyConnection(FlightGlobals.ActiveVessel.id);
}
else
{
RT2UnderControl = true;
Utilities.Log_Debug("Remote Tech installed but unable to check active connections, assume we have a connection");
}
}
//get current vessel parts list and crew numbers
if (Utilities.GameModeisFlight)
{
try
{
vesselparts = FlightGlobals.ActiveVessel.Parts;
rootPartID = 1111;
rootPartID = FlightGlobals.ActiveVessel.rootPart.craftID;
if (vesselparts == null)
{
Utilities.Log("In Flight but couldn't get parts list");
return;
}
CurrentCrewCount = FlightGlobals.ActiveVessel.GetCrewCount();
}
catch (Exception ex)
{
if (ex.Message.Contains("Reference"))
{
Utilities.Log("NullRef occurred getting parts list");
}
else
{
Utilities.Log_Debug("Error occurred getting parts list " + ex.Message);
}
return;
}
if (currentTime - checkVesselUpdateTime > 10)
{
CheckVslUpdate();
checkVesselUpdateTime = currentTime;
}
}
else
{
try
{
//parts = EditorLogic.SortedShipList;
vesselparts = EditorLogic.fetch.ship.parts;
rootPartID = 1111;
if (EditorLogic.RootPart != null)
rootPartID = EditorLogic.RootPart.craftID;
if (vesselparts == null)
{
Utilities.Log_Debug("In Editor but couldn't get parts list");
return;
}
CrewAssignmentDialog dialog = CrewAssignmentDialog.Instance;
if (dialog != null)
{
VesselCrewManifest manifest = dialog.GetManifest();
if (manifest != null)
{
CurrentCrewCount = 0;
List<PartCrewManifest> manifests = manifest.GetCrewableParts();
for (int i = 0; i < manifests.Count; i++)
{
var partCrew = manifests[i].GetPartCrew();
int partCrewCount = 0;
for (int j = 0; j < partCrew.Length; ++j)
{
if (partCrew[j] != null)
++partCrewCount;
}
CurrentCrewCount += partCrewCount;
}
}
}
}
catch (Exception Ex)
{
if (Ex.Message.Contains("Reference"))
{
Utilities.Log("NullRef occurred getting parts list");
}
else
{
Utilities.Log_Debug("Error occurred getting parts list " + Ex.Message);
}
return;
}
}
//Compile information about the vessel and its parts
// zero accumulators
TotalElectricCharge = 0.0;
TotalElectricChargeFlowOff = 0.0;
TotalElectricChargeCapacity = 0.0;
TotalReservePower = 0.0;
TotalReservePowerFlowOff = 0.0;
TotalReservePowerCapacity = 0.0;
TotalClimateParts = 0;
TotalPowerDrain = 0;
TotalPowerProduced = 0;
_sasPwrDrain = 0.0f;
HasRcs = false;
TACLSProcessedforVessel = false;
currentRCSThrust = 0.0f;
currentPoweredRCSDrain = 0.0f;
crewablePartList.Clear();
PartsModuleCommand.Clear();
MaxCrew = 0;
try
{
PartsToDelete.Clear();
foreach (var entry in AYVesselPartLists.VesselProdPartsList)
{
entry.Value.PrtPower = "0";
entry.Value.PrtPowerF = 0;
entry.Value.PrtActive = false;
if (!PartsToDelete.Contains(entry.Key))
PartsToDelete.Add(entry.Key);
}
foreach (var entry in AYVesselPartLists.VesselConsPartsList)
{
entry.Value.PrtPower = "0";
entry.Value.PrtPowerF = 0;
entry.Value.PrtActive = false;
if (!PartsToDelete.Contains(entry.Key))
PartsToDelete.Add(entry.Key);
}
//VslRstr.Clear(); //clear the vessel roster
//Begin calcs
if (Utilities.GameModeisFlight && FlightGlobals.ActiveVessel != null) // if in flight compile the vessel roster
{
VslRstr = FlightGlobals.ActiveVessel.GetVesselCrew();
}
//loop through all parts in the parts list of the vessel
for (int i = 0; i < vesselparts.Count; i++)
{
if (vesselparts[i].CrewCapacity > 0)
{
crewablePartList.Add(vesselparts[i]);
MaxCrew += vesselparts[i].CrewCapacity;
}
hasAlternator = false;
currentEngActive = false;
altRate = 0f;
//loop through all the modules in the current part
for (int j = 0; j < vesselparts[i].Modules.Count; j++)
{
//Check if the current module is a stock part module and process it.
//Returned values : Bool true if it was a stock module or false if it was not.
// hasAlternator is true if the module had an Alternator.
outhasAlternator = false;
outcurrentEngActive = false;
outaltRate = 0f;
wasStockModule = ProcessStockPartModule(vesselparts[i], vesselparts[i].Modules[j], hasAlternator, currentEngActive, altRate,
out outhasAlternator, out outcurrentEngActive, out outaltRate);
hasAlternator = outhasAlternator;
currentEngActive = outcurrentEngActive;
altRate = outaltRate;
//If it wasn't a stock part module, process the currently supported mod partmodules.
if (!wasStockModule)
{
ProcessModPartModule(vesselparts[i], vesselparts[i].Modules[j]);
}
} // end modules loop
//Sum up the power resources
if (!hasAlternator) //Ignore parts with alternators in power-capacity calculate because they don't actually store power
{
for (int k = 0; k < vesselparts[i].Resources.Count; k++)
{
//foreach (PartResource resource in parts[i].Resources)
//{
if (vesselparts[i].Resources[k].resourceName == MAIN_POWER_NAME)
{
if (vesselparts[i].Resources[k].flowState)
{
TotalElectricCharge += vesselparts[i].Resources[k].amount;
}
else
{
TotalElectricChargeFlowOff += vesselparts[i].Resources[k].amount;
}
TotalElectricChargeCapacity += vesselparts[i].Resources[k].maxAmount;
}
else if (vesselparts[i].Resources[k].resourceName == RESERVE_POWER_NAME)
{
if (vesselparts[i].Resources[k].flowState)
{
TotalReservePower += vesselparts[i].Resources[k].amount;
}
else
{
TotalReservePowerFlowOff += vesselparts[i].Resources[k].amount;
}
TotalReservePowerCapacity += vesselparts[i].Resources[k].maxAmount;
}
}
}
} // end part loop
}
catch (Exception ex)
{
Utilities.Log("Failure in Part Processing");
Utilities.Log("Exception: {0}", ex);
}
if (Utilities.GameModeisFlight)
{
//Here we check if ESP is running and if it is we set the Processing flags so we only do it once per priority until a EC %age
// is crossed again.
if (Emergencypowerdownactivated)
{
switch (_espPriority)
{
case ESPPriority.HIGH:
ESPPriorityHighProcessed = true;
break;
case ESPPriority.MEDIUM:
ESPPriorityMediumProcessed = true;
break;
case ESPPriority.LOW:
ESPPriorityLowProcessed = true;
break;
}
}
if (Emergencypowerdownreset)
{
switch (_espPriority)
{
case ESPPriority.HIGH:
ESPPriorityHighResetProcessed = true;
break;
case ESPPriority.MEDIUM:
ESPPriorityMediumResetProcessed = true;
break;
case ESPPriority.LOW:
ESPPriorityLowResetProcessed = true;
break;
}
}
}
//Do Subsystem processing, EC calcs and Emergency Shutdown Processing
try
{
SubsystemUpdate();
}
catch (Exception ex)
{
Utilities.Log("Failure in AYSubSystem Processing");
Utilities.Log("Exception: {0}", ex);
}
//Remove parts that aren't currently attached to the current vessel.
for (int i = 0; i < PartsToDelete.Count; i++)
{
//foreach (string part in PartsToDelete)
//{
if (AYVesselPartLists.VesselProdPartsList.ContainsKey(PartsToDelete[i]))
{
AYVesselPartLists.VesselProdPartsList.Remove(PartsToDelete[i]);
}
if (AYVesselPartLists.VesselConsPartsList.ContainsKey(PartsToDelete[i]))
{
AYVesselPartLists.VesselConsPartsList.Remove(PartsToDelete[i]);
}
}
} // end if active vessel not null
}
private void SubsystemUpdate()
{
//This is the Logic that Executes in Flight
if (HighLogic.LoadedSceneIsFlight)
{
currentVessel = FlightGlobals.ActiveVessel;
if (currentVessel.ActionGroups[KSPActionGroup.RCS] && !SubsystemPowered(Subsystem.RCS))
{
Utilities.Log("RCS - disabled.");
//Disable RCS when the subsystem isn't powered
currentVessel.ActionGroups.SetGroup(KSPActionGroup.RCS, false);
_reenableRcs = true;
}
if (KKPresent)
{
KKAutopilotChk(currentVessel);
}
else
{
if (currentVessel.ActionGroups[KSPActionGroup.SAS] && !SubsystemPowered(Subsystem.SAS))
{
Utilities.Log("SAS - disabled.");
//Disable SAS when the subsystem isn't powered
currentVessel.ActionGroups.SetGroup(KSPActionGroup.SAS, false);
_reenableSas = true;
}
}
if (ManagerIsActive && hasPower)
{
//Re-enable SAS/RCS if they were shut off by the manager and can be run again
if (KKPresent)
{
KKSASChk();
}
else
{
if (_reenableSas)
{
SetSubsystemEnabled(Subsystem.SAS, true);
_reenableSas = false;
Utilities.Log("SAS - enabled.");
}
}
if (_reenableRcs)
{
SetSubsystemEnabled(Subsystem.RCS, true);
_reenableRcs = false;
Utilities.Log("RCS - enabled.");
}
}
//Calculate total drain from subsystems
subsystem_drain = 0.0;
_subsystemDrain[(int)Subsystem.RCS] -= currentPoweredRCSDrain;
for (int i = LoadGlobals.SubsystemArrayCache.Length - 1; i >= 0; --i)
{
_subsystemDrain[(int)LoadGlobals.SubsystemArrayCache[i]] = SubsystemCurrentDrain(LoadGlobals.SubsystemArrayCache[i]);
subsystem_drain += _subsystemDrain[(int)LoadGlobals.SubsystemArrayCache[i]];
}
manager_drain = ManagerCurrentDrain;
total_manager_drain = subsystem_drain + manager_drain;
//TotalPowerDrain += total_manager_drain;
//Recharge reserve power if main power is above a certain threshold
if (ManagerIsActive && (TotalElectricCharge > 0) && (TotalElectricCharge / TotalElectricChargeCapacity > AYsettings.RECHARGE_RESERVE_THRESHOLD)
&& (TotalReservePower < TotalReservePowerCapacity))
TransferMainToReserve(RECHARGE_RESERVE_RATE * TimeWarp.fixedDeltaTime);
//Store the AmpYear Manager and Subsystems into the parts list
prtName = "AmpYear SubSystems";
uint partId = CalcAmpYearMgrPartID();
for (int i = LoadGlobals.SubsystemArrayCache.Length - 1; i >= 0; --i)
{
if (!KKPresent && (LoadGlobals.SubsystemArrayCache[i] == Subsystem.CLIMATE || LoadGlobals.SubsystemArrayCache[i] == Subsystem.MASSAGE || LoadGlobals.SubsystemArrayCache[i] == Subsystem.MUSIC))
continue;
AYVesselPartLists.AddPart(partId, prtName, prtName, SubsystemName(LoadGlobals.SubsystemArrayCache[i]), true, SubsystemEnabled(LoadGlobals.SubsystemArrayCache[i]), _subsystemDrain[(int)LoadGlobals.SubsystemArrayCache[i]], false, false, currentVessel.rootPart);
}
if (AYsettings.AYMonitoringUseEC)
{
prtName = "AmpYear Manager";
AYVesselPartLists.AddPart(partId, prtName, prtName, prtName, true, _managerEnabled,(float) manager_drain, false, false, currentVessel.rootPart);
}
//Drain main power
//double currentTime = Planetarium.GetUniversalTime();
//double timestepDrain = total_manager_drain * TimeWarp.fixedDeltaTime;
minimumSufficientCharge = managerActiveDrain + 4;
deltaTime = Math.Min(currentTime - _timeLastElectricity, Math.Max(1, TimeWarp.fixedDeltaTime));
desiredElectricity = total_manager_drain * deltaTime;
if (desiredElectricity > 0.0 && TimewarpIsValid) // if power required > 0 and time warp is valid
{
if (TotalElectricCharge >= desiredElectricity) // if main power >= power required
{
Utilities.Log_Debug("drawing main power");
double totalAvailable = 0f;
Utilities.requireResource(FlightGlobals.ActiveVessel, MAIN_POWER_NAME, desiredElectricity, true,
true, false, out totalElecreceived, out totalAvailable); //get power
_timeLastElectricity = currentTime - (desiredElectricity - totalElecreceived) / total_manager_drain; //set time last power received
hasPower = (UnityEngine.Time.realtimeSinceStartup > _powerUpTime)
&& (desiredElectricity <= 0.0 || totalElecreceived >= desiredElectricity * 0.99); //set hasPower > power up delay and we received power requested
}
else //not enough main power try reserve power
{
hasPower = TotalElectricCharge >= minimumSufficientCharge; //set hasPower
Utilities.Log_Debug("drawing reserve power");
if (TotalReservePower > minimumSufficientCharge && !_lockReservePower) // if reserve power available > minimum charge required
{
//If main power is insufficient, drain reserve power for manager
//double managerTimestepDrain = manager_drain * TimeWarp.fixedDeltaTime; //we only drain manager function
//double deltaTime2 = Math.Min(currentTime - _timeLastElectricity, Math.Max(1, TimeWarp.fixedDeltaTime));
desiredElectricity2 = manager_drain * deltaTime;
double totalAvailable = 0f;
Utilities.requireResource(FlightGlobals.ActiveVessel, RESERVE_POWER_NAME, desiredElectricity2, true,
true, false, out totalElecreceived2, out totalAvailable); //get power
_timeLastElectricity = currentTime - (desiredElectricity2 - totalElecreceived2) / manager_drain; // set time last power received
HasReservePower = (UnityEngine.Time.realtimeSinceStartup > _powerUpTime)
&& (desiredElectricity2 <= 0.0 || totalElecreceived2 >= desiredElectricity2 * 0.99); // set hasReservePower > power up delay and we received power
}
else // not enough reservepower
{
if (_lockReservePower)
Utilities.Log_Debug("reserve power is isolated");
else
Utilities.Log_Debug("not enough reserve power");
HasReservePower = TotalReservePower > minimumSufficientCharge; //set hasReservePower
_timeLastElectricity += currentTime - _lastUpdate; //set time we last received electricity to current time - last update
}
}
}
else // no electricity required OR time warp is too high (so we hibernate)
{
Utilities.Log_Debug("Timewarp not valid or elec < 0");
_timeLastElectricity += currentTime - _lastUpdate;
}
//Do ESP checking and processing.
ProcessEmergencyShutdownChecking();
if (!hasPower) //some processing if we are out of power
{
Utilities.Log_Debug("no main power processing");
if (UnityEngine.Time.realtimeSinceStartup > _powerUpTime)
//reset the power up delay - for powering back up to avoid rapid flickering of the system
{
Utilities.Log_Debug("reset power up delay");
_powerUpTime = UnityEngine.Time.realtimeSinceStartup + POWER_UP_DELAY;
Utilities.Log_Debug("powerup time = " + _powerUpTime);
}
HasReservePower = TotalReservePower > minimumSufficientCharge; //set hasReservePower
hasPower = TotalElectricCharge >= minimumSufficientCharge; //set hasPower
Utilities.Log_Debug("hasReservePower = " + HasReservePower);
Utilities.Log_Debug("hasPower = " + hasPower);
}
_lastUpdate = currentTime;
}
//This is the Logic that Executes in the Editor (VAB/SPH)
if (HighLogic.LoadedSceneIsEditor)
{
//Calculate total drain from subsystems
subsystem_drain = 0.0;
manager_drain = 0.0;
prtName = "AmpYear SubSystems-Max";
prtPower = "";
uint partId = CalcAmpYearMgrPartID();
for (int i = LoadGlobals.SubsystemArrayCache.Length - 1; i >= 0; --i)
{
_subsystemDrain[(int)LoadGlobals.SubsystemArrayCache[i]] = SubsystemActiveDrain(LoadGlobals.SubsystemArrayCache[i]);
subsystem_drain += _subsystemDrain[(int)LoadGlobals.SubsystemArrayCache[i]];
if (!KKPresent && (LoadGlobals.SubsystemArrayCache[i] == Subsystem.CLIMATE || LoadGlobals.SubsystemArrayCache[i] == Subsystem.MASSAGE || LoadGlobals.SubsystemArrayCache[i] == Subsystem.MUSIC))
continue;
AYVesselPartLists.AddPart(partId, prtName, prtName, SubsystemName(LoadGlobals.SubsystemArrayCache[i]), true, true, _subsystemDrain[(int)LoadGlobals.SubsystemArrayCache[i]], false, false, EditorLogic.RootPart);
}
manager_drain = ManagerCurrentDrain;
if (AYsettings.AYMonitoringUseEC)
{
prtName = "AmpYear Manager";
AYVesselPartLists.AddPart(partId, prtName, prtName, prtName, true, _managerEnabled, manager_drain,false, false, EditorLogic.RootPart);
}
hasPower = true;
HasReservePower = true;
}
}
#region VesselFunctions
//Vessel Functions Follow - to store list of vessels and store/retrieve AmpYear settings for each vessel
private void CheckVslUpdate()
{
// Called every fixed update from fixedupdate
// also updates current active vessel details/settings
//*Update the current vessel
if (AYgameSettings.KnownVessels.TryGetValue(Currentvesselid, out currvesselInfo))