-
Notifications
You must be signed in to change notification settings - Fork 228
/
kOSProcessor.cs
934 lines (800 loc) · 36.5 KB
/
kOSProcessor.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
using kOS.Binding;
using kOS.Callback;
using kOS.Execution;
using kOS.Communication;
using kOS.Persistence;
using kOS.Safe;
using kOS.Safe.Compilation;
using kOS.Safe.Compilation.KS;
using kOS.Safe.Module;
using kOS.Safe.Persistence;
using kOS.Safe.Screen;
using kOS.Safe.Utilities;
using kOS.Utilities;
using KSP.IO;
using System;
using System.Collections.Generic;
using System.Linq;
using kOS.Safe.Execution;
using UnityEngine;
using kOS.Safe.Encapsulation;
using KSP.UI;
using kOS.Suffixed;
using kOS.Safe.Function;
namespace kOS.Module
{
public class kOSProcessor : PartModule, IProcessor, IPartCostModifier, IPartMassModifier
{
public ProcessorModes ProcessorMode { get; private set; }
public Harddisk HardDisk { get; private set; }
public Archive Archive { get; private set; }
public MessageQueue Messages { get; private set; }
public string Tag
{
get
{
KOSNameTag tag = part.Modules.OfType<KOSNameTag>().FirstOrDefault();
return tag == null ? string.Empty : tag.nameTag;
}
}
private int vesselPartCount;
private SharedObjects shared;
private static readonly List<kOSProcessor> allMyInstances = new List<kOSProcessor>();
private bool firstUpdate = true;
private bool objectsInitialized = false;
public float AdditionalMass { get; set; }
/// How many times have instances of this class been constructed during this process run?
private static int constructorCount;
private int kOSCoreId;
/// <summary>Can be used as a unique ID of which processor this is, but unlike Guid,
/// it doesn't remain unique across runs so you shouldn't use it for serialization.</summary>
public int KOSCoreId { get { return kOSCoreId; } }
private MovingAverage averagePower = new MovingAverage();
// This is the "constant" byte count used when calculating the EC
// required by the archive volume (which has infinite space).
// TODO: This corresponds to the existing value and should be adjusted for balance.
private const int ARCHIVE_EFFECTIVE_BYTES = 50000;
private const string BootDirectoryName = "boot";
[KSPField(isPersistant = true, guiActive = false, guiActiveEditor = true, guiName = "Boot File"), UI_ChooseOption(scene = UI_Scene.Editor)]
public string bootFile = "None";
[KSPField(isPersistant = true, guiName = "kOS Disk Space", guiActive = true)]
public int diskSpace = 1024;
[KSPField(isPersistant = true, guiName = "kOS Base Disk Space", guiActive = false)]
public int baseDiskSpace = 0;
[KSPField(isPersistant = false, guiName = "kOS Base Module Cost", guiActive = false)]
public float baseModuleCost = 0F; // this is the base cost added to a part for including the kOSProcessor, default to 0.
[KSPField(isPersistant = true, guiName = "kOS Base Module Mass", guiActive = false)]
public float baseModuleMass = 0F; // this is the base mass added to a part for including the kOSProcessor, default to 0.
[KSPField(isPersistant = false, guiName = "kOS Disk Space", guiActive = false, guiActiveEditor = true), UI_ChooseOption(scene = UI_Scene.Editor)]
public string diskSpaceUI = "1024";
[KSPField(isPersistant = true, guiName = "CPU/Disk Upgrade Cost", guiActive = false, guiActiveEditor = true)]
public float additionalCost = 0F;
[KSPField(isPersistant = false, guiName = "CPU/Disk Upgrade Mass", guiActive = false, guiActiveEditor = true, guiUnits = "Kg", guiFormat = "0.00")]
public float additionalMassGui = 0F;
[KSPField(isPersistant = false, guiActive = false, guiActiveEditor = false)]
public float diskSpaceCostFactor = 0.0244140625F; //implies approx 100funds for 4096bytes of diskSpace
[KSPField(isPersistant = false, guiActive = false, guiActiveEditor = false)]
public float diskSpaceMassFactor = 0.0000000048829F; //implies approx 0.020kg for 4096bytes of diskSpace
[KSPField(isPersistant = true, guiActive = false)]
public int MaxPartId = 100;
// This represents how much EC to consume per executed instruction.
// This would be the "variable" component of the processor's power.
// Important: This value should be overriden in the part.cfg file
// for the kOS processor. The only reason it's being given a value
// here is as a fallback for those cases where an old legacy part
// might be loaded from before the part files had this value.
[KSPField(isPersistant = false, guiActive = false)]
public float ECPerInstruction = 0.000004F;
// This represents how much EC to consume per Byte of the current volume, per second.
// This would be the "continuous" compoenent of the processor's power (though it varies
// when you change to another volume).
// IMPORTANT: The value defaults to zero and must be overriden in the module
// definition for any given part (within the part.cfg file).
[KSPField(isPersistant = false, guiActive = false)]
public float ECPerBytePerSecond = 0F;
public kOSProcessor()
{
ProcessorMode = ProcessorModes.READY;
kOSCoreId = ++constructorCount;
}
public VolumePath BootFilePath {
get
{
if (string.IsNullOrEmpty(bootFile) || bootFile.Equals("None", StringComparison.OrdinalIgnoreCase))
return null;
return VolumePath.FromString(bootFile);
}
}
[KSPEvent(guiActive = true, guiName = "Open Terminal", category = "skip_delay;")]
public void Activate()
{
SafeHouse.Logger.Log("Activate");
OpenWindow();
}
[KSPField(isPersistant = true, guiName = "kOS Average Power", guiActive = true, guiActiveEditor = true, guiUnits = "EC/s", guiFormat = "0.000")]
public float RequiredPower = 0;
[KSPEvent(guiActive = true, guiName = "Toggle Power")]
public void TogglePower()
{
SafeHouse.Logger.Log("Toggle Power");
ProcessorModes newProcessorMode = (ProcessorMode != ProcessorModes.OFF) ? ProcessorModes.OFF : ProcessorModes.STARVED;
SetMode(newProcessorMode);
}
[KSPAction("Open Terminal", actionGroup = KSPActionGroup.None)]
public void Activate(KSPActionParam param)
{
SafeHouse.Logger.Log("Open Terminal from Dialog");
Activate();
}
[KSPAction("Close Terminal", actionGroup = KSPActionGroup.None)]
public void Deactivate(KSPActionParam param)
{
SafeHouse.Logger.Log("Close Terminal from ActionGroup");
CloseWindow();
}
[KSPAction("Toggle Terminal", actionGroup = KSPActionGroup.None)]
public void Toggle(KSPActionParam param)
{
SafeHouse.Logger.Log("Toggle Terminal from ActionGroup");
ToggleWindow();
}
[KSPAction("Toggle Power", actionGroup = KSPActionGroup.None)]
public void TogglePower(KSPActionParam param)
{
SafeHouse.Logger.Log("Toggle Power from ActionGroup");
TogglePower();
}
public void OpenWindow()
{
shared.Window.Open();
}
public void CloseWindow()
{
shared.Window.Close();
}
public void ToggleWindow()
{
shared.Window.Toggle();
}
public bool WindowIsOpen()
{
return shared.Window.IsOpen;
}
public bool TelnetIsAttached()
{
return shared.Window.NumTelnets() > 0;
}
public IScreenBuffer GetScreen()
{
return shared.Screen;
}
// TODO - later refactor making this kOS.Safer so it can work on ITermWindow, which also means moving all of UserIO's classes too.
public Screen.TermWindow GetWindow()
{
if (shared.Window != null)
return shared.Window;
return GetComponent<Screen.TermWindow>();
}
//returns basic information on kOSProcessor module in Editor
public override string GetInfo()
{
int defaultAvgInstructions = 200;
string format =
"Default disk capacity: {0}\n\n" +
"<color=#99ff00ff>Requires:</color>\n" +
" - ElectricCharge: {1}\n" +
"<color=#99ff00ff>Example:</color>\n" +
" - {2:N3}EC/s if IPU={3} and no wait instructions.";
// For the sake of GetInfo, prorate the EC usage based on the smallest physics frame currently selected
// Because this is called before the part is set, we need to manually calculate it instead of letting Update handle it.
double power = diskSpace * ECPerBytePerSecond + defaultAvgInstructions * ECPerInstruction / Time.fixedDeltaTime;
string chargeText = (ECPerInstruction == 0) ?
"None. It's powered by pure magic ... apparently." : // for cheaters who use MM or editing part.cfg, to get rid of it.
string.Format("1 per {0} instructions executed", (int)(1 / ECPerInstruction));
return string.Format(format, diskSpace, chargeText, power, defaultAvgInstructions);
}
//implement IPartCostModifier component
public float GetModuleCost(float defaultCost, ModifierStagingSituation sit)
{
// the 'sit' arg is irrelevant to us, but the interface requires it.
return baseModuleCost + additionalCost;
}
//implement IPartMassModifier component
public ModifierChangeWhen GetModuleCostChangeWhen()
{
return ModifierChangeWhen.FIXED;
}
private void UpdateCostAndMass()
{
float spaceDelta = diskSpace - baseDiskSpace;
additionalCost = (float)System.Math.Round(spaceDelta * diskSpaceCostFactor, 0);
AdditionalMass = spaceDelta * diskSpaceMassFactor;
additionalMassGui = AdditionalMass * 1000;
}
//implement IPartMassModifier component
public float GetModuleMass(float defaultMass, ModifierStagingSituation sit)
{
// the 'sit' arg is irrelevant to us, but the interface requires it.
return baseModuleMass + AdditionalMass;
}
//implement IPartMassModifier component
public ModifierChangeWhen GetModuleMassChangeWhen()
{
return ModifierChangeWhen.FIXED;
}
public override void OnStart(StartState state)
{
try
{
//if in Editor, populate boot script selector, diskSpace selector and etc.
if (state == StartState.Editor)
{
if (baseDiskSpace == 0)
baseDiskSpace = diskSpace;
InitUI();
}
UpdateCostAndMass();
//Do not start from editor and at KSP first loading
if (state == StartState.Editor || state == StartState.None)
{
return;
}
SafeHouse.Logger.Log(string.Format("OnStart: {0} {1}", state, ProcessorMode));
InitObjects();
} catch (Exception e)
{
SafeHouse.Logger.LogException(e);
}
}
private void InitUI()
{
//Populate selector for boot scripts
BaseField field = Fields["bootFile"];
var options = (UI_ChooseOption)field.uiControlEditor;
var bootFiles = new List<VolumePath>();
bootFiles.AddRange(BootDirectoryFiles());
//no need to show the control if there are no available boot files
options.controlEnabled = bootFiles.Count >= 1;
field.guiActiveEditor = bootFiles.Count >= 1;
var availableOptions = bootFiles.Select(e => e.ToString()).ToList();
var availableDisplays = bootFiles.Select(e => e.Name).ToList();
availableOptions.Insert(0, "None");
availableDisplays.Insert(0, "None");
var bootFilePath = BootFilePath; // store the selected path temporarily
if (bootFilePath != null && !bootFiles.Contains(bootFilePath))
{
// if the path is not null ("None", null, or empty) and if it isn't in list of files
var archive = new Archive(SafeHouse.ArchiveFolder);
var file = archive.Open(bootFilePath) as VolumeFile; // try to open the file as saved
if (file == null)
{
// check the same file name, but in the boot directory.
var path = VolumePath.FromString(BootDirectoryName).Combine(bootFilePath.Name);
file = archive.Open(path) as VolumeFile; // try to open the new path
if (file == null)
{
// try the file name without "boot" prefix
var name = bootFilePath.Name;
if (name.StartsWith("boot", StringComparison.OrdinalIgnoreCase) && name.Length > 4)
{
// strip the boot prefix and try that file name
name = name.Substring(4);
path = VolumePath.FromString(BootDirectoryName).Combine(name);
file = name.StartsWith(".") ? null : archive.Open(path) as VolumeFile; // try to open the new path
if (file == null)
{
// try the file name without "boot_" prefix
if (name.StartsWith("_", StringComparison.OrdinalIgnoreCase) && name.Length > 1)
{
// only need to strip "_" here
name = name.Substring(1);
path = VolumePath.FromString(BootDirectoryName).Combine(name);
file = name.StartsWith(".") ? null : archive.Open(path) as VolumeFile; // try to open the new path
}
}
}
}
}
// now, if we have a file object, use its values.
if (file != null)
{
// store the boot file information
bootFile = file.Path.ToString();
if (!bootFiles.Contains(file.Path))
{
availableOptions.Insert(1, bootFile);
availableDisplays.Insert(1, "*" + file.Path.Name); // "*" is indication the file is not normally available
}
}
}
SafeHouse.Logger.SuperVerbose("bootFile: " + bootFile);
options.options = availableOptions.ToArray();
options.display = availableDisplays.ToArray();
//populate diskSpaceUI selector
diskSpaceUI = diskSpace.ToString();
field = Fields["diskSpaceUI"];
options = (UI_ChooseOption)field.uiControlEditor;
var sizeOptions = new string[3];
sizeOptions[0] = baseDiskSpace.ToString();
sizeOptions[1] = (baseDiskSpace * 2).ToString();
sizeOptions[2] = (baseDiskSpace * 4).ToString();
options.options = sizeOptions;
}
private IEnumerable<VolumePath> BootDirectoryFiles()
{
var result = new List<VolumePath>();
var archive = new Archive(SafeHouse.ArchiveFolder);
var path = VolumePath.FromString(BootDirectoryName);
var bootDirectory = archive.Open(path) as VolumeDirectory;
if (bootDirectory == null)
{
return result;
}
var files = bootDirectory.List();
foreach (KeyValuePair<string, VolumeItem> pair in files)
{
if (pair.Value is VolumeFile && (pair.Value.Extension.Equals(Volume.KERBOSCRIPT_EXTENSION)
|| pair.Value.Extension.Equals(Volume.KOS_MACHINELANGUAGE_EXTENSION)))
{
result.Add(pair.Value.Path);
}
}
return result;
}
public void InitObjects()
{
if (objectsInitialized)
{
SafeHouse.Logger.SuperVerbose("kOSProcessor.InitObjects() - objects already initialized");
return;
}
objectsInitialized = true;
shared = new SharedObjects();
shared.Vessel = vessel;
shared.Processor = this;
shared.KSPPart = part;
shared.UpdateHandler = new UpdateHandler();
shared.BindingMgr = new BindingManager(shared);
shared.Interpreter = new Screen.ConnectivityInterpreter(shared);
shared.Screen = shared.Interpreter;
shared.ScriptHandler = new KSScript();
shared.Logger = new KSPLogger(shared);
shared.VolumeMgr = new ConnectivityVolumeManager(shared);
shared.ProcessorMgr = new ProcessorManager();
shared.FunctionManager = new FunctionManager(shared);
shared.TransferManager = new TransferManager(shared);
shared.Cpu = new CPU(shared);
shared.AddonManager = new AddOns.AddonManager(shared);
shared.GameEventDispatchManager = new GameEventDispatchManager(shared);
// Make the window that is going to correspond to this kOS part:
shared.Window = gameObject.AddComponent<Screen.TermWindow>();
shared.Window.AttachTo(shared);
shared.SoundMaker = shared.Window.GetSoundMaker();
// initialize archive
Archive = new Archive(SafeHouse.ArchiveFolder);
shared.VolumeMgr.Add(Archive);
Messages = new MessageQueue();
// initialize harddisk
if (HardDisk == null)
{
HardDisk = new Harddisk(diskSpace);
if (!string.IsNullOrEmpty(Tag))
{
HardDisk.Name = Tag;
}
var path = BootFilePath;
// populate it with the boot file, but only if using a new disk:
if (path != null && !SafeHouse.Config.StartOnArchive)
{
var bootVolumeFile = Archive.Open(BootFilePath) as VolumeFile;
if (bootVolumeFile != null)
{
if (HardDisk.SaveFile(BootFilePath, bootVolumeFile.ReadAll()) == null)
{
// Throwing an exception during InitObjects will break the initialization and won't show
// the error to the user. So we just log the error instead. At some point in the future
// it would be nice to queue up these init errors and display them to the user somewhere.
SafeHouse.Logger.LogError("Error copying boot file to local volume: not enough space.");
}
}
}
}
shared.VolumeMgr.Add(HardDisk);
// process setting
if (!SafeHouse.Config.StartOnArchive)
{
shared.VolumeMgr.SwitchTo(HardDisk);
}
// initialize processor mode if different than READY
if (ProcessorMode != ProcessorModes.READY)
{
ProcessorModeChanged();
}
InitProcessorTracking();
}
private void InitProcessorTracking()
{
// Track a list of all instances of me that exist:
if (!allMyInstances.Contains(this))
{
allMyInstances.Add(this);
allMyInstances.Sort(delegate(kOSProcessor a, kOSProcessor b)
{
// sort "nulls" first:
if (a.part == null || a.part.vessel == null)
return -1;
if (b.part == null || b.part.vessel == null)
return 1;
// If on different vessels, sort by vessel name next:
int compare = string.Compare(a.part.vessel.vesselName, b.part.vessel.vesselName,
StringComparison.CurrentCultureIgnoreCase);
// If on same vessel, sort by part UID last:
if (compare != 0)
return compare;
return (a.part.uid() < b.part.uid()) ? -1 : (a.part.uid() > b.part.uid()) ? 1 : 0;
});
}
}
public void OnDestroy()
{
SafeHouse.Logger.SuperVerbose("kOSProcessor.OnDestroy()!");
allMyInstances.RemoveAll(m => m == this);
if (shared != null)
{
shared.Cpu.BreakExecution(false);
shared.Cpu.Dispose();
shared.DestroyObjects();
shared = null;
}
}
/// <summary>
/// Return a list of all existing runtime instances of this PartModule.
/// The list is guaranteed to be ordered by the Vessel that it's on.
/// (i.e. all the instances of no vessel are first ,then all the module instances
/// on vessel A, then all the instances on vessel B, and so on)
/// </summary>
/// <returns></returns>
public static List<kOSProcessor> AllInstances()
{
// Doing it this way to force return value to be a shallow-level copy,
// rather than an exact reference to the internal private list.
// So if the caller adds/removes from it, it won't mess with the
// private list we're internally maintaining:
return allMyInstances.GetRange(0, allMyInstances.Count);
}
public void RegisterkOSExternalFunction(object[] parameters)
{
//SafeHouse.Logger.Log("*** External Function Registration Succeeded");
//cpu.RegisterkOSExternalFunction(parameters);
}
public static int AssignNewId()
{
var config = PluginConfiguration.CreateForType<kOSProcessor>();
config.load();
var id = config.GetValue<int>("CpuIDMax") + 1;
config.SetValue("CpuIDMax", id);
config.save();
return id;
}
public void Update()
{
if (HighLogic.LoadedScene == GameScenes.EDITOR && EditorLogic.fetch != null)
{
if (diskSpace != Convert.ToInt32(diskSpaceUI))
{
diskSpace = Convert.ToInt32(diskSpaceUI);
UpdateCostAndMass();
GameEvents.onEditorShipModified.Fire(EditorLogic.fetch.ship);
}
RequiredPower = this.diskSpace * ECPerBytePerSecond + SafeHouse.Config.InstructionsPerUpdate * ECPerInstruction / Time.fixedDeltaTime;
}
if (!IsAlive()) return;
UpdateVessel();
UpdateObservers();
}
public void FixedUpdate()
{
if (!IsAlive()) return;
if (!vessel.HoldPhysics)
{
if (firstUpdate)
{
SafeHouse.Logger.LogWarning("First Update()");
firstUpdate = false;
shared.Cpu.Boot();
}
UpdateVessel();
UpdateFixedObservers();
ProcessElectricity(part, TimeWarp.fixedDeltaTime);
}
}
private void UpdateVessel()
{
if (shared != null && shared.Vessel != vessel)
{
shared.Vessel = vessel;
}
}
private void UpdateObservers()
{
if (ProcessorMode == ProcessorModes.READY)
{
if (shared.UpdateHandler != null) shared.UpdateHandler.UpdateObservers(TimeWarp.deltaTime);
UpdateParts();
}
}
private void UpdateFixedObservers()
{
if (ProcessorMode == ProcessorModes.READY)
{
if (shared.UpdateHandler != null) shared.UpdateHandler.UpdateFixedObservers(TimeWarp.fixedDeltaTime);
}
}
private bool IsAlive()
{
if (shared == null) return false;
if (part.State == PartStates.DEAD)
{
ProcessorMode = ProcessorModes.OFF;
return false;
}
return true;
}
public void UpdateParts()
{
// Trigger whenever the number of parts in the vessel changes (like when staging, docking or undocking).
if (vessel.parts.Count == vesselPartCount) return;
var missingHardDisks = false;
var attachedVolumes = new List<Volume>();
var processors = new List<kOSProcessor>();
// Look for all the processors that exists in the vessel
foreach (var partObj in vessel.parts)
{
kOSProcessor processorPart;
if (!PartIsKosProc(partObj, out processorPart)) continue;
processors.Add(processorPart);
// A harddisk may be null because the kOS part haven't been initialized yet
// Wait until the next update and everything should be fine
if (processorPart.HardDisk != null)
{
attachedVolumes.Add(processorPart.HardDisk);
}
else
{
missingHardDisks = true;
break;
}
}
if (missingHardDisks) return;
shared.VolumeMgr.UpdateVolumes(attachedVolumes);
shared.ProcessorMgr.UpdateProcessors(processors);
vesselPartCount = vessel.parts.Count;
}
public bool PartIsKosProc(Part input, out kOSProcessor proc)
{
foreach (var processor in input.Modules.OfType<kOSProcessor>())
{
proc = processor;
return true;
}
proc = null;
return false;
}
public override void OnFixedUpdate()
{
}
public override void OnInactive()
{
SafeHouse.Logger.Log("Processor Stop");
}
public override void OnLoad(ConfigNode node)
{
SafeHouse.Logger.SuperVerbose("kOSProcessor.OnLoad");
try
{
// KSP Seems to want to make an instance of my partModule during initial load
if (vessel == null) return;
if (node.HasValue("activated") && !bool.Parse(node.GetValue("activated")))
{
ProcessorMode = ProcessorModes.OFF;
}
if (node.HasNode("harddisk"))
{
var newDisk = node.GetNode("harddisk").ToHardDisk();
HardDisk = newDisk;
}
InitObjects();
base.OnLoad(node);
}
catch (Exception ex) //Intentional Pokemon, if exceptions get out of here it can kill the craft
{
SafeHouse.Logger.Log("ONLOAD Exception: " + ex.TargetSite);
SafeHouse.Logger.LogException(ex);
}
}
public override void OnSave(ConfigNode node)
{
try
{
node.AddValue("activated", ProcessorMode != ProcessorModes.OFF);
if (HardDisk != null)
{
ConfigNode hdNode = HardDisk.ToConfigNode("harddisk");
node.AddNode(hdNode);
}
if (shared != null && shared.Cpu != null)
{
SafeHouse.Config.SaveConfig();
}
base.OnSave(node);
}
catch (Exception ex) //Intentional Pokemon, if exceptions get out of here it can kill the craft
{
SafeHouse.Logger.Log("ONSAVE Exception: " + ex.TargetSite);
SafeHouse.Logger.LogException(ex);
}
}
// This is what KSP calls during the initial loading screen (the screen
// with the progress bar and all of the "Turning correct end toward space"
// funny messages.) This is where kOS *should* be putting all the
// static initializing that does not change per-part, or per-vessel
// or per-CPU. It might be true that some of what we're doing up above
// in OnLoad and OnStart might really belong here.
//
// At some future point it would be a really good idea to look very carefully
// at *everything* being done during those initialzations and see if any of
// those steps really are meant to be static do-once steps that belong here
// instead:
public override void OnAwake()
{
Opcode.InitMachineCodeData();
CompiledObject.InitTypeData();
}
private void ProcessElectricity(Part partObj, float time)
{
if (ProcessorMode == ProcessorModes.OFF) return;
double volumePower = 0;
if (shared.VolumeMgr.CheckCurrentVolumeRange())
{
// If the current volume is in range, check the capacity and calculate power
var volume = shared.VolumeMgr.CurrentVolume;
if (volume.Name == "Archive")
{
volumePower = ARCHIVE_EFFECTIVE_BYTES * ECPerBytePerSecond;
}
else
{
volumePower = volume.Capacity * ECPerBytePerSecond;
}
}
else
{
// if the volume isn't in range, assume it doesn't consume any power
volumePower = 0;
}
if (ProcessorMode == ProcessorModes.STARVED)
{
// If the processor is STARVED, check to see if there is enough EC to turn it back on.
var request = averagePower.Mean; // use the average power draw as a baseline of the power needed to restart.
if (request > 0)
{
var available = partObj.RequestResource("ElectricCharge", request);
if (available / request > 0.5)
{
SetMode(ProcessorModes.READY);
}
// Since we're just checking to see if there is enough power to restart, return
// the consumed EC. The actual demand value will be drawn on the next update after
// the cpu boots. This should give the ship a chance to collect a little more EC
// before the cpu actually boots.
partObj.RequestResource("ElectricCharge", -available);
}
else
{
// If there is no historical power request, simply turn the processor back on. This
// should not be possible, since it means that some how the processor got set to
// the STARVED mode, even though no power was requested.
SetMode(ProcessorModes.READY);
}
RequiredPower = (float)request; // Make sure RequiredPower matches the average.
}
else
{
// Because the processor is not STARVED, evaluate the power requirement based on actual operation.
// For EC drain purposes, always pretend atleast 1 instruction happened, so idle drain isn't quite zero:
int instructions = System.Math.Max(shared.Cpu.InstructionsThisUpdate, 1);
var request = volumePower * time + instructions * ECPerInstruction;
if (request > 0)
{
// only check the available EC if the request is greater than 0EC. If the request value
// is zero, then available will always be zero and it appears that mono/.net treat
// "0 / 0" as equaling "0", which prevents us from checking the ratio. Since getting
// "0" available of "0" requested is a valid state, the processor mode is only evaluated
// if request is greater than zero.
var available = partObj.RequestResource("ElectricCharge", request);
if (available / request < 0.5)
{
// 0.5 is an arbitrary ratio for triggering the STARVED mode. It allows for some
// fluctuation away from the exact requested EC, ando adds some fuzzy math to how
// we deal with the descreet physics frames. Essentially if there was enough power
// to run for half of a physics frame, the processor stays on.
SetMode(ProcessorModes.STARVED);
}
}
// Set RequiredPower to the average requested power. This should help "de-bounce" the value
// so that it doesn't fluctuate wildly (between 0.2 and 0.000001 in a single frame for example)
RequiredPower = (float)averagePower.Update(request) / TimeWarp.fixedDeltaTime;
}
}
public void SetMode(ProcessorModes newProcessorMode)
{
if (newProcessorMode != ProcessorMode)
{
ProcessorMode = newProcessorMode;
ProcessorModeChanged();
}
}
private void ProcessorModeChanged()
{
switch (ProcessorMode)
{
case ProcessorModes.READY:
if (SafeHouse.Config.StartOnArchive)
{
shared.VolumeMgr.SwitchTo(Archive);
}
else
{
shared.VolumeMgr.SwitchTo(HardDisk);
}
firstUpdate = true; // handle booting the cpu on the next FixedUpdate
if (shared.Interpreter != null) shared.Interpreter.SetInputLock(false);
if (shared.Window != null) shared.Window.IsPowered = true;
foreach (var w in shared.ManagedWindows) w.IsPowered = true;
break;
case ProcessorModes.OFF:
case ProcessorModes.STARVED:
if (shared.Cpu != null) shared.Cpu.BreakExecution(true);
if (shared.Interpreter != null) shared.Interpreter.SetInputLock(true);
if (shared.Window != null) shared.Window.IsPowered = false;
if (shared.SoundMaker != null) shared.SoundMaker.StopAllVoices();
foreach (var w in shared.ManagedWindows) w.IsPowered = false;
break;
}
}
public void ExecuteInterProcCommand(InterProcCommand command)
{
if (command != null)
{
command.Execute(shared);
}
}
public void SetAutopilotMode(int mode)
{
UIStateToggleButton[] modeButtons = FindObjectOfType<VesselAutopilotUI>().modeButtons;
modeButtons.ElementAt(mode).SetState(true);
}
public string BootFilename
{
get { return bootFile; }
set { bootFile = value; }
}
public bool CheckCanBoot()
{
if (shared.VolumeMgr == null) { shared.Logger.Log("No volume mgr"); }
else if (!shared.VolumeMgr.CheckCurrentVolumeRange()) { shared.Logger.LogException(new Safe.Exceptions.KOSVolumeOutOfRangeException("Boot")); }
else if (shared.VolumeMgr.CurrentVolume == null) { shared.Logger.Log("No current volume"); }
else if (shared.ScriptHandler == null) { shared.Logger.Log("No script handler"); }
else
{
return true;
}
return false;
}
public void Send(Structure content)
{
double sentAt = Planetarium.GetUniversalTime();
Messages.Push(Message.Create(content, sentAt, sentAt, VesselTarget.CreateOrGetExisting(shared), Tag));
}
}
}