/
ModuleManager.cs
532 lines (446 loc) · 21.2 KB
/
ModuleManager.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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using TMPro;
using UnityEngine;
using Debug = UnityEngine.Debug;
using ModuleManager.Cats;
using ModuleManager.Logging;
namespace ModuleManager
{
[KSPAddon(KSPAddon.Startup.Instantly, true)]
public class ModuleManager : MonoBehaviour
{
#region state
private bool inRnDCenter;
private bool reloading;
public bool showUI = false;
private Rect windowPos = new Rect(80f, 60f, 240f, 40f);
private float textPos = 0;
private string version = "";
//private Texture2D tex;
//private Texture2D tex2;
private bool nyan = false;
private bool nCats = false;
public static bool dumpPostPatch = false;
private PopupDialog menu;
private MMPatchRunner patchRunner;
#endregion state
private static bool loadedInScene;
internal void OnRnDCenterSpawn()
{
inRnDCenter = true;
}
internal void OnRnDCenterDeSpawn()
{
inRnDCenter = false;
}
public static void Log(String s)
{
print("[ModuleManager] " + s);
}
private Stopwatch totalTime = new Stopwatch();
internal void Awake()
{
if (LoadingScreen.Instance == null)
{
Destroy(gameObject);
return;
}
// Ensure that only one copy of the service is run per scene change.
if (loadedInScene || !ElectionAndCheck())
{
Assembly currentAssembly = Assembly.GetExecutingAssembly();
Log("Multiple copies of current version. Using the first copy. Version: " +
currentAssembly.GetName().Version);
Destroy(gameObject);
return;
}
totalTime.Start();
// Allow loading the background in the laoding screen
Application.runInBackground = true;
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = -1;
// More cool loading screen. Less 4 stoke logo.
for (int i = 0; i < LoadingScreen.Instance.Screens.Count; i++)
{
var state = LoadingScreen.Instance.Screens[i];
state.fadeInTime = i < 3 ? 0.1f : 1;
state.displayTime = i < 3 ? 1 : 3;
state.fadeOutTime = i < 3 ? 0.1f : 1;
}
TextMeshProUGUI[] texts = LoadingScreen.Instance.gameObject.GetComponentsInChildren<TextMeshProUGUI>();
foreach (var text in texts)
{
textPos = Mathf.Min(textPos, text.rectTransform.localPosition.y);
}
DontDestroyOnLoad(gameObject);
Version v = Assembly.GetExecutingAssembly().GetName().Version;
version = v.Major + "." + v.Minor + "." + v.Build;
// Subscribe to the RnD center spawn/deSpawn events
GameEvents.onGUIRnDComplexSpawn.Add(OnRnDCenterSpawn);
GameEvents.onGUIRnDComplexDespawn.Add(OnRnDCenterDeSpawn);
LoadingScreen screen = FindObjectOfType<LoadingScreen>();
if (screen == null)
{
Log("Can't find LoadingScreen type. Aborting ModuleManager execution");
return;
}
List<LoadingSystem> list = LoadingScreen.Instance.loaders;
if (list != null)
{
// So you can insert a LoadingSystem object in this list at any point.
// GameDatabase is first in the list, and PartLoader is second
// We could insert ModuleManager after GameDatabase to get it to run there
// and SaveGameFixer after PartLoader.
int gameDatabaseIndex = list.FindIndex(s => s is GameDatabase);
GameObject aGameObject = new GameObject("ModuleManager");
DontDestroyOnLoad(aGameObject);
Log(string.Format("Adding post patch to the loading screen {0}", list.Count));
list.Insert(gameDatabaseIndex + 1, aGameObject.AddComponent<PostPatchLoader>());
patchRunner = new MMPatchRunner(new ModLogger("ModuleManager", new UnityLogger(Debug.unityLogger)));
StartCoroutine(patchRunner.Run());
// Workaround for 1.6.0 Editor bug after a PartDatabase rebuild.
if (Versioning.version_major == 1 && Versioning.version_minor == 6 && Versioning.Revision == 0)
{
Fix16 fix16 = aGameObject.AddComponent<Fix16>();
list.Add(fix16);
}
}
bool foolsDay = (DateTime.Now.Month == 4 && DateTime.Now.Day == 1);
bool catDay = (DateTime.Now.Month == 2 && DateTime.Now.Day == 22);
nyan = foolsDay
|| Environment.GetCommandLineArgs().Contains("-nyan-nyan");
nCats = catDay
|| Environment.GetCommandLineArgs().Contains("-ncats");
dumpPostPatch = Environment.GetCommandLineArgs().Contains("-mm-dump");
loadedInScene = true;
}
private TextMeshProUGUI status;
private TextMeshProUGUI errors;
private TextMeshProUGUI warning;
private void Start()
{
if (nCats)
CatManager.LaunchCats();
else if (nyan)
CatManager.LaunchCat();
Canvas canvas = LoadingScreen.Instance.GetComponentInChildren<Canvas>();
status = CreateTextObject(canvas, "MMStatus");
errors = CreateTextObject(canvas, "MMErrors");
warning = CreateTextObject(canvas, "MMWarning");
warning.text = "";
//if (Versioning.version_major == 1 && Versioning.version_minor == 0 && Versioning.Revision == 5 && Versioning.BuildID == 1024)
//{
// warning.text = "Your KSP 1.0.5 is running on build 1024. You should upgrade to build 1028 to avoid problems with addons.";
// //if (GUI.Button(new Rect(Screen.width / 2f - 100, offsetY, 200, 20), "Click to open the Forum thread"))
// // Application.OpenURL("http://forum.kerbalspaceprogram.com/index.php?/topic/124998-silent-patch-for-ksp-105-published/");
//}
}
private TextMeshProUGUI CreateTextObject(Canvas canvas, string name)
{
GameObject statusGameObject = new GameObject(name);
TextMeshProUGUI text = statusGameObject.AddComponent<TextMeshProUGUI>();
text.text = "STATUS";
text.fontSize = 18;
text.autoSizeTextContainer = true;
text.font = Resources.Load("Fonts/Calibri SDF", typeof(TMP_FontAsset)) as TMP_FontAsset;
text.alignment = TextAlignmentOptions.Center;
text.enableWordWrapping = false;
text.isOverlay = true;
text.rectTransform.anchorMin = new Vector2(0.5f, 0);
text.rectTransform.anchorMax = new Vector2(0.5f, 0);
text.rectTransform.anchoredPosition = Vector2.zero;
statusGameObject.transform.SetParent(canvas.transform);
return text;
}
// Unsubscribe from events when the behavior dies
internal void OnDestroy()
{
GameEvents.onGUIRnDComplexSpawn.Remove(OnRnDCenterSpawn);
GameEvents.onGUIRnDComplexDespawn.Remove(OnRnDCenterDeSpawn);
}
internal void Update()
{
if (GameSettings.MODIFIER_KEY.GetKey() && Input.GetKeyDown(KeyCode.F11)
&& (HighLogic.LoadedScene == GameScenes.SPACECENTER || HighLogic.LoadedScene == GameScenes.MAINMENU)
&& !inRnDCenter)
{
if (menu == null)
{
menu = PopupDialog.SpawnPopupDialog(new Vector2(0.5f, 0.5f),
new Vector2(0.5f, 0.5f),
new MultiOptionDialog(
"ModuleManagerMenu",
"",
"ModuleManager",
HighLogic.UISkin,
new Rect(0.5f, 0.5f, 150f, 60f),
new DialogGUIFlexibleSpace(),
new DialogGUIVerticalLayout(
new DialogGUIFlexibleSpace(),
new DialogGUIButton("Reload Database",
delegate
{
MMPatchLoader.keepPartDB = false;
StartCoroutine(DataBaseReloadWithMM());
}, 140.0f, 30.0f, true),
new DialogGUIButton("Quick Reload Database",
delegate
{
MMPatchLoader.keepPartDB = true;
StartCoroutine(DataBaseReloadWithMM());
}, 140.0f, 30.0f, true),
new DialogGUIButton("Dump Database to Files",
delegate
{
StartCoroutine(DataBaseReloadWithMM(true));
}, 140.0f, 30.0f, true),
new DialogGUIButton("Close", () => { }, 140.0f, 30.0f, true)
)),
false,
HighLogic.UISkin);
}
else
{
menu.Dismiss();
menu = null;
}
}
if (totalTime.IsRunning && HighLogic.LoadedScene == GameScenes.MAINMENU)
{
totalTime.Stop();
Log("Total loading Time = " + ((float)totalTime.ElapsedMilliseconds / 1000).ToString("F3") + "s");
Application.runInBackground = GameSettings.SIMULATE_IN_BACKGROUND;
QualitySettings.vSyncCount = GameSettings.SYNC_VBL;
Application.targetFrameRate = GameSettings.FRAMERATE_LIMIT;
}
float offsetY = textPos;
float h;
if (patchRunner != null)
{
if (warning)
{
h = warning.text.Length > 0 ? warning.textBounds.size.y : 0;
offsetY = offsetY + h;
warning.rectTransform.localPosition = new Vector3(0, offsetY);
}
if (status)
{
status.text = patchRunner.Status;
h = status.text.Length > 0 ? status.textBounds.size.y : 0;
offsetY = offsetY + h;
status.transform.localPosition = new Vector3(0, offsetY);
}
if (errors)
{
errors.text = patchRunner.Errors;
h = errors.text.Length > 0 ? errors.textBounds.size.y : 0;
offsetY = offsetY + h;
errors.transform.localPosition = new Vector3(0, offsetY);
}
}
if (reloading)
{
float percent = 0;
if (!GameDatabase.Instance.IsReady())
percent = GameDatabase.Instance.ProgressFraction();
else if (!PartLoader.Instance.IsReady())
percent = 2f + PartLoader.Instance.ProgressFraction();
int intPercent = Mathf.CeilToInt(percent * 100f / 3f);
ScreenMessages.PostScreenMessage("Database reloading " + intPercent + "%", Time.deltaTime,
ScreenMessageStyle.UPPER_CENTER);
}
}
#region GUI stuff.
internal static IntPtr intPtr = new IntPtr(long.MaxValue);
/* Not required anymore. At least
public static bool IsABadIdea()
{
return (intPtr.ToInt64() == long.MaxValue) && (Environment.OSVersion.Platform == PlatformID.Win32NT);
}
*/
private IEnumerator DataBaseReloadWithMM(bool dump = false)
{
reloading = true;
QualitySettings.vSyncCount = 0;
Application.targetFrameRate = -1;
ScreenMessages.PostScreenMessage("Database reloading started", 1, ScreenMessageStyle.UPPER_CENTER);
yield return null;
GameDatabase.Instance.Recompile = true;
GameDatabase.Instance.StartLoad();
yield return null;
patchRunner = new MMPatchRunner(new ModLogger("ModuleManager", new UnityLogger(Debug.unityLogger)));
StartCoroutine(patchRunner.Run());
// wait for it to finish
while (!GameDatabase.Instance.IsReady())
yield return null;
PostPatchLoader.Instance.StartLoad();
while (!PostPatchLoader.Instance.IsReady())
yield return null;
if (dump)
OutputAllConfigs();
PartLoader.Instance.StartLoad();
while (!PartLoader.Instance.IsReady())
yield return null;
// Needs more work.
//ConfigNode game = HighLogic.CurrentGame.config.GetNode("GAME");
//if (game != null && ResearchAndDevelopment.Instance != null)
//{
// ScreenMessages.PostScreenMessage("GAME found");
// ConfigNode scenario = game.GetNodes("SCENARIO").FirstOrDefault((ConfigNode n) => n.name == "ResearchAndDevelopment");
// if (scenario != null)
// {
// ScreenMessages.PostScreenMessage("SCENARIO found");
// ResearchAndDevelopment.Instance.OnLoad(scenario);
// }
//}
QualitySettings.vSyncCount = GameSettings.SYNC_VBL;
Application.targetFrameRate = GameSettings.FRAMERATE_LIMIT;
reloading = false;
ScreenMessages.PostScreenMessage("Database reloading finished", 1, ScreenMessageStyle.UPPER_CENTER);
}
public static void OutputAllConfigs()
{
string path = KSPUtil.ApplicationRootPath + "/_MMCfgOutput/";
try
{
Directory.CreateDirectory(path);
foreach (string file in Directory.GetFiles(path))
{
File.Delete(file);
}
foreach (string dir in Directory.GetDirectories(path))
{
Directory.Delete(dir, true);
}
}
catch (IOException ioException)
{
Log("Exception while cleaning the export dir\n" + ioException);
}
catch (UnauthorizedAccessException unauthorizedAccessException)
{
Log("Exception while cleaning the export dir\n" + unauthorizedAccessException);
}
Stack<UrlDir> dirs = new Stack<UrlDir>();
dirs.Push(GameDatabase.Instance.root);
Stack<String> paths = new Stack<string>();
paths.Push("");
try
{
while (dirs.Count > 0)
{
var currentDir = dirs.Pop();
string currentPath = paths.Pop();
foreach (UrlDir.UrlFile urlFile in currentDir.files)
{
if (urlFile.fileType == UrlDir.FileType.Config)
{
string dirPath = path + currentPath;
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
Log("Exporting " + currentPath + urlFile.name + "." + urlFile.fileExtension);
string filePath = dirPath + urlFile.name + "." + urlFile.fileExtension;
foreach (UrlDir.UrlConfig urlConfig in urlFile.configs)
{
try
{
File.AppendAllText(filePath, urlConfig.config.ToString());
}
catch (Exception e)
{
Log("Exception while trying to write the file " + filePath + "\n" + e);
}
}
}
}
foreach (UrlDir urlDir in currentDir.children)
{
dirs.Push(urlDir);
paths.Push(currentPath + urlDir.name + "/");
}
}
}
catch (DirectoryNotFoundException directoryNotFoundException)
{
Log("Exception while exporting the cfg\n" + directoryNotFoundException);
}
catch (IOException ioException)
{
Log("Exception while exporting the cfg\n" + ioException);
}
catch (UnauthorizedAccessException unauthorizedAccessException)
{
Log("Exception while exporting the cfg\n" + unauthorizedAccessException);
}
}
#endregion GUI stuff.
public bool ElectionAndCheck()
{
#region Type election
// TODO : Move the old version check in a process that call Update.
// Check for old version and MMSarbianExt
IEnumerable<AssemblyLoader.LoadedAssembly> oldMM =
AssemblyLoader.loadedAssemblies.Where(
a => a.assembly.GetName().Name == Assembly.GetExecutingAssembly().GetName().Name)
.Where(a => a.assembly.GetName().Version.CompareTo(new System.Version(1, 5, 0)) == -1);
IEnumerable<AssemblyLoader.LoadedAssembly> oldAssemblies =
oldMM.Concat(AssemblyLoader.loadedAssemblies.Where(a => a.assembly.GetName().Name == "MMSarbianExt"));
if (oldAssemblies.Any())
{
IEnumerable<string> badPaths =
oldAssemblies.Select(a => a.path)
.Select(
p =>
Uri.UnescapeDataString(
new Uri(Path.GetFullPath(KSPUtil.ApplicationRootPath)).MakeRelativeUri(new Uri(p))
.ToString()
.Replace('/', Path.DirectorySeparatorChar)));
string status =
"You have old versions of Module Manager (older than 1.5) or MMSarbianExt.\nYou will need to remove them for Module Manager and the mods using it to work\nExit KSP and delete those files :\n" +
String.Join("\n", badPaths.ToArray());
PopupDialog.SpawnPopupDialog(new Vector2(0f, 1f), new Vector2(0f, 1f), "ModuleManagerOldVersions", "Old versions of Module Manager", status, "OK", false, UISkinManager.defaultSkin);
Log("Old version of Module Manager present. Stopping");
return false;
}
//PopupDialog.SpawnPopupDialog(new Vector2(0.1f, 1f), new Vector2(0.2f, 1f), "Test of the dialog", "Stuff", "OK", false, UISkinManager.defaultSkin);
Assembly currentAssembly = Assembly.GetExecutingAssembly();
IEnumerable<AssemblyLoader.LoadedAssembly> eligible = from a in AssemblyLoader.loadedAssemblies
let ass = a.assembly
where ass.GetName().Name == currentAssembly.GetName().Name
orderby ass.GetName().Version descending, a.path ascending
select a;
// Elect the newest loaded version of MM to process all patch files.
// If there is a newer version loaded then don't do anything
// If there is a same version but earlier in the list, don't do anything either.
if (eligible.First().assembly != currentAssembly)
{
//loaded = true;
Log("version " + currentAssembly.GetName().Version + " at " + currentAssembly.Location +
" lost the election");
Destroy(gameObject);
return false;
}
string candidates = "";
foreach (AssemblyLoader.LoadedAssembly a in eligible)
{
if (currentAssembly.Location != a.path)
candidates += "Version " + a.assembly.GetName().Version + " " + a.path + " " + "\n";
}
if (candidates.Length > 0)
{
Log("version " + currentAssembly.GetName().Version + " at " + currentAssembly.Location +
" won the election against\n" + candidates);
}
#endregion Type election
return true;
}
}
}