forked from trumank/kismet-analyzer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
895 lines (814 loc) · 46.8 KB
/
Program.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
namespace KismetAnalyzer;
using System.CommandLine;
using System.CommandLine.Builder;
using System.CommandLine.Parsing;
using System;
using System.Text;
using System.Reflection;
using System.Diagnostics;
using UAssetAPI;
using UAssetAPI.Unversioned;
using UAssetAPI.UnrealTypes;
using UAssetAPI.ExportTypes;
using UAssetAPI.PropertyTypes.Objects;
using UAssetAPI.PropertyTypes.Structs;
using UAssetAPI.Kismet.Bytecode;
using UAssetAPI.Kismet.Bytecode.Expressions;
using Dot;
using Konsole;
using System.Runtime.InteropServices;
public class Program {
static int Main(string[] args) {
var rootCommand = new RootCommand();
var assetSource = new Argument<string>
(name: "src",
description: "Source asset");
var assetDestination = new Argument<string>
(name: "dest",
description: "Destination asset");
var assetMerged = new Argument<string>
(name: "merged",
description: "Merged asset");
var importIndexes = new Argument<IList<int>>
(name: "import indexes",
description: "Import indexes");
var assetInput = new Argument<string>
(name: "input",
description: "Path to asset");
var assetOutput = new Argument<string>
(name: "output",
description: "Path to asset");
var assetInputDirectory = new Argument<string>
(name: "input",
description: "Path to asset input directory");
var assetOutputDirectory = new Argument<string>
(name: "output",
description: "Path to asset output directory");
var cfgOutputDiretory = new Argument<string>
(name: "output",
description: "Path to CFG output directory");
var jsonOutput = new Argument<string>
(name: "output",
description: "Path to JSON output");
var jsonInput = new Argument<string>
(name: "input",
description: "Path to JSON input");
var jsonOutputDiretory = new Argument<string>
(name: "output",
description: "Path to JSON output directory");
var contextPath = new Argument<string>
(name: "context",
description: "Path to context JSON object generated by BPGen plugin (kismet.json in UE project directory)");
var showProgress = new Option<bool>
(name: "--progress",
description: "Show progress bar (possibly hides error messages)");
var dotPath = new Option<string>
(name: "--dot",
description: "Path to graphviz dot executable, otherwise will search PATH");
dotPath.AddValidator(result => {
if (!File.Exists(result.GetValueForOption(dotPath))) {
result.ErrorMessage = "--dot path does not exist";
}
});
var projectName = new Argument<string>
(name: "project-name",
description: "Unreal Engine project name (top level directory name in a game .pak)");
var ueVersion = new Option<EngineVersion>
(name: "--ue-version",
description: "Unreal Engine version",
getDefaultValue: () => EngineVersion.VER_UE4_27);
var mappings = new Option<string>
(name: "--mappings",
description: "Path to .usmap for assets using unversioned properties");
mappings.AddAlias("-m");
rootCommand.AddGlobalOption(ueVersion);
rootCommand.AddGlobalOption(mappings);
var cfg = new Command("cfg", "Generate control flow graphs of single asset and open in a web browser");
cfg.Add(assetInput);
cfg.Add(dotPath);
cfg.SetHandler(Cfg, ueVersion, mappings, assetInput, dotPath);
rootCommand.AddCommand(cfg);
var genCfg = new Command("gen-cfg", "Generate control flow graphs of single asset");
genCfg.Add(assetInput);
genCfg.Add(cfgOutputDiretory);
genCfg.SetHandler(GenCfg, ueVersion, mappings, assetInput, cfgOutputDiretory);
rootCommand.AddCommand(genCfg);
var genCfgTree = new Command("gen-cfg-tree", "Generate control flow graphs of assets");
genCfgTree.Add(assetInputDirectory);
genCfgTree.Add(cfgOutputDiretory);
genCfgTree.Add(projectName);
genCfgTree.Add(dotPath);
genCfgTree.Add(showProgress);
genCfgTree.SetHandler(GenCfgTree, ueVersion, mappings, assetInputDirectory, cfgOutputDiretory, projectName, dotPath, showProgress);
rootCommand.AddCommand(genCfgTree);
var genJsonTree = new Command("gen-json-tree", "Generate JSON representation of assets");
genJsonTree.Add(assetInputDirectory);
genJsonTree.Add(jsonOutputDiretory);
genJsonTree.SetHandler(GenJsonTree, ueVersion, mappings, assetInputDirectory, jsonOutputDiretory);
rootCommand.AddCommand(genJsonTree);
var toJson = new Command("to-json", "Convert binary asset to JSON");
toJson.Add(assetInput);
toJson.SetHandler(ToJson, ueVersion, mappings, assetInput);
rootCommand.AddCommand(toJson);
var read = new Command("read", "Read asset into memory");
read.Add(assetInput);
read.SetHandler(Read, ueVersion, mappings, assetInput);
rootCommand.AddCommand(read);
var fromJson = new Command("from-json", "Convert JSON to binary asset");
fromJson.Add(assetOutput);
fromJson.SetHandler(FromJson, ueVersion, mappings, assetOutput);
rootCommand.AddCommand(fromJson);
var genBlueprint = new Command("gen-blueprint", "Generate blueprint asset");
genBlueprint.Add(contextPath);
genBlueprint.Add(assetSource);
genBlueprint.Add(assetDestination);
genBlueprint.SetHandler(GenBlueprint, ueVersion, mappings, contextPath, assetSource, assetDestination);
rootCommand.AddCommand(genBlueprint);
var copyImports = new Command("copy-imports", "Copies imports from one asset to another and returns the new import indexes");
copyImports.Add(assetSource);
copyImports.Add(assetDestination);
copyImports.Add(importIndexes);
copyImports.SetHandler(CopyImports, ueVersion, mappings, assetSource, assetDestination, importIndexes);
rootCommand.AddCommand(copyImports);
var spliceAsset = new Command("splice-asset","splice asset");
spliceAsset.Add(assetInput);
spliceAsset.Add(assetOutput);
spliceAsset.SetHandler(SpliceAsset, ueVersion, mappings, assetInput, assetOutput);
rootCommand.AddCommand(spliceAsset);
var spliceMissionTerminal = new Command("splice-mission-terminal","splice asset");
spliceMissionTerminal.Add(assetInput);
spliceMissionTerminal.Add(assetOutput);
spliceMissionTerminal.SetHandler(SpliceMissionTerminal, ueVersion, mappings, assetInput, assetOutput);
rootCommand.AddCommand(spliceMissionTerminal);
var mergeFunctions = new Command("merge-functions",
@"Merge functions from source asset to the start of functions with matching names in the destination asset.
Leading underscores can be used to work around special function names being illegal in the editor.");
mergeFunctions.Add(assetSource);
mergeFunctions.Add(assetDestination);
mergeFunctions.Add(assetMerged);
mergeFunctions.SetHandler(MergeFunctions, ueVersion, mappings, assetSource, assetDestination, assetMerged);
rootCommand.AddCommand(mergeFunctions);
var findSchematics = new Command("find-schematics", "Find all Deep Rock Galactic schematics");
findSchematics.Add(assetInputDirectory);
findSchematics.SetHandler(FindSchematics, ueVersion, mappings, assetInputDirectory);
rootCommand.AddCommand(findSchematics);
var makeModRemoveWeaponBobbing = new Command("make-mod-remove-weapon-bobbing", "Generate remove weapon bobbing assets");
makeModRemoveWeaponBobbing.Add(assetInputDirectory);
makeModRemoveWeaponBobbing.Add(assetOutputDirectory);
makeModRemoveWeaponBobbing.SetHandler(MakeModRemoveWeaponBobbing, ueVersion, mappings, assetInputDirectory, assetOutputDirectory);
rootCommand.AddCommand(makeModRemoveWeaponBobbing);
var makeModRemoveAllParticles = new Command("make-mod-remove-all-particles", "Generate remove all particles assets");
makeModRemoveAllParticles.SetHandler(MakeModRemoveAllParticles, ueVersion);
rootCommand.AddCommand(makeModRemoveAllParticles);
var getType = new Command("get-type", "Get asset type");
getType.Add(assetInputDirectory);
getType.SetHandler(GetType, ueVersion, mappings, assetInputDirectory);
rootCommand.AddCommand(getType);
var akExport = new Command("abstract-kismet-export", "Export abstract kismet");
akExport.Add(assetInput);
akExport.Add(jsonOutput);
akExport.SetHandler(AbstractKismet.AbstractKismet.Export, ueVersion, assetInput, jsonOutput);
rootCommand.AddCommand(akExport);
var akImport = new Command("abstract-kismet-import", "Import abstract kismet");
akImport.Add(assetInput);
akImport.Add(assetOutput);
akImport.Add(jsonInput);
akImport.SetHandler(AbstractKismet.AbstractKismet.Import, ueVersion, assetInput, assetOutput, jsonInput);
rootCommand.AddCommand(akImport);
new CommandLineBuilder(rootCommand)
.UseVersionOption()
.UseHelp()
.UseEnvironmentVariableDirective()
.UseParseDirective()
.UseSuggestDirective()
.UseTypoCorrections()
.UseParseErrorReporting()
.UseExceptionHandler()
.CancelOnProcessTermination()
.Build()
.Invoke(args);
return 0;
}
static IEnumerable<string> GetAssets(string directory) {
var enumOptions = new EnumerationOptions();
enumOptions.IgnoreInaccessible = true;
enumOptions.RecurseSubdirectories = true;
return new[] { "*.uasset", "*.umap" }.SelectMany(pattern => Directory.EnumerateFiles(directory, pattern, enumOptions));
}
static UAsset LoadAsset(EngineVersion ueVersion, string? mappings, string assetPath) {
return mappings != null ? new UAsset(assetPath, ueVersion, new Usmap(mappings)) : new UAsset(assetPath, ueVersion);
}
static void WriteDotViewer(string dot, string outputPath, string? dotPath) {
ProcessStartInfo info = new ProcessStartInfo(dotPath ?? "dot");
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.ArgumentList.Add("-Tsvg");
var p = Process.Start(info) ?? throw new Exception("Process null");
p.Start();
p.StandardInput.Write(dot);
p.StandardInput.Close();
var svgData = p.StandardOutput.ReadToEnd();
p.WaitForExit();
var assembly = Assembly.GetAssembly(typeof(Program));
var resourceName = $"{assembly.GetName().Name.Replace("-", "_")}.viz.embed.html";
var template = new StreamReader(assembly.GetManifestResourceStream(resourceName)).ReadToEnd();
var html = template.Replace("[DATA]", Convert.ToBase64String(Encoding.UTF8.GetBytes(svgData)));
using(StreamWriter writetext = new StreamWriter(outputPath)) {
writetext.Write(html);
}
}
static void Cfg(EngineVersion ueVersion, string? mappings, string assetPath, string? dotPath) {
UAsset asset = LoadAsset(ueVersion, mappings, assetPath);
var dot = new StringWriter();
new SummaryGenerator(asset, StreamWriter.Null, dot).Summarize();
string outputPath = Path.Join(System.IO.Path.GetTempPath(), $"{Path.GetFileNameWithoutExtension(assetPath)}-{Guid.NewGuid().ToString()}.html");
WriteDotViewer(dot.ToString(), outputPath, dotPath);
Console.WriteLine($"writing to {outputPath}");
OpenUrl(outputPath);
}
static void GenCfg(EngineVersion ueVersion, string? mappings, string assetPath, string outputDir) {
UAsset asset = LoadAsset(ueVersion, mappings, assetPath);
var fileName = Path.GetFileName(assetPath);
var output = new StreamWriter(Path.Join(outputDir, Path.ChangeExtension(fileName, ".txt")));
var dotOutput = new StreamWriter(Path.Join(outputDir, Path.ChangeExtension(fileName, ".dot")));
new SummaryGenerator(asset, output, dotOutput).Summarize();
output.Close();
dotOutput.Close();
}
struct Progress {
public ProgressBar Bar {get; set;}
public TextWriter StdOut {get; set;}
public TextWriter StdError {get; set;}
public TextWriter NullOut {get; set;}
}
static void GenCfgTree(EngineVersion ueVersion, string? mappings, string assetInputDir, string output, string projectName, string? dotPath, bool showProgress) {
Directory.CreateDirectory(output);
var graph = new Graph("digraph");
graph.GraphAttributes["rankdir"] = "LR";
var assets = GetAssets(assetInputDir).ToList();
Progress? progress = null;
if (showProgress) {
progress = new Progress {
Bar = new ProgressBar(assets.Count()),
StdOut = Console.Out,
StdError = Console.Error,
NullOut = new System.IO.StreamWriter(System.IO.Stream.Null),
};
Console.SetOut(progress.Value.NullOut);
Console.SetError(progress.Value.NullOut);
}
var usmap = mappings != null ? new Usmap(mappings) : null;
var i = 0;
foreach (var assetPath in assets) {
if (progress is Progress p2) {
Console.SetOut(p2.StdOut);
p2.Bar.Refresh(i++, $"Hierarchy... ({Path.GetFileName(assetPath)})");
Console.SetOut(p2.NullOut);
}
var asset = new UAsset(assetPath, ueVersion, usmap);
var classExport = asset.GetClassExport();
if (classExport != null) {
var parent = classExport.SuperStruct.ToImport(asset);
var assetPackage = Path.Join("/Game", Path.GetRelativePath(Path.Join(assetInputDir, projectName, "Content"), Path.GetDirectoryName(assetPath)), Path.GetFileNameWithoutExtension(assetPath));
Console.WriteLine($"{assetPackage}.{classExport.ObjectName} : {parent.OuterIndex.ToImport(asset).ObjectName}.{parent.ObjectName}");
var fullClassName = $"{assetPackage}.{classExport.ObjectName}";
var fullParentName = $"{parent.OuterIndex.ToImport(asset).ObjectName}.{parent.ObjectName}";
string relativePath = Path.GetRelativePath(assetInputDir, Path.GetDirectoryName(assetPath));
string fileName = Path.ChangeExtension(Path.GetFileName(assetPath), ".html");
var classNode = new Node(fullClassName);
classNode.Attributes["label"] = classExport.ObjectName.ToString();
classNode.Attributes["URL"] = Path.Join("cfgs", relativePath, fileName).Replace('\\', '/');
graph.Nodes.Add(classNode);
var edge = new Edge(fullClassName, fullParentName);
graph.Edges.Add(edge);
}
}
var hierarchyPath = Path.Join(output, "index.html");
var hierarchy = new StringWriter();
graph.Write(hierarchy);
WriteDotViewer(hierarchy.ToString(), hierarchyPath, dotPath);
i = 0;
Parallel.ForEach(assets, assetPath => {
if (progress is Progress p2) {
Console.SetOut(p2.StdOut);
p2.Bar.Refresh(i++, $"CFGs... ({Path.GetFileName(assetPath)})");
Console.SetOut(p2.NullOut);
}
var outputDir = Path.GetDirectoryName(Path.Join(output, "cfgs", Path.GetRelativePath(assetInputDir, assetPath)));
var outputPath = Path.Join(outputDir, Path.ChangeExtension(Path.GetFileName(assetPath), ".html"));
Directory.CreateDirectory(outputDir);
UAsset asset = new UAsset(assetPath, ueVersion, usmap);
var dot = new StringWriter();
if (new SummaryGenerator(asset, TextWriter.Null, dot).Summarize()) {
WriteDotViewer(dot.ToString(), outputPath, dotPath);
}
});
if (progress is Progress p3) {
Console.SetOut(p3.StdOut);
Console.SetError(p3.StdError);
Console.WriteLine(); // wipe progress bar
}
Console.WriteLine($"Finished generating CFGs for {assets.Count()} assets");
}
static void GenJsonTree(EngineVersion ueVersion, string? mappings, string assetInputDir, string jsonOutputDir) {
foreach (var assetPath in GetAssets(assetInputDir)) {
var outputPath = Path.ChangeExtension(Path.Join(jsonOutputDir, Path.GetRelativePath(assetInputDir, assetPath)), ".json");
var asset = LoadAsset(ueVersion, mappings, assetPath);
string jsonSerializedAsset = asset.SerializeJson(Newtonsoft.Json.Formatting.Indented);
Console.WriteLine(outputPath);
Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
File.WriteAllText(outputPath, jsonSerializedAsset);
}
}
static void ToJson(EngineVersion ueVersion, string? mappings, string assetInput) {
Console.WriteLine(LoadAsset(ueVersion, mappings, assetInput).SerializeJson(Newtonsoft.Json.Formatting.Indented));
}
static void Read(EngineVersion ueVersion, string? mappings, string assetInput) {
LoadAsset(ueVersion, mappings, assetInput);
Console.WriteLine("complete");
}
static void FromJson(EngineVersion ueVersion, string? mappings, string assetOutput) {
UAsset.DeserializeJson(Console.OpenStandardInput()).Write(assetOutput);
}
static void CopyImports(EngineVersion ueVersion, string? mappings, string assetSource, string assetDestination, IList<int> imports) {
UAsset from = LoadAsset(ueVersion, mappings, assetSource);
UAsset to = LoadAsset(ueVersion, mappings, assetDestination);
foreach (var index in imports) {
var newIndex = Kismet.CopyImportTo((from, FPackageIndex.FromRawIndex(index)), to);
var i = newIndex.ToImport(to);
Console.WriteLine($"Copied import {index} => {newIndex}: {i.ClassName}, {i.ClassPackage}, {i.ObjectName}");
}
to.Write(assetDestination);
}
static void SpliceAsset(EngineVersion ueVersion, string? mappings, string assetInput, string assetOutput) {
UAsset input = LoadAsset(ueVersion, mappings, assetInput);
Kismet.SpliceAsset(input);
input.Write(assetOutput);
}
static void SpliceMissionTerminal(EngineVersion ueVersion, string? mappings, string assetInput, string assetOutput) {
UAsset input = LoadAsset(ueVersion, mappings, assetInput);
Kismet.SpliceMissionTerminal(input);
input.Write(assetOutput);
}
static void MergeFunctions(EngineVersion ueVersion, string? mappings, string assetSource, string assetDestination, string assetMerged) {
UAsset source = LoadAsset(ueVersion, mappings, assetSource);
UAsset dest = LoadAsset(ueVersion, mappings, assetDestination);
foreach (var export in source.Exports) {
if (export is FunctionExport fnSrc) {
if (export.ObjectName.ToString().StartsWith("ExecuteUbergraph")) {
Console.Error.WriteLine("Ignoring ubergraph");
continue;
}
var found = false;
foreach (var exportDest in dest.Exports) {
if (exportDest is FunctionExport fnDest) {
if (fnSrc.ObjectName.ToString().TrimStart('_') != fnDest.ObjectName.ToString().TrimStart('_')) continue;
Console.WriteLine($"Found matching function named {export.ObjectName}");
var newInst = new List<KismetExpression>();
//for (int i = 0; i < fnSrc.ScriptBytecode.Length; i++) {
var offset = 0;
var keepReturn = false;
foreach (var inst in fnSrc.ScriptBytecode) {
if (inst is EX_Context c) {
if (c.ContextExpression is EX_LocalVirtualFunction i) {
if (i.VirtualFunctionName.Value.ToString() == "RETURN") {
keepReturn = true;
continue; // TODO handle offset addresses in source function because now we're skipping expressions
}
}
}
var isReturn = inst.GetType() == typeof(EX_Return);
if (isReturn ? keepReturn : true) {
offset += (int) Kismet.GetSize(source, inst);
newInst.Add(Kismet.CopyExpressionTo(inst, source, dest, fnSrc, fnDest));
}
if (isReturn) break;
}
foreach (var inst in fnDest.ScriptBytecode) {
Kismet.ShiftAddressses(inst, offset);
newInst.Add(inst);
}
fnDest.ScriptBytecode = newInst.ToArray();
found = true;
break;
}
}
if (!found) {
Kismet.CopyExportTo((source, FPackageIndex.FromExport(source.Exports.IndexOf(export))), dest);
}
}
}
dest.Write(assetMerged);
}
static void GenBlueprint(EngineVersion ueVersion, string? mappings, string contextPath, string assetSource, string assetDestination) {
var context = UEContext.FromFile(contextPath);
UAsset source = LoadAsset(ueVersion, mappings, assetSource);
var generator = new BlueprintGenerator(context, source);
generator.Generate();
}
static void FindSchematics(EngineVersion ueVersion, string? mappings, string assetInputDir) {
foreach (var assetPath in GetAssets(assetInputDir)) {
//var file = Path.GetFileName(assetPath);
//if (!Path.GetFileName(assetPath).StartsWith("IAS_") || file == "IAS_Snowball.uasset") continue;
UAsset asset = LoadAsset(ueVersion, mappings, assetPath);
//Console.WriteLine(assetPath);
foreach (var export in asset.Exports) {
if (export.ClassIndex.IsImport() && export.ClassIndex.ToImport(asset).ObjectName.ToString() == "Schematic" && export is NormalExport e) {
Console.WriteLine($"{assetPath} {export.ObjectName}");
if (e["SaveGameID"] is StructPropertyData idStruct && idStruct.Value[0] is GuidPropertyData id) {
Console.WriteLine(id);
}
if (e["Item"] is ObjectPropertyData objData
&& objData.IsExport() &&
objData.ToExport(asset) is NormalExport schematicItem) {
var type = schematicItem.ClassIndex.ToImport(asset).ObjectName.ToString();
switch (type.ToString()) {
case "SkinSchematicItem":
{
if (schematicItem["Skin"] is ObjectPropertyData skinData) {
if (skinData.IsExport()) {
//var item3 = skinData.ToExport(asset);
//Console.WriteLine($"{item3.ObjectName}");
} else if (skinData.IsImport()) {
//var item3 = skinData.ToImport(asset);
//Console.WriteLine($"{item3.ObjectName}");
} else {
throw new NotImplementedException("Expected import");
}
} else {
throw new NotImplementedException("No ObjectPropertyData \"Skin\"");
}
break;
}
case "VanitySchematicItem":
{
if (schematicItem["Item"] is ObjectPropertyData vanityData) {
if (vanityData.IsExport() && vanityData.ToExport(asset) is NormalExport vanityItem) {
if (vanityItem["ItemName"] is TextPropertyData txt) {
Console.WriteLine(txt.CultureInvariantString);
} else {
throw new NotImplementedException("Expected TextPropertyData");
}
} else if (vanityData.IsImport()) {
//throw new NotImplementedException("Expected export");
//var item3 = vanityData.ToImport(asset);
//Console.WriteLine($"{item3.ObjectName}");
} else {
throw new NotImplementedException("Expected import");
}
} else {
throw new NotImplementedException("No ObjectPropertyData \"Item\"");
}
break;
}
case "OverclockShematicItem":
{
break;
}
case "ResourceSchematicItem":
{
break;
}
case "VictoryPoseSchematicItem":
{
break;
}
case "BlankSchematicItem":
{
break;
}
default:
{
throw new NotImplementedException($"Unknown schematic type {type}");
}
}
} else {
throw new NotImplementedException("Expected import");
}
}
}
}
}
static void MakeModRemoveWeaponBobbing(EngineVersion ueVersion, string? mappings, string assetInputDirectory, string assetOutputDirectory) {
List<string> fpNames = new List<string> {
//"FP_Idle",
//"FP_InspectWeapon",
//"FP_Walk",
//"FP_Sprint",
"FP_JumpStart",
"FP_JumpLoop",
"FP_JumpLand",
"FP_JumpLand_Aim",
//"FP_Downed",
};
HashSet<(string, string)> animations = new HashSet<(string, string)>();
foreach (var assetPath in GetAssets(assetInputDirectory)) {
var file = Path.GetFileName(assetPath);
if (!Path.GetFileName(assetPath).StartsWith("IAS_") || file == "IAS_Snowball.uasset") continue;
var outputPath = Path.Join(assetOutputDirectory, Path.GetRelativePath(assetInputDirectory, assetPath));
UAsset asset = LoadAsset(ueVersion, mappings, assetPath);
Console.WriteLine(assetPath);
foreach (var export in asset.Exports) {
if (export.ClassIndex.IsImport() && export.ClassIndex.ToImport(asset).ObjectName.ToString() == "ItemCharacterAnimationSet" && export is NormalExport e) {
Console.WriteLine(export.ObjectName);
Dictionary<string, ObjectPropertyData> props = new Dictionary<string, ObjectPropertyData>();
foreach (var prop in e.Data) {
var name = prop.Name.ToString();
if (prop is ObjectPropertyData anim) {
props[name] = anim;
if (fpNames.Contains(name)) {
var path = Path.Join(assetInputDirectory, Path.GetRelativePath("/Game", anim.Value.ToImport(asset).OuterIndex.ToImport(asset).ObjectName + ".uasset"));
animations.Add((path, prop.Name.ToString()));
}
}
}
//if (props.ContainsKey("FP_Walk") && props.ContainsKey("FP_Sprint"))
//props["FP_Walk"].Value = props["FP_Sprint"].Value;
/*
if (fpWalk != null) {
foreach (var prop in e.Data) {
if (fpNames.Contains(prop.Name.ToString()) && prop is ObjectPropertyData anim) {
anim.Value = fpWalk;
}
}
}
*/
break;
}
}
Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
asset.Write(outputPath);
Console.WriteLine(outputPath);
}
foreach (var (assetPath, animationType) in animations) {
var outputPath = Path.Join(assetOutputDirectory, Path.GetRelativePath(assetInputDirectory, assetPath));
UAsset asset = LoadAsset(ueVersion, mappings, assetPath);
string? type = null;
foreach (var export in asset.Exports) {
if (export.ClassIndex.IsImport() && export.ClassIndex.ToImport(asset).ObjectName.ToString() == "AnimSequence" && export is NormalExport e) {
foreach (var prop in e.Data) {
if (prop.Name.ToString() == "NumFrames" && prop is IntPropertyData numFrames) {
//numFrames.Value = 1;
}
if (prop.Name.ToString() == "SequenceLength" && prop is FloatPropertyData sequenceLength) {
if (animationType == "FP_JumpLand") {
sequenceLength.Value = 0.01f;
} else {
sequenceLength.Value = 999999999999;
}
}
if (prop.Name.ToString() == "Skeleton" && prop is ObjectPropertyData skeleton) {
type = skeleton.Value.ToImport(asset).ObjectName.ToString();
//sequenceLength.Value = 0;
}
}
break;
}
}
if (type == "1P_Dwarf_Rig_Skeleton") {
Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
asset.Write(outputPath);
Console.WriteLine(outputPath);
}
//Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
//var asset = new UAsset(assetPath, ueVersion);
}
}
static void MakeModRemoveAllParticles(EngineVersion ueVersion) {
UAsset particleAsset = new UAsset("FSD/Saved/Cooked/LinuxNoEditor/FSD/Content/_Tests/Dummy/EmptyParticleSystem.uasset", ueVersion);
int particleAssetNameIndex = particleAsset.SearchNameReference(new FString("EmptyParticleSystem"));
int particleAssetPathIndex = particleAsset.SearchNameReference(new FString("/Game/_Tests/Dummy/EmptyParticleSystem"));
UAsset niagaraAsset = new UAsset("FSD/Saved/Cooked/LinuxNoEditor/FSD/Content/_Tests/Dummy/EmptyNiagaraSystem.uasset", ueVersion);
int niagaraAssetNameIndex = niagaraAsset.SearchNameReference(new FString("EmptyNiagaraSystem"));
int niagaraAssetPathIndex = niagaraAsset.SearchNameReference(new FString("/Game/_Tests/Dummy/EmptyNiagaraSystem"));
string[] exclusions = {
"FSD/Content/Critters/FesterFlea/Flea/P_Flea_Trail",
"FSD/Content/Art/Particles/ActorFX/P_GreenMaggot_PoisonCloud",
"FSD/Content/Art/Particles/ActorFX/Spawning/P_SpawnCloud_Large",
"FSD/Content/Art/Particles/P_Geyser_EruptAir",
"FSD/Content/Enemies/Spider/Spitter/P_SpittingSpiderProjectile_A",
"FSD/Content/Enemies/Spider/Shooter/P_SpiderShooterProjectile_A",
"FSD/Content/Enemies/Spider/Tank/Particles/P_RadioActive_Cloud",
"FSD/Content/Enemies/Spider/RapidShooter/P_Spider_RapidShooterProjectile_A",
"FSD/Content/Enemies/Spider/Particles/P_Spider_Tank_AcidFlame",
"FSD/Content/Enemies/Spider/Particles/P_Spider_TankIce_Shoot",
"FSD/Content/Enemies/Spider/Particles/P_Spider_Tank_DeathCloud",
"FSD/Content/Enemies/Spider/Particles/P_Spider_TankIce_DeathCloud",
"FSD/Content/Enemies/Plague/Particles/NS_Plague_Spider_Tank_DeathCloud",
"FSD/Content/Enemies/Plague/Particles/NS_Plague_Projectile_Trail",
"FSD/Content/Enemies/Spider/Tank/Particles/P_RadioActive_Cloud",
"FSD/Content/Enemies/Spider/Tank/Particles/P_RadioActive_Cloud_Medium",
"FSD/Content/Enemies/Spider/Particles/P_Spider_BarrageAttack_A",
"FSD/Content/Enemies/Spider/Particles/P_Spider_Tank_DeathCloud",
"FSD/Content/Enemies/Spider/Particles/P_Spider_TankPlague_Shoot",
"FSD/Content/Enemies/Spider/TankBoss/BossTank/P_Spider_Boss_ShootTrail",
"FSD/Content/Enemies/Spider/TankBoss/BossHeavy/Particles/NS_Rock_Projectile",
"FSD/Content/Enemies/Spider/TankBoss/BossHeavy/Particles/P_SentinelGoo_AOEpuddle",
"FSD/Content/Enemies/Spider/TankBoss/BossTwins/P_Spider_BossTwin_SmallShootTrail",
"FSD/Content/Enemies/Spider/TankBoss/BossTwins/Particles/NS_Twin_Fire_Breath",
"FSD/Content/Enemies/Spider/TankBoss/BossTwins/Particles/NS_Stomp_Wave",
"FSD/Content/Enemies/Spider/TankBoss/BossTwins/P_TwinA_Mine_AreaAttackWindup",
"FSD/Content/Enemies/Spider/TankBoss/BossTwins/P_Spider_BossTwin_Explosion",
"FSD/Content/Enemies/Spider/TankBoss/BossTwins/P_TwinA_Mine_AreaAttack",
"FSD/Content/Enemies/Spider/TankBoss/BossTank/P_Spider_Boss_AreaAttack_B",
"FSD/Content/Enemies/FlyingBug/Bomber/P_BomberGoo_AOEpuddle",
"FSD/Content/Enemies/FlyingBug/Bomber/P_BomberIce_AOEpuddle",
"FSD/Content/Enemies/Woodlouse/Particles/P_WoodLouse_Projectile",
"FSD/Content/LevelElements/RoomObjects/Hazards/InsectSwarm/P_InsectSwarm_A",
"FSD/Content/Landscape/Biomes/Biomes_Ingame/HollowBough/WaspNest/P_InsectSwarm_Showroom",
"FSD/Content/GameElements/Missions/Warnings/HeroEnemies/Particle_Effects/NS_HeroEnemy_Beacon_Constant_Big",
"FSD/Content/GameElements/Missions/Warnings/HeroEnemies/Particle_Effects/NS_HeroEnemy_Beacon_Constant",
"FSD/Content/GameElements/Missions/Warnings/Plague/CleaningPod/Soaper/NS_Foam_Projectile",
"FSD/Content/GameElements/Missions/Warnings/Plague/CleaningPod/Soaper/NS_Foam_Puddle",
"FSD/Content/Enemies/HydraWeed/Particles/P_HealerSeed_Trail",
"FSD/Content/Enemies/HydraWeed/Particles/P_ShooterSeed_Trail",
"FSD/Content/GameElements/Objectives/Facility/DefenseTurret/P_FacilityTurret_Sniperbeam",
"FSD/Content/GameElements/Objectives/Facility/NS_Facility_Projectile_Power_Sniper",
"FSD/Content/GameElements/Objectives/Facility/NS_Facility_Projectile",
"FSD/Content/GameElements/Objectives/Facility/NS_Facility_Projectile",
"FSD/Content/GameElements/Objectives/Facility/NS_Facility_Projectile_Power",
"FSD/Content/GameElements/Objectives/Facility/DefensiveTentacles/NS_Defence_Tentacle_Projectile",
"FSD/Content/Enemies/Spider/ExploderTank/P_ExploderTank_CollectingEmbers",
"FSD/Content/Enemies/Spider/ExploderTank/P_GhostTank_CollectingEmbers",
"FSD/Content/Enemies/Spider/Particles/P_SpiderExploderTank_Footstep",
"FSD/Content/LevelElements/RoomObjects/Hazards/StickyGoo/P_StickyGoo",
"FSD/Content/LevelElements/RoomObjects/Hazards/PoisonGasFungus/P_PoisonGasFungus_PoisonCloud",
"FSD/Content/LevelElements/RoomObjects/Hazards/LavaGeyser/P_Geyser_EruptLava_Small_Tell",
"FSD/Content/LevelElements/RoomObjects/Hazards/ExplodingGooPlant/P_ExplodingGooPlant_AOEpuddle",
"FSD/Content/LevelElements/RoomObjects/Hazards/SandGeyser/P_Geyser_Sand_Errupt_Outside",
"FSD/Content/LevelElements/RoomObjects/Hazards/SandGeyser/P_Geyser_Sand_Inside-Idle",
"FSD/Content/LevelElements/RoomObjects/Hazards/FrostGeyser/P_Geyser_Frost_Errupt_Outside",
"FSD/Content/LevelElements/RoomObjects/Hazards/FrostGeyser/P_Geyser_Frost_Inside-Idle",
"FSD/Content/LevelElements/RoomObjects/Hazards/ElectricPlant/Particles/P_ElectroPlantBeam",
"FSD/Content/LevelElements/Refinery/LiquidMorkite_Well/P_LiquidMorkite_Well",
"FSD/Content/GameElements/Objectives/Escort/FlyingSmartRocks/P_Heartstone_ConnectionLine",
"FSD/Content/GameElements/Objectives/Facility/Tethers/NS_Teather_Beam",
"FSD/Content/GameElements/PawnAffliction/EnemyEffects/Burning/P_Burning_Huge",
"FSD/Content/GameElements/PawnAffliction/EnemyEffects/Burning/P_Burning_Large",
"FSD/Content/GameElements/PawnAffliction/EnemyEffects/Burning/P_Burning_Medium",
"FSD/Content/GameElements/PawnAffliction/EnemyEffects/Burning/P_Burning_Small",
"FSD/Content/GameElements/PawnAffliction/EnemyEffects/Poisoned/P_PoisonedEnemy_Medium",
"FSD/Content/GameElements/PawnAffliction/EnemyEffects/Poisoned/P_PoisonedEnemy_Tiny",
"FSD/Content/GameElements/PawnAffliction/EnemyEffects/Eletrocuted/P_State_Electrocute_2Mid",
"FSD/Content/GameElements/PawnAffliction/EnemyEffects/Regenerating/P_RegenrativeEnemies_FX",
"FSD/Content/GameElements/Drone/P_Drone_Tracer",
"FSD/Content/GameElements/Drone/P_Bosco_Rocket_Trail",
"FSD/Content/WeaponsNTools/Extractor/P_OilExtractor_BeamActive",
"FSD/Content/WeaponsNTools/Extractor/P_OilExtractor_BeamInactive",
"FSD/Content/WeaponsNTools/SentryGun/P_Sentry_Tracer",
"FSD/Content/WeaponsNTools/SentryGun/SentryGun_Engineer/P_OverchargeProjectile_Trail",
"FSD/Content/Enemies/Spider/Tank/Particles/P_RadioActive_Cloud_Large",
"FSD/Content/WeaponsNTools/LineCutter/Particles/P_Plasma_Projectile",
"FSD/Content/WeaponsNTools/LineCutter/Particles/P_PlasmaBeam_PlasmaTrailSegment",
"FSD/Content/WeaponsNTools/SentryGun/P_ElectrocutedTurret",
"FSD/Content/GameElements/GameEvents/AmberEvent/Particles/P_AmberEvent_Explosion",
"FSD/Content/WeaponsNTools/ChargeBlaster/Particles/P_ChargedProjectileExplodeBig",
"FSD/Content/WeaponsNTools/ChargeBlaster/Particles/P_ChargedProjectile_Persistance",
"FSD/Content/WeaponsNTools/ChargeBlaster/Particles/P_UPG_Charged_AOE",
"FSD/Content/WeaponsNTools/FlameThrower/Particles/P_WPN_Environment_StickyFlame",
"FSD/Content/WeaponsNTools/FlameThrower/Particles/P_WPN_Flamethrower_Plume_1stPerson",
"FSD/Content/WeaponsNTools/FlameThrower/Particles/P_UPG_Flamethrower_HighPressure_1stPerson_New",
"FSD/Content/WeaponsNTools/FlameThrower/Particles/P_UPG_Flamethrower_VeryHighPressure_1stPerson",
"FSD/Content/WeaponsNTools/Cryospray/Particles/P_WPN_Cryospray_Impact",
"FSD/Content/WeaponsNTools/Cryospray/Particles/P_WPN_Cryospray_1stPerson",
"FSD/Content/WeaponsNTools/Cryospray/Particles/P_WPN_Cryospray_3rdPerson",
"FSD/Content/WeaponsNTools/Cryospray/Particles/P_WPN_Environment_StickyFrost",
"FSD/Content/WeaponsNTools/Grenades/Neurotoxin/P_Grenade_Neurotoxin_Cloud",
"FSD/Content/WeaponsNTools/GooCannon/Particles/NS_Goo_Projectile",
"FSD/Content/WeaponsNTools/GooCannon/Particles/NS_Goo_Puddle",
"FSD/Content/WeaponsNTools/GooCannon/Particles/NS_GooCannon_DoT",
"FSD/Content/WeaponsNTools/GooCannon/Particles/NS_GooCannon_DoT_Large",
"FSD/Content/WeaponsNTools/GooCannon/Particles/NS_GooCannon_DoT_XLarge",
"FSD/Content/WeaponsNTools/Autocannon/Particles/NS_AutoCannon_ShotImpact",
"FSD/Content/WeaponsNTools/Grenades/Incendiary/P_Grenade_Incendiary_Flames",
"FSD/Content/WeaponsNTools/Grenades/IFG/P_Grenade_IFG_Explosion_A_AttemptingGFXfix",
"FSD/Content/WeaponsNTools/Grenades/ParasiteGrenade/NS_Grenade_Parasites_Explosion",
"FSD/Content/WeaponsNTools/Grenades/Pheromone/P_Grenade_Pheromone_Soaked",
"FSD/Content/WeaponsNTools/PlasmaCarbine/Particles/NS_PlasmaCarbine_Projectile",
"FSD/Content/WeaponsNTools/Crossbow/Particles/NS_Crossbow_Bodkin",
"FSD/Content/WeaponsNTools/Crossbow/Particles/",
"FSD/Content/Art/Environments/Holiday_Halloween/",
"FSD/Content/Art/Environments/Holiday_Xmas/",
"FSD/Content/Art/Environments/SpaceRig/",
"FSD/Content/Art/Environments/SpaceRig_Exterior/",
"FSD/Content/GameElements/Bar/",
"FSD/Content/CharacterStructure/Forge/",
"FSD/Content/Character/",
"FSD/Content/CharacterStructure/Gear_Unarmed/TP/EndScreenAnims/Attachments/",
"FSD/Content/Enemies/Spider/Exploder/P_BarrelExplosion",
"FSD/Content/Enemies/Spider/Buffer/p_BufferArc",
"FSD/Content/Enemies/HydraWeed/Particles/p_HydraWeed_BuffLine",
"FSD/Content/WeaponsNTools/CoilGun/Assets/Particles/P_WPN_Environment_Coilgun_StickyFlame",
"FSD/Content/WeaponsNTools/CoilGun/Assets/Particles/NS_CoilGun_Multi_Trail",
"FSD/Content/WeaponsNTools/Autocannon/Overclocks/OC_BonusesAndPenalties/NS_OC_NeuroToxin_Payload",
"FSD/Content/WeaponsNTools/HeavyParticleCannon/Particles/NS_HPC_Volatile_Impact_Reactor",
};
string[] weaponsntools = {
"FSD/Content/WeaponsNTools/",
"FSD/Content/GameElements/Drone/",
};
var unmatched = new HashSet<string>(exclusions);
var FSDPath = "unpacked-fsd";
var OutputRemoveParticles = "unpacked-mods/remove-all-particles";
var OutputRemoveParticlesButWeaponsNTools = "unpacked-mods/remove-all-particles-but-weaponsntools";
try { Directory.Delete(OutputRemoveParticles, true); } catch {}
try { Directory.Delete(OutputRemoveParticlesButWeaponsNTools, true); } catch {}
foreach (var assetPath in GetAssets(FSDPath)) {
var relPath = Path.GetRelativePath(FSDPath, Path.ChangeExtension(assetPath, null));
var exclude = false;
foreach (var ex in exclusions) {
if (relPath.StartsWith(ex)) {
unmatched.Remove(ex);
exclude = true;
// cannot break out early as some exclusions won't match and will cause a warning
}
}
if (exclude) {
continue;
}
UAsset asset = new UAsset(assetPath, ueVersion);
foreach (var export in asset.Exports) {
if (export.ClassIndex.IsImport()) {
var assetType = export.ClassIndex.ToImport(asset).ObjectName.ToString();
var name = Path.GetFileNameWithoutExtension(assetPath);
var path = Path.Combine("/Game/", relPath);
UAsset? empty = null;
if (assetType == "ParticleSystem") {
empty = particleAsset;
empty.SetNameReference(particleAssetNameIndex, new FString(name));
empty.SetNameReference(particleAssetPathIndex, new FString(path));
} else if (assetType == "NiagaraSystem") {
empty = niagaraAsset;
empty.SetNameReference(niagaraAssetNameIndex, new FString(name));
empty.SetNameReference(niagaraAssetPathIndex, new FString(path));
}
if (empty != null) {
var withExtension = $"{relPath}.uasset";
var outPath = Path.Join(OutputRemoveParticles, withExtension);
Directory.CreateDirectory(Path.GetDirectoryName(outPath));
empty.Write(outPath);
var excludeWNT = false;
foreach (var ex in weaponsntools) {
if (relPath.StartsWith(ex)) {
excludeWNT = true;
}
}
if (!excludeWNT) {
var outPathWNT = Path.Join(OutputRemoveParticlesButWeaponsNTools, withExtension);
Directory.CreateDirectory(Path.GetDirectoryName(outPathWNT));
empty.Write(outPathWNT);
}
break;
}
}
}
}
foreach (var ex in unmatched) {
Console.Error.WriteLine($"WARNING: Exclusion {ex} did not have any matches");
}
}
static void GetType(EngineVersion ueVersion, string? mappings, string assetInputDirectory) {
var autoVerified = new HashSet<string> {
"SoundWave",
"SoundCue",
"SoundClass",
"SoundMix",
"MaterialInstanceConstant",
"Material",
"SkeletalMesh",
"StaticMesh",
"Texture2D",
"AnimSequence",
"Skeleton",
"StringTable",
};
foreach (var (type, autoVerify, asset) in GetAssets(assetInputDirectory).AsParallel().Select(assetPath => {
UAsset asset = LoadAsset(ueVersion, mappings, assetPath);
var primary = asset.Exports.First(e => e.OuterIndex.IsNull());
var type = primary.ClassIndex.ToImport(asset).ObjectName.ToString();
return (
type,
autoVerified.Contains(type),
Path.GetRelativePath(assetInputDirectory, assetPath)
);
}).OrderBy(t => t.Item1)) {
Console.WriteLine($"{type},{autoVerify},{asset}");
}
}
// https://stackoverflow.com/a/43232486
static void OpenUrl(string url) {
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
url = url.Replace("&", "^&");
Process.Start(new ProcessStartInfo(url) { UseShellExecute = true });
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
Process.Start("open", url);
}
}
}