-
Notifications
You must be signed in to change notification settings - Fork 96
/
MMPatchLoader.cs
2604 lines (2243 loc) · 101 KB
/
MMPatchLoader.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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using UnityEngine;
using Debug = UnityEngine.Debug;
using ModuleManager.Logging;
using ModuleManager.Extensions;
using NodeStack = ModuleManager.Collections.ImmutableStack<ConfigNode>;
namespace ModuleManager
{
public delegate void ModuleManagerPostPatchCallback();
[SuppressMessage("ReSharper", "StringLastIndexOfIsCultureSpecific.1")]
[SuppressMessage("ReSharper", "StringIndexOfIsCultureSpecific.1")]
public class MMPatchLoader : LoadingSystem
{
private List<string> mods;
public string status = "";
public string errors = "";
public static bool keepPartDB = false;
private string activity = "Module Manager";
private static readonly Dictionary<string, Regex> regexCache = new Dictionary<string, Regex>();
private static string cachePath;
internal static string techTreeFile;
internal static string techTreePath;
internal static string physicsFile;
internal static string physicsPath;
private static string defaultPhysicsPath;
internal static string partDatabasePath;
private static string shaPath;
private UrlDir.UrlFile physicsUrlFile;
private string configSha;
private Dictionary<string, string> filesSha = new Dictionary<string, string>();
private bool useCache = false;
private readonly Stopwatch patchSw = new Stopwatch();
private static readonly List<ModuleManagerPostPatchCallback> postPatchCallbacks = new List<ModuleManagerPostPatchCallback>();
private const float yieldInterval = 1f/30f; // Patch at ~30fps
private IBasicLogger logger;
public IPatchProgress progress;
public static MMPatchLoader Instance { get; private set; }
private void Awake()
{
if (Instance != null)
{
DestroyImmediate(this);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
cachePath = KSPUtil.ApplicationRootPath + Path.DirectorySeparatorChar + "GameData" + Path.DirectorySeparatorChar + "ModuleManager.ConfigCache";
techTreeFile = "GameData" + Path.DirectorySeparatorChar + "ModuleManager.TechTree";
techTreePath = KSPUtil.ApplicationRootPath + Path.DirectorySeparatorChar + techTreeFile;
physicsFile = "GameData" + Path.DirectorySeparatorChar + "ModuleManager.Physics";
physicsPath = KSPUtil.ApplicationRootPath + Path.DirectorySeparatorChar + physicsFile;
defaultPhysicsPath = KSPUtil.ApplicationRootPath + Path.DirectorySeparatorChar + "Physics.cfg";
partDatabasePath = KSPUtil.ApplicationRootPath + Path.DirectorySeparatorChar + "PartDatabase.cfg";
shaPath = KSPUtil.ApplicationRootPath + Path.DirectorySeparatorChar + "GameData" + Path.DirectorySeparatorChar + "ModuleManager.ConfigSHA";
logger = new ModLogger("ModuleManager", Debug.logger);
progress = new PatchProgress(logger);
}
private bool ready;
public override bool IsReady()
{
//return false;
if (ready)
{
patchSw.Stop();
logger.Info("Ran in " + ((float)patchSw.ElapsedMilliseconds / 1000).ToString("F3") + "s");
}
return ready;
}
public override float ProgressFraction() => progress.ProgressFraction;
public override string ProgressTitle()
{
return activity;
}
public override void StartLoad()
{
patchSw.Reset();
patchSw.Start();
progress = new PatchProgress(logger);
ready = false;
// DB check used to track the now fixed TextureReplacer corruption
//checkValues();
StartCoroutine(ProcessPatch());
}
public void Update()
{
if (progress.AppliedPatchCount > 0 && HighLogic.LoadedScene == GameScenes.LOADING)
StatusUpdate();
}
public static void addPostPatchCallback(ModuleManagerPostPatchCallback callback)
{
if (!postPatchCallbacks.Contains(callback))
postPatchCallbacks.Add(callback);
}
private void PrePatchInit()
{
#region List of mods
//string envInfo = "ModuleManager env info\n";
//envInfo += " " + Environment.OSVersion.Platform + " " + ModuleManager.intPtr.ToInt64().ToString("X16") + "\n";
//envInfo += " " + Convert.ToString(ModuleManager.intPtr.ToInt64(), 2) + " " + Convert.ToString(ModuleManager.intPtr.ToInt64() >> 63, 2) + "\n";
//string gamePath = Environment.GetCommandLineArgs()[0];
//envInfo += " Args: " + gamePath.Split(Path.DirectorySeparatorChar).Last() + " " + string.Join(" ", Environment.GetCommandLineArgs().Skip(1).ToArray()) + "\n";
//envInfo += " Executable SHA256 " + FileSHA(gamePath);
//
//log(envInfo);
mods = new List<string>();
string modlist = "compiling list of loaded mods...\nMod DLLs found:\n";
foreach (AssemblyLoader.LoadedAssembly mod in AssemblyLoader.loadedAssemblies)
{
if (string.IsNullOrEmpty(mod.assembly.Location)) //Diazo Edit for xEvilReeperx AssemblyReloader mod
continue;
FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(mod.assembly.Location);
AssemblyName assemblyName = mod.assembly.GetName();
string modInfo = " " + assemblyName.Name
+ " v" + assemblyName.Version
+
(fileVersionInfo.ProductVersion != " " && fileVersionInfo.ProductVersion != assemblyName.Version.ToString()
? " / v" + fileVersionInfo.ProductVersion
: "")
+
(fileVersionInfo.FileVersion != " " &&fileVersionInfo.FileVersion != assemblyName.Version.ToString() && fileVersionInfo.FileVersion != fileVersionInfo.ProductVersion
? " / v" + fileVersionInfo.FileVersion
: "");
modlist += String.Format(" {0,-50} SHA256 {1}\n", modInfo, FileSHA(mod.assembly.Location));
if (!mods.Contains(assemblyName.Name, StringComparer.OrdinalIgnoreCase))
mods.Add(assemblyName.Name);
}
modlist += "Non-DLL mods added (:FOR[xxx]):\n";
foreach (UrlDir.UrlConfig cfgmod in GameDatabase.Instance.root.AllConfigs)
{
string name;
if (ParseCommand(cfgmod.type, out name) != Command.Insert)
{
progress.PatchAdded();
if (name.Contains(":FOR["))
{
name = RemoveWS(name);
// check for FOR[] blocks that don't match loaded DLLs and add them to the pass list
try
{
string dependency = name.Substring(name.IndexOf(":FOR[") + 5);
dependency = dependency.Substring(0, dependency.IndexOf(']'));
if (!mods.Contains(dependency, StringComparer.OrdinalIgnoreCase))
{
// found one, now add it to the list.
mods.Add(dependency);
modlist += " " + dependency + "\n";
}
}
catch (ArgumentOutOfRangeException)
{
progress.Error(cfgmod, "Skipping :FOR init for line " + name +
". The line most likely contains a space that should be removed");
}
}
}
}
modlist += "Mods by directory (sub directories of GameData):\n";
string gameData = Path.Combine(Path.GetFullPath(KSPUtil.ApplicationRootPath), "GameData");
foreach (string subdir in Directory.GetDirectories(gameData))
{
string name = Path.GetFileName(subdir);
string cleanName = RemoveWS(name);
if (!mods.Contains(cleanName, StringComparer.OrdinalIgnoreCase))
{
mods.Add(cleanName);
modlist += " " + cleanName + "\n";
}
}
logger.Info(modlist);
mods.Sort();
#endregion List of mods
}
private IEnumerator ProcessPatch()
{
status = "Checking Cache";
logger.Info(status);
yield return null;
try
{
IsCacheUpToDate();
}
catch (Exception ex)
{
logger.Exception("Exception in IsCacheUpToDate", ex);
useCache = false;
}
#if DEBUG
//useCache = false;
#endif
status = "Pre patch init";
logger.Info(status);
yield return null;
PrePatchInit();
if (!useCache)
{
yield return null;
// If we don't use the cache then it is best to clean the PartDatabase.cfg
if (!keepPartDB && File.Exists(partDatabasePath))
File.Delete(partDatabasePath);
LoadPhysicsConfig();
#region Check Needs
// Do filtering with NEEDS
status = "Checking NEEDS.";
logger.Info(status);
yield return null;
CheckNeeds();
#endregion Check Needs
#region Applying patches
status = "Applying patches";
logger.Info(status);
yield return null;
// :First node
yield return StartCoroutine(ApplyPatch(":FIRST"));
// any node without a :pass
yield return StartCoroutine(ApplyPatch(":LEGACY"));
foreach (string mod in mods)
{
string upperModName = mod.ToUpper();
yield return StartCoroutine(ApplyPatch(":BEFORE[" + upperModName + "]"));
yield return StartCoroutine(ApplyPatch(":FOR[" + upperModName + "]"));
yield return StartCoroutine(ApplyPatch(":AFTER[" + upperModName + "]"));
}
// :Final node
yield return StartCoroutine(ApplyPatch(":FINAL"));
PurgeUnused();
#endregion Applying patches
#region Logging
if (progress.ErrorCount > 0 || progress.ExceptionCount > 0)
{
foreach (string file in progress.ErrorFiles.Keys)
{
errors += progress.ErrorFiles[file] + " error" + (progress.ErrorFiles[file] > 1 ? "s" : "") + " related to GameData/" + file
+ "\n";
}
logger.Warning("Errors in patch prevents the creation of the cache");
try
{
if (File.Exists(cachePath))
File.Delete(cachePath);
if (File.Exists(shaPath))
File.Delete(shaPath);
}
catch (Exception e)
{
logger.Exception("Exception while deleting stale cache ", e);
}
}
else
{
status = "Saving Cache";
logger.Info(status);
yield return null;
CreateCache();
}
SaveModdedTechTree();
SaveModdedPhysics();
}
else
{
status = "Loading from Cache";
logger.Info(status);
yield return null;
LoadCache();
}
StatusUpdate();
logger.Info(status + "\n" + errors);
#endregion Logging
#if DEBUG
RunTestCases();
#endif
// TODO : Remove if we ever get a way to load sooner
logger.Info("Reloading resources definitions");
PartResourceLibrary.Instance.LoadDefinitions();
logger.Info("Reloading Trait configs");
GameDatabase.Instance.ExperienceConfigs.LoadTraitConfigs();
logger.Info("Reloading Part Upgrades");
PartUpgradeManager.Handler.FillUpgrades();
foreach (ModuleManagerPostPatchCallback callback in postPatchCallbacks)
{
try
{
callback();
}
catch (Exception e)
{
logger.Exception("Exception while running a post patch callback", e);
}
yield return null;
}
yield return null;
// Call all "public static void ModuleManagerPostLoad()" on all class
foreach (Assembly ass in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
foreach (Type type in ass.GetTypes())
{
MethodInfo method = type.GetMethod("ModuleManagerPostLoad", BindingFlags.Public | BindingFlags.Static);
if (method != null && method.GetParameters().Length == 0)
{
try
{
logger.Info("Calling " + ass.GetName().Name + "." + type.Name + "." + method.Name + "()");
method.Invoke(null, null);
}
catch (Exception e)
{
logger.Exception("Exception while calling " + ass.GetName().Name + "." + type.Name + "." + method.Name + "()", e);
}
}
}
}
catch (Exception e)
{
logger.Exception("Post run call threw an exception in loading " + ass.FullName, e);
}
}
yield return null;
// Call "public void ModuleManagerPostLoad()" on all active MonoBehaviour instance
foreach (MonoBehaviour obj in FindObjectsOfType<MonoBehaviour>())
{
MethodInfo method = obj.GetType().GetMethod("ModuleManagerPostLoad", BindingFlags.Public | BindingFlags.Instance);
if (method != null && method.GetParameters().Length == 0)
{
try
{
logger.Info("Calling " + obj.GetType().Name + "." + method.Name + "()");
method.Invoke(obj, null);
}
catch (Exception e)
{
logger.Exception("Exception while calling " + obj.GetType().Name + "." + method.Name + "() :\n", e);
}
}
}
yield return null;
ready = true;
}
private void LoadPhysicsConfig()
{
logger.Info("Loading Physics.cfg");
UrlDir gameDataDir = GameDatabase.Instance.root.AllDirectories.First(d => d.path.EndsWith("GameData") && d.name == "" && d.url == "");
// need to use a file with a cfg extenssion to get the right fileType or you can't AddConfig on it
physicsUrlFile = new UrlDir.UrlFile(gameDataDir, new FileInfo(defaultPhysicsPath));
// Since it loaded the default config badly (sub node only) we clear it first
physicsUrlFile.configs.Clear();
// And reload it properly
ConfigNode physicsContent = ConfigNode.Load(defaultPhysicsPath);
physicsContent.name = "PHYSICSGLOBALS";
physicsUrlFile.AddConfig(physicsContent);
gameDataDir.files.Add(physicsUrlFile);
}
private void SaveModdedPhysics()
{
List<UrlDir.UrlConfig> configs = physicsUrlFile.configs;
if (configs.Count == 0)
{
logger.Info("No PHYSICSGLOBALS node found. No custom Physics config will be saved");
return;
}
if (configs.Count > 1)
{
logger.Info(configs.Count + " PHYSICSGLOBALS node found. A patch may be wrong. Using the first one");
}
configs[0].config.Save(physicsPath);
}
private string FileSHA(string filename)
{
try
{
if (File.Exists(filename))
{
System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create();
byte[] data = null;
using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read))
{
data = sha.ComputeHash(fs);
}
string hashedValue = string.Empty;
foreach (byte b in data)
{
hashedValue += String.Format("{0,2:x2}", b);
}
return hashedValue;
}
}
catch (Exception e)
{
logger.Exception("Exception hashing file " + filename, e);
return "0";
}
return "0";
}
private void IsCacheUpToDate()
{
Stopwatch sw = new Stopwatch();
sw.Start();
System.Security.Cryptography.SHA256 sha = System.Security.Cryptography.SHA256.Create();
System.Security.Cryptography.SHA256 filesha = System.Security.Cryptography.SHA256.Create();
UrlDir.UrlFile[] files = GameDatabase.Instance.root.AllConfigFiles.ToArray();
for (int i = 0; i < files.Length; i++)
{
// Hash the file path so the checksum change if files are moved
byte[] pathBytes = Encoding.UTF8.GetBytes(files[i].url);
sha.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0);
// hash the file content
byte[] contentBytes = File.ReadAllBytes(files[i].fullPath);
if (i == files.Length - 1)
sha.TransformFinalBlock(contentBytes, 0, contentBytes.Length);
else
sha.TransformBlock(contentBytes, 0, contentBytes.Length, contentBytes, 0);
filesha.ComputeHash(contentBytes);
if (!filesSha.ContainsKey(files[i].url))
{
filesSha.Add(files[i].url, BitConverter.ToString(filesha.Hash));
}
else
{
logger.Warning("Duplicate fileSha key. This should not append. The key is " + files[i].url);
}
}
// Hash the mods dll path so the checksum change if dlls are moved or removed (impact NEEDS)
foreach (AssemblyLoader.LoadedAssembly dll in AssemblyLoader.loadedAssemblies)
{
string path = dll.url + "/" + dll.name;
byte[] pathBytes = Encoding.UTF8.GetBytes(path);
sha.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0);
}
configSha = BitConverter.ToString(sha.Hash);
sha.Clear();
filesha.Clear();
sw.Stop();
logger.Info("SHA generated in " + ((float)sw.ElapsedMilliseconds / 1000).ToString("F3") + "s");
logger.Info(" SHA = " + configSha);
useCache = false;
if (File.Exists(shaPath))
{
ConfigNode shaConfigNode = ConfigNode.Load(shaPath);
if (shaConfigNode != null && shaConfigNode.HasValue("SHA") && shaConfigNode.HasValue("version") && shaConfigNode.HasValue("KSPVersion"))
{
string storedSHA = shaConfigNode.GetValue("SHA");
string version = shaConfigNode.GetValue("version");
string kspVersion = shaConfigNode.GetValue("KSPVersion");
ConfigNode filesShaNode = shaConfigNode.GetNode("FilesSHA");
useCache = CheckFilesChange(files, filesShaNode);
useCache = useCache && storedSHA.Equals(configSha);
useCache = useCache && version.Equals(Assembly.GetExecutingAssembly().GetName().Version.ToString());
useCache = useCache && kspVersion.Equals(Versioning.version_major + "." + Versioning.version_minor + "." + Versioning.Revision + "." + Versioning.BuildID);
useCache = useCache && File.Exists(cachePath);
useCache = useCache && File.Exists(physicsPath);
useCache = useCache && File.Exists(techTreePath);
logger.Info("Cache SHA = " + storedSHA);
logger.Info("useCache = " + useCache);
}
}
}
private bool CheckFilesChange(UrlDir.UrlFile[] files, ConfigNode shaConfigNode)
{
bool noChange = true;
StringBuilder changes = new StringBuilder();
for (int i = 0; i < files.Length; i++)
{
ConfigNode fileNode = getFileNode(shaConfigNode, files[i].url);
string fileSha = fileNode?.GetValue("SHA");
if (fileNode == null)
continue;
if (fileSha == null || filesSha[files[i].url] != fileSha)
{
changes.Append("Changed : " + fileNode.GetValue("filename") + ".cfg\n");
noChange = false;
}
}
for (int i = 0; i < files.Length; i++)
{
ConfigNode fileNode = getFileNode(shaConfigNode, files[i].url);
if (fileNode == null)
{
changes.Append("Added : " + files[i].url + ".cfg\n");
noChange = false;
}
shaConfigNode.RemoveNode(fileNode);
}
foreach (ConfigNode fileNode in shaConfigNode.GetNodes())
{
changes.Append("Deleted : " + fileNode.GetValue("filename") + ".cfg\n");
noChange = false;
}
if (!noChange)
logger.Info("Changes :\n" + changes.ToString());
return noChange;
}
private ConfigNode getFileNode(ConfigNode shaConfigNode, string filename)
{
for (int i = 0; i < shaConfigNode.nodes.Count; i++)
{
ConfigNode file = shaConfigNode.nodes[i];
if (file.name == "FILE" && file.GetValue("filename") == filename)
return file;
}
return null;
}
private void CreateCache()
{
ConfigNode shaConfigNode = new ConfigNode();
shaConfigNode.AddValue("SHA", configSha);
shaConfigNode.AddValue("version", Assembly.GetExecutingAssembly().GetName().Version.ToString());
shaConfigNode.AddValue("KSPVersion", Versioning.version_major + "." + Versioning.version_minor + "." + Versioning.Revision + "." + Versioning.BuildID);
ConfigNode filesSHANode = shaConfigNode.AddNode("FilesSHA");
ConfigNode cache = new ConfigNode();
cache.AddValue("patchedNodeCount", progress.PatchedNodeCount.ToString());
foreach (UrlDir.UrlConfig config in GameDatabase.Instance.root.AllConfigs)
{
ConfigNode node = cache.AddNode("UrlConfig");
node.AddValue("name", config.name);
node.AddValue("type", config.type);
node.AddValue("parentUrl", config.parent.url);
node.AddValue("url", config.url);
node.AddNode(config.config);
}
foreach (var file in GameDatabase.Instance.root.AllConfigFiles)
{
// "/Physics" is the node we created manually to loads the PHYSIC config
if (file.url != "/Physics" && filesSha.ContainsKey(file.url))
{
ConfigNode shaNode = filesSHANode.AddNode("FILE");
shaNode.AddValue("filename", file.url);
shaNode.AddValue("SHA", filesSha[file.url]);
filesSha.Remove(file.url);
}
}
logger.Info("Saving cache");
try
{
shaConfigNode.Save(shaPath);
}
catch (Exception e)
{
logger.Exception("Exception while saving the sha", e);
}
try
{
cache.Save(cachePath);
return;
}
catch (NullReferenceException e)
{
logger.Exception("NullReferenceException while saving the cache", e);
}
catch (Exception e)
{
logger.Exception("Exception while saving the cache", e);
}
try
{
logger.Error("An error occured while creating the cache. Deleting the cache files to avoid keeping a bad cache");
if (File.Exists(cachePath))
File.Delete(cachePath);
if (File.Exists(shaPath))
File.Delete(shaPath);
}
catch (Exception e)
{
logger.Exception("Exception while deleting the cache", e);
}
}
private void SaveModdedTechTree()
{
UrlDir.UrlConfig[] configs = GameDatabase.Instance.GetConfigs("TechTree");
if (configs.Length == 0)
{
logger.Info("No TechTree node found. No custom TechTree will be saved");
return;
}
if (configs.Length > 1)
{
logger.Info(configs.Length + " TechTree node found. A patch may be wrong. Using the first one");
}
ConfigNode techNode = new ConfigNode("TechTree");
techNode.AddNode(configs[0].config);
techNode.Save(techTreePath);
}
private void LoadCache()
{
// Clear the config DB
foreach (UrlDir.UrlFile files in GameDatabase.Instance.root.AllConfigFiles)
{
files.configs.Clear();
}
// And then load all the cached configs
ConfigNode cache = ConfigNode.Load(cachePath);
if (cache.HasValue("patchedNodeCount") && int.TryParse(cache.GetValue("patchedNodeCount"), out int patchedNodeCount))
progress.PatchedNodeCount = patchedNodeCount;
// Create the fake file where we load the physic config cache
UrlDir gameDataDir = GameDatabase.Instance.root.AllDirectories.First(d => d.path.EndsWith("GameData") && d.name == "" && d.url == "");
// need to use a file with a cfg extension to get the right fileType or you can't AddConfig on it
physicsUrlFile = new UrlDir.UrlFile(gameDataDir, new FileInfo(defaultPhysicsPath));
gameDataDir.files.Add(physicsUrlFile);
foreach (ConfigNode node in cache.nodes)
{
string name = node.GetValue("name");
string type = node.GetValue("type");
string parentUrl = node.GetValue("parentUrl");
string url = node.GetValue("url");
UrlDir.UrlFile parent = GameDatabase.Instance.root.AllConfigFiles.FirstOrDefault(f => f.url == parentUrl);
if (parent != null)
{
parent.AddConfig(node.nodes[0]);
}
else
{
logger.Warning("Parent null for " + parentUrl);
}
}
logger.Info("Cache Loaded");
}
private void StatusUpdate()
{
status = "ModuleManager: " + progress.PatchedNodeCount + " patch" + (progress.PatchedNodeCount != 1 ? "es" : "") + (useCache ? " loaded from cache" : " applied");
if (progress.ErrorCount > 0)
status += ", found <color=orange>" + progress.ErrorCount + " error" + (progress.ErrorCount != 1 ? "s" : "") + "</color>";
if (progress.ExceptionCount > 0)
status += ", encountered <color=red>" + progress.ExceptionCount + " exception" + (progress.ExceptionCount != 1 ? "s" : "") + "</color>";
}
#region Needs checking
private void CheckNeeds()
{
UrlDir.UrlConfig[] allConfigs = GameDatabase.Instance.root.AllConfigs.ToArray();
// Check the NEEDS parts first.
foreach (UrlDir.UrlConfig mod in allConfigs)
{
UrlDir.UrlConfig currentMod = mod;
try
{
if (mod.config.name == null)
{
progress.Error(currentMod, "Error - Node in file " + currentMod.parent.url + " subnode: " + currentMod.type +
" has config.name == null");
}
if (currentMod.type.Contains(":NEEDS["))
{
mod.parent.configs.Remove(currentMod);
string type = currentMod.type;
if (!CheckNeeds(ref type))
{
progress.NeedsUnsatisfiedNode(currentMod.parent.url, currentMod.type);
continue;
}
ConfigNode copy = new ConfigNode(type);
ShallowCopy(currentMod.config, copy);
currentMod = new UrlDir.UrlConfig(currentMod.parent, copy);
mod.parent.configs.Add(currentMod);
}
// Recursively check the contents
CheckNeeds(new NodeStack(mod.config), new PatchContext(mod, GameDatabase.Instance.root, logger, progress));
}
catch (Exception ex)
{
progress.Exception(currentMod, "Exception while checking needs : " + currentMod.url + " with a type of " + currentMod.type, ex);
logger.Error("Node is : " + PrettyConfig(currentMod));
}
}
}
private void CheckNeeds(NodeStack stack, PatchContext context)
{
bool needsCopy = false;
ConfigNode original = stack.value;
ConfigNode copy = new ConfigNode(original.name);
for (int i = 0; i < original.values.Count; ++i)
{
ConfigNode.Value val = original.values[i];
string valname = val.name;
try
{
if (CheckNeeds(ref valname))
{
copy.AddValue(valname, val.value);
}
else
{
needsCopy = true;
context.progress.NeedsUnsatisfiedValue(context.patchUrl.url, stack.GetPath(), val.name);
}
}
catch (ArgumentOutOfRangeException e)
{
progress.Exception("ArgumentOutOfRangeException in CheckNeeds for value \"" + val.name + "\"", e);
throw;
}
catch (Exception e)
{
progress.Exception("General Exception in CheckNeeds for value \"" + val.name + "\"", e);
throw;
}
}
for (int i = 0; i < original.nodes.Count; ++i)
{
ConfigNode node = original.nodes[i];
string nodeName = node.name;
if (nodeName == null)
{
progress.Error(context.patchUrl, "Error - Node in file " + context.patchUrl.url + " subnode: " + stack.GetPath() +
" has config.name == null");
}
try
{
if (CheckNeeds(ref nodeName))
{
node.name = nodeName;
CheckNeeds(stack.Push(node), context);
copy.AddNode(node);
}
else
{
needsCopy = true;
progress.NeedsUnsatisfiedNode(context.patchUrl.url, stack.Push(node).GetPath());
}
}
catch (ArgumentOutOfRangeException e)
{
progress.Exception("ArgumentOutOfRangeException in CheckNeeds for node \"" + node.name + "\"", e);
throw;
}
catch (Exception e)
{
progress.Exception("General Exception " + e.GetType().Name + " for node \"" + node.name + "\"", e);
throw;
}
}
if (needsCopy)
ShallowCopy(copy, original);
}
/// <summary>
/// Returns true if needs are satisfied.
/// </summary>
private bool CheckNeeds(ref string name)
{
if (name == null)
return true;
int idxStart = name.IndexOf(":NEEDS[");
if (idxStart < 0)
return true;
int idxEnd = name.IndexOf(']', idxStart + 7);
string needsString = name.Substring(idxStart + 7, idxEnd - idxStart - 7).ToUpper();
name = name.Substring(0, idxStart) + name.Substring(idxEnd + 1);
// Check to see if all the needed dependencies are present.
foreach (string andDependencies in needsString.Split(',', '&'))
{
bool orMatch = false;
foreach (string orDependency in andDependencies.Split('|'))
{
if (orDependency.Length == 0)
continue;
bool not = orDependency[0] == '!';
string toFind = not ? orDependency.Substring(1) : orDependency;
bool found = mods.Contains(toFind, StringComparer.OrdinalIgnoreCase);
if (not == !found)
{
orMatch = true;
break;
}
}
if (!orMatch)
return false;
}
return true;
}
private void PurgeUnused()
{
foreach (UrlDir.UrlConfig mod in GameDatabase.Instance.root.AllConfigs.ToArray())
{
string name = RemoveWS(mod.type);
if (ParseCommand(name, out name) != Command.Insert)
mod.parent.configs.Remove(mod);
}
}
#endregion Needs checking
#region Applying Patches
// Apply patch to all relevent nodes
public IEnumerator ApplyPatch(string Stage)
{
StatusUpdate();
logger.Info(Stage + (Stage == ":LEGACY" ? " (default) pass" : " pass"));
yield return null;
activity = "ModuleManager " + Stage;
UrlDir.UrlConfig[] allConfigs = GameDatabase.Instance.root.AllConfigs.ToArray();
float nextYield = Time.realtimeSinceStartup + yieldInterval;
for (int modsIndex = 0; modsIndex < allConfigs.Length; modsIndex++)
{
UrlDir.UrlConfig mod = allConfigs[modsIndex];
try
{
string name = RemoveWS(mod.type);
string tmp;
Command cmd = ParseCommand(name, out tmp);
if (cmd != Command.Insert)
{
if (!IsBracketBalanced(mod.type))
{
progress.Error(mod,
"Error - Skipping a patch with unbalanced square brackets or a space (replace them with a '?') :\n" +
mod.name + "\n");
// And remove it so it's not tried anymore
mod.parent.configs.Remove(mod);
continue;
}
// Ensure the stage is correct
string upperName = name.ToUpper();
int stageIdx = upperName.IndexOf(Stage);
if (stageIdx >= 0)
name = name.Substring(0, stageIdx) + name.Substring(stageIdx + Stage.Length);
else if (
!((upperName.Contains(":FIRST") || Stage == ":LEGACY")
&& !upperName.Contains(":BEFORE[") && !upperName.Contains(":FOR[")
&& !upperName.Contains(":AFTER[") && !upperName.Contains(":FINAL")))
continue;
// TODO: do we want to ensure there's only one phase specifier?