-
Notifications
You must be signed in to change notification settings - Fork 66
/
ModuleEngineConfigs.cs
1890 lines (1647 loc) · 77.7 KB
/
ModuleEngineConfigs.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using UnityEngine;
using Debug = UnityEngine.Debug;
using RealFuels.TechLevels;
using KSP.UI.Screens;
using KSP.Localization;
namespace RealFuels
{
public struct Gimbal
{
public float gimbalRange;
public float gimbalRangeXP;
public float gimbalRangeXN;
public float gimbalRangeYP;
public float gimbalRangeYN;
public Gimbal(float gimbalRange, float gimbalRangeXP, float gimbalRangeXN, float gimbalRangeYP, float gimbalRangeYN)
{
this.gimbalRange = gimbalRange;
this.gimbalRangeXP = gimbalRangeXP;
this.gimbalRangeXN = gimbalRangeXN;
this.gimbalRangeYP = gimbalRangeYP;
this.gimbalRangeYN = gimbalRangeYN;
}
public string Info()
{
if (new[] { gimbalRange, gimbalRangeXP, gimbalRangeXN, gimbalRangeYP, gimbalRangeYN }.Distinct().Count() == 1)
return $"{gimbalRange:N1}d"; //
if (new[] { gimbalRangeXP, gimbalRangeXN, gimbalRangeYP, gimbalRangeYN }.Distinct().Count() == 1)
return $"{gimbalRangeXP:N1}d"; //
var ret = string.Empty;
if (gimbalRangeXP == gimbalRangeXN)
ret += $"{gimbalRangeXP:N1}d pitch, "; //
else
ret += $"+{gimbalRangeXP:N1}d/-{gimbalRangeXN:N1}d pitch, "; //
if (gimbalRangeYP == gimbalRangeYN)
ret += $"{gimbalRangeYP:N1}d yaw"; //
else
ret += $"+{gimbalRangeYP:N1}d/-{gimbalRangeYN:N1}d yaw"; //
return ret;
}
}
public class ModuleEngineConfigs : ModuleEngineConfigsBase
{
public const string PatchNodeName = "SUBCONFIG";
protected const string PatchNameKey = "__mpecPatchName";
[KSPField(isPersistant = true)]
public string activePatchName = "";
[KSPField(isPersistant = true)]
public bool dynamicPatchApplied = false;
protected bool ConfigHasPatch(ConfigNode config) => GetPatchesOfConfig(config).Count > 0;
protected List<ConfigNode> GetPatchesOfConfig(ConfigNode config)
{
ConfigNode[] list = config.GetNodes(PatchNodeName);
List<ConfigNode> sortedList = ConfigFilters.Instance.FilterDisplayConfigs(list.ToList());
return sortedList;
}
protected ConfigNode GetPatch(string configName, string patchName)
{
return GetPatchesOfConfig(GetConfigByName(configName))
.FirstOrDefault(patch => patch.GetValue("name") == patchName);
}
protected bool ConfigIsPatched(ConfigNode config) => config.HasValue(PatchNameKey);
// TODO: This is called a lot, performance concern?
protected ConfigNode PatchConfig(ConfigNode parentConfig, ConfigNode patch, bool dynamic)
{
var patchedNode = parentConfig.CreateCopy();
foreach (var key in patch.values.DistinctNames())
patchedNode.RemoveValues(key);
foreach (var nodeName in patch.nodes.DistinctNames())
patchedNode.RemoveNodes(nodeName);
patch.CopyTo(patchedNode);
// Apply cost offset
int costOffset = 0;
patch.TryGetValue("costOffset", ref costOffset);
int cost = 0;
patchedNode.TryGetValue("cost", ref cost);
cost += costOffset;
patchedNode.SetValue("cost", cost, true);
patchedNode.SetValue("name", parentConfig.GetValue("name"));
if (!dynamic)
patchedNode.AddValue(PatchNameKey, patch.GetValue("name"));
return patchedNode;
}
public ConfigNode GetNonDynamicPatchedConfiguration() => GetSetConfigurationTarget(configuration);
public void ApplyDynamicPatch(ConfigNode patch)
{
// Debug.Log($"**RFMPEC** dynamic patch applied to active config `{configurationDisplay}`");
SetConfiguration(PatchConfig(GetNonDynamicPatchedConfiguration(), patch, true), false);
dynamicPatchApplied = true;
}
protected override ConfigNode GetSetConfigurationTarget(string newConfiguration)
{
if (activePatchName == "")
return base.GetSetConfigurationTarget(newConfiguration);
return PatchConfig(GetConfigByName(newConfiguration), GetPatch(newConfiguration, activePatchName), false);
}
public override void SetConfiguration(string newConfiguration = null, bool resetTechLevels = false)
{
base.SetConfiguration(newConfiguration, resetTechLevels);
if (dynamicPatchApplied)
{
dynamicPatchApplied = false;
part.SendMessage("OnMPECDynamicPatchReset", SendMessageOptions.DontRequireReceiver);
}
}
public override int UpdateSymmetryCounterparts()
{
DoForEachSymmetryCounterpart((engine) =>
(engine as ModuleEngineConfigs).activePatchName = activePatchName);
return base.UpdateSymmetryCounterparts();
}
public override string GetConfigInfo(ConfigNode config, bool addDescription = true, bool colorName = false)
{
var info = base.GetConfigInfo(config, addDescription, colorName);
if (!ConfigHasPatch(config) || ConfigIsPatched(config))
return info;
if (addDescription) info += "\n";
foreach (var patch in GetPatchesOfConfig(config))
info += ConfigInfoString(PatchConfig(config, patch, false), false, colorName);
return info;
}
public override string GetConfigDisplayName(ConfigNode node)
{
if (node.HasValue("displayName"))
return node.GetValue("displayName");
var name = node.GetValue("name");
if (!node.HasValue(PatchNameKey))
return name;
return $"{name} [Subconfig {node.GetValue(PatchNameKey)}]";
}
protected override void DrawConfigSelectors(IEnumerable<ConfigNode> availableConfigNodes)
{
foreach (var node in availableConfigNodes)
{
DrawSelectButton(
node,
node.GetValue("name") == configuration && activePatchName == "",
(configName) =>
{
activePatchName = "";
GUIApplyConfig(configName);
});
foreach (var patch in GetPatchesOfConfig(node))
{
var patchedNode = PatchConfig(node, patch, false);
string patchName = patch.GetValue("name");
using (new GUILayout.HorizontalScope())
{
GUILayout.Space(30);
DrawSelectButton(
patchedNode,
node.GetValue("name") == configuration && patchName == activePatchName,
(configName) =>
{
activePatchName = patchName;
GUIApplyConfig(configName);
});
}
}
}
}
}
public class ModuleEngineConfigsBase : PartModule, IPartCostModifier, IPartMassModifier
{
private static FieldInfo MRCSConsumedResources = typeof(ModuleRCS).GetField("consumedResources", BindingFlags.NonPublic | BindingFlags.Instance);
//protected const string groupName = "ModuleEngineConfigs";
public const string groupName = ModuleEnginesRF.groupName;
public const string groupDisplayName = "#RF_Engine_EngineConfigs"; // "Engine Configs"
#region Fields
protected bool compatible = true;
[KSPField(isPersistant = true)]
public string configuration = string.Empty;
// For display purposes only.
[KSPField(guiName = "#RF_Engine_Configuration", isPersistant = true, guiActiveEditor = true, guiActive = true, // Configuration
groupName = groupName, groupDisplayName = groupDisplayName)]
public string configurationDisplay = string.Empty;
// Tech Level stuff
[KSPField(isPersistant = true)]
public int techLevel = -1; // default: disable
[KSPField]
public int origTechLevel = -1; // default TL, starts disabled
[KSPField]
public float origMass = -1;
protected float massDelta = 0;
public int? Ignitions { get; protected set; }
[KSPField]
public string gimbalTransform = string.Empty;
[KSPField]
public float gimbalMult = 1f;
[KSPField]
public bool useGimbalAnyway = false;
private Dictionary<string, Gimbal> defaultGimbals = null;
[KSPField]
public bool autoUnlock = true;
[KSPField]
public int maxTechLevel = -1;
[KSPField]
public int minTechLevel = -1;
[KSPField]
public string engineType = "L"; // default = lower stage
[KSPField]
public float throttle = 0.0f; // default min throttle level
public float configThrottle;
public string configDescription = string.Empty;
public ConfigNode techNodes;
[KSPField]
public bool isMaster = true; //is this Module the "master" module on the part? (if false, don't do GUI)
// For TestFlight integration, only ONE ModuleEngineConfigs (or child class) can be master module on a part.
[KSPField]
public string type = "ModuleEnginesRF";
[KSPField]
public bool useWeakType = true; // match any ModuleEngines*
[KSPField]
public string engineID = string.Empty;
[KSPField]
public int moduleIndex = -1;
[KSPField]
public int offsetGUIPos = -1;
[KSPField(isPersistant = true)]
public string thrustRating = "maxThrust";
[KSPField(isPersistant = true)]
public bool modded = false;
[KSPField]
public bool literalZeroIgnitions = false; /* Normally, ignitions = 0 means unlimited. Setting this changes it to really mean zero */
public List<ConfigNode> configs;
internal List<ConfigNode> filteredDisplayConfigs;
public ConfigNode config;
public static Dictionary<string, string> techNameToTitle = new Dictionary<string, string>();
// KIDS integration
public static float ispSLMult = 1.0f;
public static float ispVMult = 1.0f;
[KSPField]
public bool useConfigAsTitle = false;
public float configMaxThrust = 1.0f;
public float configMinThrust = 0.0f;
public float configMassMult = 1.0f;
public float configHeat = 0.0f;
public float configCost = 0f;
public float scale = 1f;
#endregion
#region TestFlight
public void UpdateTFInterops()
{
TestFlightWrapper.AddInteropValue(part, isMaster ? "engineConfig" : "vernierConfig", configuration, "RealFuels");
}
#endregion
#region B9PartSwitch
protected static bool _b9psReflectionInitialized = false;
protected static FieldInfo B9PS_moduleID;
protected static MethodInfo B9PS_SwitchSubtype;
protected static FieldInfo B9PS_switchInFlight;
public Dictionary<string, PartModule> B9PSModules;
protected Dictionary<string, string> RequestedB9PSVariants = new Dictionary<string, string>();
private void InitializeB9PSReflection()
{
if (_b9psReflectionInitialized || !Utilities.B9PSFound) return;
B9PS_moduleID = Type.GetType("B9PartSwitch.CustomPartModule, B9PartSwitch")?.GetField("moduleID");
B9PS_SwitchSubtype = Type.GetType("B9PartSwitch.ModuleB9PartSwitch, B9PartSwitch")?.GetMethod("SwitchSubtype");
B9PS_switchInFlight = Type.GetType("B9PartSwitch.ModuleB9PartSwitch, B9PartSwitch")?.GetField("switchInFlight");
_b9psReflectionInitialized = true;
}
private void LoadB9PSModules()
{
IEnumerable<string> b9psModuleIDs = configs
.Where(cfg => cfg.HasNode("LinkB9PSModule"))
.SelectMany(cfg => cfg.GetNodes("LinkB9PSModule"))
.Select(link => link?.GetValue("name"))
.Where(moduleID => moduleID != null)
.Distinct();
B9PSModules = new Dictionary<string, PartModule>(b9psModuleIDs.Count());
foreach (string moduleID in b9psModuleIDs)
{
var module = GetSpecifiedModules(part, string.Empty, -1, "ModuleB9PartSwitch", false)
.FirstOrDefault(m => (string)B9PS_moduleID?.GetValue(m) == moduleID);
if (module == null)
Debug.LogError($"*RFMEC* B9PartSwitch module with ID {moduleID} was not found for {part}!");
else
B9PSModules[moduleID] = module;
}
}
/// <summary>
/// Hide the GUI for all `ModuleB9PartSwitch`s managed by RF.
/// This is somewhat of a hack-ish approach...
/// </summary>
private void HideB9PSVariantSelectors()
{
if (B9PSModules == null) return;
foreach (var module in B9PSModules.Values)
{
module.Fields["currentSubtypeTitle"].guiActive = false;
module.Fields["currentSubtypeTitle"].guiActiveEditor = false;
module.Fields["currentSubtypeIndex"].guiActive = false;
module.Fields["currentSubtypeIndex"].guiActiveEditor = false;
module.Events["ShowSubtypesWindow"].guiActive = false;
module.Events["ShowSubtypesWindow"].guiActiveEditor = false;
}
}
private IEnumerator HideB9PSInFlightSelector_Coroutine(PartModule module)
{
yield return null;
module.Events["ShowSubtypesWindow"].guiActive = false;
}
protected void RequestB9PSVariantsForConfig(ConfigNode node)
{
if (B9PSModules == null || B9PSModules.Count == 0) return;
RequestedB9PSVariants.Clear();
if (node.GetNodes("LinkB9PSModule") is ConfigNode[] links)
{
foreach (ConfigNode link in links)
{
string moduleID = null, subtype = null;
if (!link.TryGetValue("name", ref moduleID))
Debug.LogError($"*RFMEC* Config `{configurationDisplay}` of {part} has a LinkB9PSModule specification without a name key!");
if (!link.TryGetValue("subtype", ref subtype))
Debug.LogError($"*RFMEC* Config `{configurationDisplay}` of {part} has a LinkB9PSModule specification without a subtype key!");
if (moduleID != null && subtype != null)
RequestedB9PSVariants[moduleID] = subtype;
}
}
StartCoroutine(ApplyRequestedB9PSVariants_Coroutine());
}
protected IEnumerator ApplyRequestedB9PSVariants_Coroutine()
{
yield return new WaitForEndOfFrame();
if (RequestedB9PSVariants.Count == 0) yield break;
foreach (var entry in B9PSModules)
{
string moduleID = entry.Key;
PartModule module = entry.Value;
if (HighLogic.LoadedSceneIsFlight
&& B9PS_switchInFlight != null
&& !(bool)B9PS_switchInFlight.GetValue(module)) continue;
if (!RequestedB9PSVariants.TryGetValue(moduleID, out string subtypeName))
{
Debug.LogError($"*RFMEC* Config {configurationDisplay} of {part} does not specify a subtype for linked B9PS module with ID {moduleID}; defaulting to `{configuration}`.");
subtypeName = configuration;
}
B9PS_SwitchSubtype?.Invoke(module, new object[] { subtypeName });
if (HighLogic.LoadedSceneIsFlight) StartCoroutine(HideB9PSInFlightSelector_Coroutine(module));
}
RequestedB9PSVariants.Clear();
// Clear symmetry counterparts' queues since B9PS already handles symmetry.
DoForEachSymmetryCounterpart(mec => mec.RequestedB9PSVariants.Clear());
}
public void UpdateB9PSVariants() => RequestB9PSVariantsForConfig(config);
#endregion
#region Callbacks
public float GetModuleCost(float stdCost, ModifierStagingSituation sit) => configCost;
public ModifierChangeWhen GetModuleCostChangeWhen() => ModifierChangeWhen.FIXED;
public float GetModuleMass(float defaultMass, ModifierStagingSituation sit) => massDelta;
public ModifierChangeWhen GetModuleMassChangeWhen() => ModifierChangeWhen.FIXED;
[KSPEvent(guiActive = false, active = true)]
void OnPartScaleChanged(BaseEventDetails data)
{
float factorAbsolute = data.Get<float>("factorAbsolute");
float factorRelative = data.Get<float>("factorRelative");
scale = factorAbsolute * factorAbsolute; // quadratic
SetConfiguration();
//Debug.Log($"[RFMEC] OnPartScaleChanged for {part}: factorRelative={factorRelative} | factorAbsolute={factorAbsolute}");
}
#endregion
public static void BuildTechNodeMap()
{
if (techNameToTitle?.Count == 0)
{
string fullPath = KSPUtil.ApplicationRootPath + HighLogic.CurrentGame.Parameters.Career.TechTreeUrl;
ConfigNode treeNode = new ConfigNode();
if (ConfigNode.Load(fullPath) is ConfigNode fileNode && fileNode.TryGetNode("TechTree", ref treeNode))
{
foreach (ConfigNode n in treeNode.GetNodes("RDNode"))
{
if (n.HasValue("id") && n.HasValue("title"))
techNameToTitle[n.GetValue("id")] = n.GetValue("title");
}
}
}
}
private void LoadDefaultGimbals()
{
defaultGimbals = new Dictionary<string, Gimbal>();
foreach (var g in part.Modules.OfType<ModuleGimbal>())
defaultGimbals[g.gimbalTransformName] = new Gimbal(g.gimbalRange, g.gimbalRangeXP, g.gimbalRangeXN, g.gimbalRangeYP, g.gimbalRangeYN);
}
public static void RelocateRCSPawItems(ModuleRCS module)
{
var field = module.Fields["thrusterPower"];
field.guiActive = true;
field.guiActiveEditor = true;
field.guiName = Localizer.GetStringByTag("#RF_Engine_ThrusterPower"); // Thruster Power
field.guiUnits = "kN";
field.group = new BasePAWGroup(groupName, groupDisplayName, false);
}
private List<ConfigNode> FilteredDisplayConfigs(bool update)
{
if (update || filteredDisplayConfigs == null)
{
filteredDisplayConfigs = ConfigFilters.Instance.FilterDisplayConfigs(configs);
}
return filteredDisplayConfigs;
}
#region PartModule Overrides
public override void OnAwake()
{
techNodes = new ConfigNode();
configs = new List<ConfigNode>();
InitializeB9PSReflection();
}
public override void OnLoad(ConfigNode node)
{
if (!compatible)
return;
base.OnLoad(node);
if (techLevel != -1)
{
if (maxTechLevel < 0)
maxTechLevel = TechLevel.MaxTL(node, engineType);
if (minTechLevel < 0)
minTechLevel = Math.Min(origTechLevel, techLevel);
}
if (origMass > 0)
{
part.mass = origMass * RFSettings.Instance.EngineMassMultiplier;
massDelta = (part?.partInfo?.partPrefab is Part p) ? part.mass - p.mass : 0;
}
if (node.GetNodes("CONFIG") is ConfigNode[] cNodes && cNodes.Length > 0)
{
configs.Clear();
foreach (ConfigNode subNode in cNodes)
{
//Debug.Log("*RFMEC* Load Engine Configs. Part " + part.name + " has config " + subNode.GetValue("name"));
ConfigNode newNode = new ConfigNode("CONFIG");
subNode.CopyTo(newNode);
configs.Add(newNode);
}
}
foreach (ConfigNode n in node.GetNodes("TECHLEVEL"))
techNodes.AddNode(n);
ConfigSaveLoad();
SetConfiguration();
}
public override void OnStart(StartState state)
{
if (!compatible)
return;
enabled = true;
BuildTechNodeMap();
Fields[nameof(showRFGUI)].guiActiveEditor = isMaster;
if (HighLogic.LoadedSceneIsEditor)
GameEvents.onPartActionUIDismiss.Add(OnPartActionGuiDismiss);
ConfigSaveLoad();
LoadB9PSModules();
LoadDefaultGimbals();
SetConfiguration();
Fields[nameof(showRFGUI)].guiName = GUIButtonName;
// Why is this here, if KSP will call this normally?
part.Modules.GetModule("ModuleEngineIgnitor")?.OnStart(state);
}
public override void OnStartFinished(StartState state)
{
HideB9PSVariantSelectors();
if (pModule is ModuleRCS mrcs) RelocateRCSPawItems(mrcs);
}
#endregion
#region Info Methods
private string TLTInfo()
{
string retStr = string.Empty;
if (engineID != string.Empty)
retStr += $"{Localizer.Format("#RF_Engine_BoundToEngineID", engineID)}\n"; // (Bound to {engineID})
if (moduleIndex >= 0)
retStr += $"{Localizer.Format("#RF_Engine_BoundToModuleIndex", moduleIndex)}\n"; // (Bound to engine {moduleIndex} in part)
if (techLevel != -1)
{
TechLevel cTL = new TechLevel();
if (!cTL.Load(config, techNodes, engineType, techLevel))
cTL = null;
if (!string.IsNullOrEmpty(configDescription))
retStr += configDescription + "\n";
retStr += $"{Localizer.GetStringByTag("#RF_Engine_TLTInfo_Type")}: {engineType}. {Localizer.GetStringByTag("#RF_Engine_TLTInfo_TechLevel")}: {techLevel} ({origTechLevel}-{maxTechLevel})"; // TypeTech Level
if (origMass > 0)
retStr += $", {Localizer.Format("#RF_Engine_TLTInfo_OrigMass", $"{part.mass:N3}", $"{origMass * RFSettings.Instance.EngineMassMultiplier:N3}")}"; // Mass: {part.mass:N3} (was {origMass * RFSettings.Instance.EngineMassMultiplier:N3})
if (configThrottle >= 0)
retStr += $", {Localizer.GetStringByTag("#RF_Engine_TLTInfo_MinThrust")} {configThrottle:P0}"; // MinThr
float gimbalR = -1f;
if (config.HasValue("gimbalRange"))
gimbalR = float.Parse(config.GetValue("gimbalRange"));
else if (!gimbalTransform.Equals(string.Empty) || useGimbalAnyway)
{
if (cTL != null)
gimbalR = cTL.GimbalRange;
}
if (gimbalR != -1f)
retStr += $", {Localizer.GetStringByTag("#RF_Engine_TLTInfo_Gimbal")} {gimbalR:N1}"; // Gimbal
}
return retStr;
}
virtual public string GetConfigDisplayName(ConfigNode node) => node.GetValue("name");
public override string GetInfo()
{
if (!compatible)
return string.Empty;
var configsToDisplay = FilteredDisplayConfigs(true);
if (configsToDisplay.Count < 2)
return TLTInfo();
string info = TLTInfo() + $"\n{Localizer.GetStringByTag("#RF_Engine_AlternateConfigurations")}:\n"; // Alternate configurations
foreach (ConfigNode config in configsToDisplay)
if (!config.GetValue("name").Equals(configuration))
info += GetConfigInfo(config, addDescription: false, colorName: true);
return info;
}
protected string ConfigInfoString(ConfigNode config, bool addDescription, bool colorName)
{
TechLevel cTL = new TechLevel();
if (!cTL.Load(config, techNodes, engineType, techLevel))
cTL = null;
var info = StringBuilderCache.Acquire();
if (colorName)
info.Append("<color=green>");
info.Append(GetConfigDisplayName(config));
if (colorName)
info.Append("</color>");
info.Append("\n");
if (config.HasValue(thrustRating))
{
info.Append($" {Utilities.FormatThrust(scale * ThrustTL(config.GetValue(thrustRating), config))}");
// add throttling info if present
if (config.HasValue("minThrust"))
info.Append($", {Localizer.GetStringByTag("#RF_Engine_minThrustInfo")} {float.Parse(config.GetValue("minThrust")) / float.Parse(config.GetValue(thrustRating)):P0}"); //min
else if (config.HasValue("throttle"))
info.Append($", {Localizer.GetStringByTag("#RF_Engine_minThrustInfo")} {float.Parse(config.GetValue("throttle")):P0}"); // min
}
else
info.Append($" {Localizer.GetStringByTag("#RF_Engine_UnknownThrust")}"); // Unknown Thrust
if (origMass > 0f)
{
float cMass = scale * origMass * RFSettings.Instance.EngineMassMultiplier;
if (config.HasValue("massMult") && float.TryParse(config.GetValue("massMult"), out float ftmp))
cMass *= ftmp;
info.Append($", {cMass:N3}t");
}
info.Append("\n");
if (config.HasNode("atmosphereCurve"))
{
FloatCurve isp = new FloatCurve();
isp.Load(config.GetNode("atmosphereCurve"));
info.Append($" {Localizer.GetStringByTag("#RF_Engine_Isp")}: {isp.Evaluate(isp.maxTime)} - {isp.Evaluate(isp.minTime)}s\n"); // Isp
}
else if (config.HasValue("IspSL") && config.HasValue("IspV") && cTL != null)
{
float.TryParse(config.GetValue("IspSL"), out float ispSL);
float.TryParse(config.GetValue("IspV"), out float ispV);
ispSL *= ispSLMult * cTL.AtmosphereCurve.Evaluate(1);
ispV *= ispVMult * cTL.AtmosphereCurve.Evaluate(0);
info.Append($" {Localizer.GetStringByTag("#RF_Engine_Isp")}: {ispSL:N0} - {ispV:N0}s\n"); // Isp
}
if (config.HasValue("ratedBurnTime"))
{
if (config.HasValue("ratedContinuousBurnTime"))
info.Append($" {Localizer.GetStringByTag("#RF_Engine_RatedBurnTime")}: {config.GetValue("ratedContinuousBurnTime")}/{config.GetValue("ratedBurnTime")}s\n"); // Rated burn time
else
info.Append($" {Localizer.GetStringByTag("#RF_Engine_RatedBurnTime")}: {config.GetValue("ratedBurnTime")}s\n"); // Rated burn time
}
if (part.HasModuleImplementing<ModuleGimbal>())
{
if (config.HasNode("GIMBAL"))
{
foreach (KeyValuePair<string, Gimbal> kv in ExtractGimbals(config))
{
info.Append($" {Localizer.GetStringByTag("#RF_Engine_TLTInfo_Gimbal")} ({kv.Key}): {kv.Value.Info()}\n"); // Gimbal
}
}
else if (config.HasValue("gimbalRange"))
{
// The extracted gimbals contain `gimbalRange` et al. applied to either a specific
// transform or all the gimbal transforms on the part. Either way, the values
// are all the same, so just take the first one.
var gimbal = ExtractGimbals(config).Values.First();
info.Append($" Gimbal {gimbal.Info()}\n"); //
}
}
if (config.HasValue("ullage") || config.HasValue("ignitions") || config.HasValue("pressureFed"))
{
info.Append(" ");
bool comma = false;
if (config.HasValue("ullage"))
{
info.Append(config.GetValue("ullage").ToLower() == "true" ? Localizer.GetStringByTag("#RF_Engine_ullage") : Localizer.GetStringByTag("#RF_Engine_NoUllage")); // "ullage""no ullage"
comma = true;
}
if (config.HasValue("pressureFed") && config.GetValue("pressureFed").ToLower() == "true")
{
if (comma)
info.Append(", ");
info.Append(Localizer.GetStringByTag("#RF_Engine_pressureFed")); // "pfed"
comma = true;
}
if (config.HasValue("ignitions"))
{
if (int.TryParse(config.GetValue("ignitions"), out int ignitions))
{
if (comma)
info.Append(", ");
if (ignitions > 0)
info.Append(Localizer.Format("#RF_Engine_ignitionsleft", ignitions)); // $"{ignitions} ignition{(ignitions > 1 ? "s" : string.Empty)}"
else if (literalZeroIgnitions && ignitions == 0)
info.Append(Localizer.GetStringByTag("#RF_Engine_GroundIgnitionOnly")); // "ground ignition only"
else
info.Append(Localizer.GetStringByTag("#RF_Engine_unlignitions")); // "unl. ignitions"
}
}
info.Append("\n");
}
if (config.HasValue("cost") && float.TryParse(config.GetValue("cost"), out float cst))
info.Append($" ({scale * cst:N0} {Localizer.GetStringByTag("#RF_Engine_extraCost")} )\n"); // extra cost// FIXME should get cost from TL, but this should be safe
if (addDescription && config.HasValue("description"))
info.Append($"\n {config.GetValue("description")}\n");
return info.ToStringAndRelease();
}
virtual public string GetConfigInfo(ConfigNode config, bool addDescription = true, bool colorName = false)
{
return ConfigInfoString(config, addDescription, colorName);
}
#endregion
#region FX handling
// Stop all effects registered with any config, but not with the current config
private readonly HashSet<string> effectsToStop = new HashSet<string>();
public void SetupFX()
{
List<string> effectsNames = new List<string>
{
"runningEffectName",
"powerEffectName",
"directThrottleEffectName",
"disengageEffectName",
"engageEffectName",
"flameoutEffectName"
};
string val = string.Empty;
IEnumerable<ConfigNode> others = configs.Where(x => !x.GetValue("name").Equals(configuration));
ConfigNode ours = GetConfigByName(configuration);
foreach (string fxName in effectsNames)
{
foreach (ConfigNode cfg in others)
if (cfg.TryGetValue(fxName, ref val))
effectsToStop.Add(val);
if (ours is ConfigNode && ours.TryGetValue(fxName, ref val))
effectsToStop.Remove(val);
}
}
public void StopFX()
{
foreach (var x in effectsToStop)
part?.Effect(x, 0f);
}
#endregion
#region Configuration
public PartModule pModule = null;
protected ConfigNode GetConfigByName(string name) => configs.Find(c => c.GetValue("name") == name);
protected void SetConfiguration(ConfigNode newConfig, bool resetTechLevels)
{
string newConfiguration = newConfig.GetValue("name");
if (configuration != newConfiguration)
{
if (resetTechLevels)
techLevel = origTechLevel;
while (techLevel > 0 && !TechLevel.CanTL(newConfig, techNodes, engineType, techLevel))
--techLevel;
}
// for asmi
if (useConfigAsTitle)
part.partInfo.title = configuration;
configuration = newConfiguration;
configurationDisplay = GetConfigDisplayName(newConfig);
config = new ConfigNode("MODULE");
newConfig.CopyTo(config);
config.name = "MODULE";
if ((pModule = GetSpecifiedModule(part, engineID, moduleIndex, type, useWeakType)) is null)
{
Debug.LogError($"*RFMEC* Could not find appropriate module of type {type}, with ID={engineID} and index {moduleIndex}");
return;
}
Type mType = pModule.GetType();
config.SetValue("name", mType.Name);
ClearFloatCurves(mType, pModule, config, techLevel);
ClearPropellantGauges(mType, pModule);
if (type.Equals("ModuleRCS") || type.Equals("ModuleRCSFX"))
ClearRCSPropellants(config);
else
{ // is an ENGINE
if (pModule is ModuleEngines mE && config.HasNode("PROPELLANT"))
mE.propellants.Clear();
DoConfig(config);
HandleEngineIgnitor(config);
Ignitions = null;
if (config.HasValue("ignitions"))
{
if (int.TryParse(config.GetValue("ignitions"), out int tmpIgnitions))
{
Ignitions = ConfigIgnitions(tmpIgnitions);
config.SetValue("ignitions", Ignitions.Value);
}
if (HighLogic.LoadedSceneIsFlight && vessel?.situation != Vessel.Situations.PRELAUNCH)
config.RemoveValue("ignitions");
}
// Trigger re-computation of the response rate if one is not set explicitly.
if (!config.HasValue("throttleResponseRate")) config.AddValue("throttleResponseRate", 0.0);
if (pModule is ModuleEnginesRF)
(pModule as ModuleEnginesRF).SetScale(1d);
pModule.Load(config);
}
// fix for editor NaN
if (part.Resources.Contains("ElectricCharge") && part.Resources["ElectricCharge"].maxAmount < 0.1)
{ // hacking around a KSP bug here
part.Resources["ElectricCharge"].amount = 0;
part.Resources["ElectricCharge"].maxAmount = 0.1;
}
SetGimbalRange(config);
if (!config.TryGetValue("cost", ref configCost))
configCost = 0;
if (!config.TryGetValue("description", ref configDescription))
configDescription = string.Empty;
UpdateOtherModules(config);
// GUI disabled for now - UpdateTweakableMenu();
// Prior comments suggest firing GameEvents.onEditorShipModified causes problems?
part.SendMessage("OnEngineConfigurationChanged", SendMessageOptions.DontRequireReceiver);
if (HighLogic.LoadedSceneIsEditor && EditorLogic.fetch.ship != null)
{
foreach (Part p in EditorLogic.fetch.ship.parts)
p.SendMessage("UpdateUsedBy", SendMessageOptions.DontRequireReceiver);
}
SetupFX();
UpdateB9PSVariants();
UpdateTFInterops(); // update TestFlight if it's installed
StopFX();
}
/// Allows subclasses to determine the configuration to switch to based on additional info.
/// Used by MPEC to inject the patch if necessary.
virtual protected ConfigNode GetSetConfigurationTarget(string newConfiguration) => GetConfigByName(newConfiguration);
virtual public void SetConfiguration(string newConfiguration = null, bool resetTechLevels = false)
{
if (newConfiguration == null)
newConfiguration = configuration;
ConfigSaveLoad();
if (configs.Count == 0)
{
Debug.LogError($"*RFMEC* configuration set was empty for {part}!");
StopFX();
return;
}
ConfigNode newConfig = GetSetConfigurationTarget(newConfiguration);
if (!(newConfig is ConfigNode))
{
newConfig = configs.First();
string s = newConfig.GetValue("name");
Debug.LogWarning($"*RFMEC* WARNING could not find configuration \"{newConfiguration}\" for part {part.name}: Fallback to \"{s}\".");
newConfiguration = s;
}
SetConfiguration(newConfig, resetTechLevels);
}
virtual protected int ConfigIgnitions(int ignitions)
{
if (ignitions < 0)
{
ignitions = techLevel + ignitions;
if (ignitions < 1)
ignitions = 1;
}
else if (ignitions == 0 && !literalZeroIgnitions)
ignitions = -1;
return ignitions;
}
#region SetConfiguration Tools
private void ClearFloatCurves(Type mType, PartModule pm, ConfigNode cfg, int techLevel)
{
// clear all FloatCurves we need to clear (i.e. if our config has one, or techlevels are enabled)
bool delAtmo = cfg.HasNode("atmosphereCurve") || techLevel >= 0;
bool delDens = cfg.HasNode("atmCurve") || techLevel >= 0;
bool delVel = cfg.HasNode("velCurve") || techLevel >= 0;
foreach (FieldInfo field in mType.GetFields())
{
if (field.FieldType == typeof(FloatCurve) &&
((field.Name.Equals("atmosphereCurve") && delAtmo)
|| (field.Name.Equals("atmCurve") && delDens)
|| (field.Name.Equals("velCurve") && delVel)))
{
field.SetValue(pm, new FloatCurve());
}
}
}
private void ClearPropellantGauges(Type mType, PartModule pm)
{
foreach (FieldInfo field in mType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
{
if (field.FieldType == typeof(Dictionary<Propellant, ProtoStageIconInfo>) &&
field.GetValue(pm) is Dictionary<Propellant, ProtoStageIconInfo> boxes)
{
foreach (ProtoStageIconInfo v in boxes.Values)
{
try
{
if (v is ProtoStageIconInfo)
pm.part.stackIcon.RemoveInfo(v);
}
catch (Exception e)
{
Debug.LogError("*RFMEC* Trying to remove info box: " + e.Message);
}
}
boxes.Clear();
}
}
}
private void ClearRCSPropellants(ConfigNode cfg)
{
List<ModuleRCS> RCSModules = part.Modules.OfType<ModuleRCS>().ToList();
if (RCSModules.Count > 0)
{
DoConfig(cfg);
foreach (var rcsModule in RCSModules)
{
if (cfg.HasNode("PROPELLANT"))
rcsModule.propellants.Clear();
rcsModule.Load(cfg);
List<PartResourceDefinition> res = MRCSConsumedResources.GetValue(rcsModule) as List<PartResourceDefinition>;
res.Clear();
foreach (Propellant p in rcsModule.propellants)
res.Add(p.resourceDef);
}
}
}
private Dictionary<string, Gimbal> ExtractGimbals(ConfigNode cfg)
{
Gimbal ExtractGimbalKeys(ConfigNode c)
{
float.TryParse(c.GetValue("gimbalRange"), out float range);
float xp = 0, xn = 0, yp = 0, yn = 0;
if (!c.TryGetValue("gimbalRangeXP", ref xp))
xp = range;
if (!c.TryGetValue("gimbalRangeXN", ref xn))
xn = range;