forked from danarcher/XCom2ModTool
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathModBuilder.cs
443 lines (402 loc) · 17.4 KB
/
ModBuilder.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
using System;
using System.IO;
using System.Linq;
using System.Threading;
using XCom2ModTool.UnrealPackages;
namespace XCom2ModTool
{
internal class ModBuilder
{
private static readonly string ScriptFolderName = "Script";
private static readonly string ScriptExtension = ".u";
private static readonly string CompiledScriptManifestName = "Manifest.txt";
private static readonly string KeyStandardPackageCompiledScriptFileName = "XComGame" + ScriptExtension;
private static readonly string HighlanderIndicativeExportName = "CHXComGameVersionTemplate";
private static readonly string[] StandardSourceCodeFolderNames = new[]
{
"AkAudio",
"Core",
"DLC_1",
"DLC_2",
"DLC_3",
"Engine",
"GameFramework",
"GFxUI",
"GFxUIEditor",
"IpDrv",
"OnlineSubsystemSteamworks",
"TLE",
"UnrealEd",
"XComEditor",
"XComGame",
};
private static readonly string[] StandardCompiledScripts = StandardSourceCodeFolderNames.Select(x => x + ScriptExtension).Concat(new[]
{
"DO_NOT_DELETE.TXT",
CompiledScriptManifestName,
}).ToArray();
private static readonly string[] StandardManifestModules = StandardSourceCodeFolderNames.Concat(new[]
{
"WinDrv",
"XAudio2",
}).ToArray();
private CancellationToken cancellation;
private XCom2Edition edition;
private Compiler compiler;
private ModInfo modInfo;
private ModProject modProject;
private string modStagingPath;
private string modInstallPath;
private string modShaderCacheStagingPath = null;
private string modShaderCacheInstallPath = null;
private bool modHasSourceCode;
private bool modHasShaderContent;
private string modStagingCompiledScriptFolderPath = null;
private string modSdkCompiledScriptPath = null;
private string modStagingCompiledScriptFilePath = null;
public ModBuilder(ModInfo modInfo, XCom2Edition edition, CancellationToken cancellation)
{
this.modInfo = modInfo;
this.edition = edition;
this.cancellation = cancellation;
compiler = new Compiler(edition);
modStagingPath = edition.GetModStagingPath(modInfo);
modInstallPath = edition.GetModInstallPath(modInfo);
modShaderCacheStagingPath = edition.GetModShaderCacheStagingPath(modInfo);
modShaderCacheInstallPath = edition.GetModShaderCacheInstallPath(modInfo);
modHasSourceCode = modInfo.HasSourceCode();
modHasShaderContent = modInfo.HasShaderContent();
modStagingCompiledScriptFolderPath = Path.Combine(modStagingPath, ScriptFolderName);
modSdkCompiledScriptPath = Path.Combine(edition.SdkXComGameCompiledScriptPath, modInfo.ModName + ScriptExtension);
modStagingCompiledScriptFilePath = Path.Combine(modStagingCompiledScriptFolderPath, modInfo.ModName + ScriptExtension);
compiler.ReplacePaths.Add(edition.SdkSourceCodePath, modInfo.SourceCodePath);
}
public void Clean()
{
CleanModStaging();
}
private void ThrowIfCancelled() => cancellation.ThrowIfCancellationRequested();
public void Build(ModBuildType buildType)
{
Report.Verbose($"{buildType} build of {modInfo.ModName}");
// Load project first, to check folder structure is as we expect before we start moving files.
Report.Verbose("Loading project");
modProject = ModProject.Load(modInfo, edition);
if (!string.Equals(modProject.Title, modInfo.ModName, StringComparison.Ordinal))
{
Report.Warning($"Mod name {modInfo.ModName} does not match title '{modProject.Title}' in project {modInfo.ProjectName}");
}
// Switching between building with/without the highlander requires a full build.
if (IsSdkBuiltWithHighlander() != Settings.Default.Highlander)
{
var highlander = Settings.Default.Highlander;
Report.Warning($"This is a {(highlander ? "" : "non-")}highlander build, but {KeyStandardPackageCompiledScriptFileName} was {(highlander ? "not " : "")}built with the highlander; switching to full build");
buildType = ModBuildType.Full;
}
else
{
var highlander = Settings.Default.Highlander;
Report.Verbose($"This is a {(highlander ? "" : "non-")}highlander build, as is {KeyStandardPackageCompiledScriptFileName}");
}
CleanModStaging();
ThrowIfCancelled();
CleanSdkMods();
Directory.CreateDirectory(modStagingPath);
StageModFolder(ModInfo.SourceCodeFolder);
StageModFolder(ModInfo.ConfigFolder);
StageModFolder(ModInfo.LocalizationFolder);
StageModFolder(ModInfo.ContentFolder);
StageModMetadata();
ThrowIfCancelled();
if (modHasSourceCode)
{
switch (buildType)
{
case ModBuildType.Full:
CleanSdkSourceCode();
RestoreSdkSourceCode();
CopyModSourceCodeToSdk();
CleanSdkCompiledScripts();
CompileGame();
break;
case ModBuildType.Fast:
CleanSdkSourceCode();
RestoreSdkSourceCode();
CopyModSourceCodeToSdk();
CleanModSdkCompiledScripts();
CompileGame();
break;
case ModBuildType.Smart:
var flags = GetBuiltStandardPackageFlags();
if (!flags.HasValue)
{
Report.Verbose($"{KeyStandardPackageCompiledScriptFileName} invalid or not found, switching to full build");
goto case ModBuildType.Full;
}
if (Settings.Default.Debug != flags.Value.HasFlag(PackageFlags.Debug))
{
Settings.Default.Debug = !Settings.Default.Debug;
Report.Verbose($"Detected {(Settings.Default.Debug ? "debug" : "release")} build of {KeyStandardPackageCompiledScriptFileName}");
}
SmartCleanSdkSourceCode();
CopyModSourceCodeToSdk();
SmartCleanSdkCompiledScripts();
break;
default:
throw new ArgumentOutOfRangeException(nameof(buildType));
}
CompileMod();
if (modHasShaderContent)
{
switch (buildType)
{
case ModBuildType.Full:
case ModBuildType.Fast:
CompileShaders();
break;
case ModBuildType.Smart:
if (IsDeployedShaderCacheUpToDate())
{
CopyDeployedShaderCacheToStaging();
}
else
{
CompileShaders();
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(buildType));
}
}
StageModCompiledScripts();
SmartCleanSdkSourceCode();
}
DeployMod();
}
private bool IsSdkBuiltWithHighlander()
{
var path = Path.Combine(edition.SdkXComGameCompiledScriptPath, KeyStandardPackageCompiledScriptFileName);
using (var reader = new PackageReader(path))
{
var header = reader.ReadHeader();
return header.Exports.Any(x => string.Equals(x.Name, HighlanderIndicativeExportName, StringComparison.Ordinal));
}
}
private void CleanSdkMods()
{
Report.Verbose("Cleaning SDK mods");
DirectoryHelper.DeleteDirectoryContents(edition.SdkModsPath);
}
private void CleanModStaging()
{
if (Directory.Exists(modStagingPath))
{
Report.Verbose($"Cleaning staging folder");
DirectoryHelper.Delete(modStagingPath);
}
else
{
Report.Verbose($"Staging is clean");
}
}
private bool StageModFolder(string folderName)
{
var sourcePath = Path.Combine(modInfo.InnerPath, folderName);
if (Directory.Exists(sourcePath))
{
Report.Verbose($"Staging {folderName}");
var targetPath = Path.Combine(modStagingPath, folderName);
DirectoryHelper.CopyDirectory(sourcePath, targetPath);
return true;
}
return false;
}
private void StageModMetadata()
{
Report.Verbose("Writing metadata");
ModMetadata.Save(modProject, Path.Combine(modStagingPath, modInfo.ModName + ModMetadata.Extension));
}
private void CleanSdkSourceCode()
{
Report.Verbose("Cleaning SDK source");
DirectoryHelper.Delete(edition.SdkSourceCodePath);
Directory.CreateDirectory(edition.SdkSourceCodePath);
}
private void SmartCleanSdkSourceCode()
{
Report.Verbose("Smart-cleaning SDK source");
foreach (var folderPath in Directory.GetDirectories(edition.SdkSourceCodePath))
{
var folderName = Path.GetFileName(folderPath);
if (!StandardSourceCodeFolderNames.Any(x => string.Equals(x, folderName, StringComparison.OrdinalIgnoreCase)) &&
(!Settings.Default.Highlander || !string.Equals(folderName, edition.SdkHighlanderSourceCodeFolderName)))
{
Report.Verbose($" Deleting non-standard source {folderName}", Verbosity.Loquacious);
DirectoryHelper.Delete(folderPath);
}
}
foreach (var filePath in Directory.GetFiles(edition.SdkSourceCodePath))
{
Report.Verbose($" Deleting non-standard file {Path.GetFileName(filePath)}");
DirectoryHelper.Delete(filePath);
}
}
private void RestoreSdkSourceCode()
{
Report.Verbose("Restoring SDK source");
var count = DirectoryHelper.CopyDirectory(edition.SdkOriginalSourceCodePath, edition.SdkSourceCodePath);
Report.Verbose($"Restored {count} files");
if (Settings.Default.Highlander)
{
var highlanderSourceCodePath = edition.GetHighlanderModSourceCodePath();
Report.Verbose($"Restoring highlander source from {highlanderSourceCodePath}");
count = DirectoryHelper.CopyDirectory(highlanderSourceCodePath, edition.SdkSourceCodePath);
Report.Verbose($"Restored {count} files");
}
}
private void CopyModSourceCodeToSdk()
{
Report.Verbose("Copying mod source");
DirectoryHelper.CopyDirectory(modInfo.SourceCodePath, edition.SdkSourceCodePath);
}
private void CleanSdkCompiledScripts()
{
Report.Verbose("Deleting SDK compiled scripts");
DirectoryHelper.DeleteByExtension(edition.SdkXComGameCompiledScriptPath, SearchOption.AllDirectories, StringComparison.OrdinalIgnoreCase, ScriptExtension);
}
private void CleanModSdkCompiledScripts()
{
if (File.Exists(modSdkCompiledScriptPath))
{
Report.Verbose("Deleting mod compiled script");
DirectoryHelper.Delete(modSdkCompiledScriptPath);
}
}
private PackageFlags? GetBuiltStandardPackageFlags()
{
try
{
using var reader = new PackageReader(Path.Combine(edition.SdkXComGameCompiledScriptPath, KeyStandardPackageCompiledScriptFileName));
var header = reader.ReadHeader();
return header.PackageFlags;
}
catch (Exception)
{
return null;
}
}
private void SmartCleanSdkCompiledScripts()
{
Report.Verbose("Smart-cleaning compiled scripts");
foreach (var filePath in Directory.GetFiles(edition.SdkXComGameCompiledScriptPath))
{
var fileName = Path.GetFileName(filePath);
if (!StandardCompiledScripts.Any(x => string.Equals(x, fileName, StringComparison.OrdinalIgnoreCase)))
{
Report.Verbose($" Deleting non-standard compiled script file {fileName}", Verbosity.Loquacious);
DirectoryHelper.Delete(filePath);
}
}
Report.Verbose("Smart-cleaning compiled script manifest", Verbosity.Loquacious);
var manifestPath = Path.Combine(edition.SdkXComGameCompiledScriptPath, CompiledScriptManifestName);
var lines = File.ReadAllLines(manifestPath).ToList();
for (var i = 0; i < lines.Count; ++i)
{
var line = lines[i];
var parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length >= 3)
{
var module = parts[2];
if (!StandardManifestModules.Any(x => string.Equals(x, module, StringComparison.OrdinalIgnoreCase)))
{
Report.Verbose($" Removing line {line}", Verbosity.Periphrastic);
lines.RemoveAt(i);
--i;
}
}
}
File.WriteAllLines(manifestPath, lines, Program.DefaultEncoding);
}
private void CompileGame()
{
ThrowIfCancelled();
Report.Verbose("Compiling game");
if (!compiler.CompileGame())
{
throw new Exception("Game script compilation failed (bad game source?)");
}
ThrowIfCancelled();
}
private void CompileMod()
{
ThrowIfCancelled();
Report.Verbose("Compiling mod");
if (!compiler.CompileMod(modInfo.ModName, modStagingPath))
{
throw new Exception("Mod compilation failed");
}
ThrowIfCancelled();
}
private void CompileShaders()
{
ThrowIfCancelled();
Report.Verbose("Compiling shaders");
if (!compiler.CompileShaders(modInfo.ModName))
{
throw new Exception("Shader compilation failed");
}
ThrowIfCancelled();
}
private bool IsDeployedShaderCacheUpToDate()
{
var upToDate = false;
var shaderContent = modInfo.GetShaderContent();
if (shaderContent.Any())
{
var contentDate =
shaderContent.Select(x => new FileInfo(x).LastWriteTime)
.OrderByDescending(x => x)
.ToArray()
.First();
Report.Verbose($"Shader content updated {contentDate:G}");
//Report.Verbose($"Shader cache expected at {modShaderCacheInstallPath}");
if (File.Exists(modShaderCacheInstallPath))
{
var cacheDate = new FileInfo(modShaderCacheInstallPath).LastWriteTime;
Report.Verbose($"Shader cache updated {cacheDate:G}");
upToDate = cacheDate > contentDate;
}
else
{
Report.Verbose("Shader cache not found");
}
}
if (upToDate)
{
Report.Verbose("Shader cache is up to date");
}
else
{
Report.Verbose("Shader cache is out of date");
}
return upToDate;
}
private void CopyDeployedShaderCacheToStaging()
{
Report.Verbose("Copying deployed shader cache to staging");
DirectoryHelper.CopyFile(modShaderCacheInstallPath, modShaderCacheStagingPath);
}
private void StageModCompiledScripts()
{
Report.Verbose("Copying compiled script");
Directory.CreateDirectory(modStagingCompiledScriptFolderPath);
File.Copy(modSdkCompiledScriptPath, modStagingCompiledScriptFilePath);
}
private void DeployMod()
{
Report.Verbose("Deploying mod");
DirectoryHelper.Delete(modInstallPath);
DirectoryHelper.CopyDirectory(modStagingPath, modInstallPath);
}
}
}