/
parse.js
2680 lines (2457 loc) · 85.7 KB
/
parse.js
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
// https://coolors.co/333344-45cb85-ff4f79-1e91d6-f4ac45
const VERSION = "2.3.4";
const containers = {
mods: document.querySelector("#mod-list"),
details: document.querySelector("#mod-details"),
};
const PROGRESS_READ = 50;
const PROGRESS_FINISH = 30;
const PROGRESS_SORT = 10;
const LOG_REGEX =
/^(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}).(?<ms>\d+) +(?<level>[A-Z]+) .+?: /;
const XML_REGEX = /\r?<\\*color.*?>/g;
const UNMODDED_REGEX = /^(ThunderRoad|Unity|DelegateList|RainyReignGames|ONSPAudioSource|SteamVR|OVR|OculusVR|System|StateTracker|\(wrapper|Valve|delegate|MonoBehaviourCallbackHooks|Newtonsoft|TMPro|UsingTheirs|FadeMixerGroup)/;
const IGNORED_ARGS = [
"Newtonsoft.",
"ThunderRoad.",
"Collections.",
"Generic.",
"Valve.",
"UnityEngine.",
"Unity.",
"System.",
"ResourceManagement.",
"AsyncOperations.",
"StateTracker.",
];
const IGNORED_PREVIEW = [
/^UnityEngine\.Rigidbody\./,
/^ThunderRoad\.PhysicBody\./,
/^UnityEngine\.Transform\./,
/^UnityEngine\./,
/^System\./,
]
const TAG_ICONS = {
dll: "plugin",
pdb: "search-2",
harmony: "screw-driver"
}
const COMMON_NAMESPACES = {
TOR: "TheOuterRim",
AMP: "MultiplayerMod"
}
const SYSTEM_INFO_KEYS = {
deviceType: "device_type",
graphicsDeviceName: "graphics_device_name",
graphicsDeviceType: "graphics_device_type",
graphicsDeviceVendor: "graphics_device_vendor",
graphicsMemorySize: "graphics_memory_size",
graphicsShaderLevel: "graphics_shader_level",
operatingSystem: "operating_system",
processorType: "processor_type",
processorCount: "processor_count",
processorFrequency: "processor_frequency",
systemMemorySize: "system_memory_size",
IsMobilePlatform: "is_mobile_platform",
supportsMultisampleAutoResolve: "supports_multisample_auto_resolve",
platformRequiresExplicitMsaaResolve: "platform_requires_explicit_msaa_resolve"
}
const CERTAINTY = {
certain: "Almost certain this mod is the cause.",
sure: "Pretty sure that this mod is the cause, but not guaranteed.",
likely: "This mod could be cause, but it's definitely not guaranteed.",
unsure: "This mod may or may not be the cause; this is simply the best guess available."
}
const REASONS = {
name: "Saw mod's name in log entry.",
folder: "Saw mod folder name in log entry.",
catalog: "Saw mod catalog name in log entry.",
namespace: "Matched C# namespace to a namespace associated with this mod.",
assembly: "Matched C# namespace to mod DLL name.",
fuzzy: "Used fuzzy text matching to guess mod. Closeness: [[score]]",
base_game: "Appears to be unmodded entry.",
address: "Matched mod Addressables address.",
};
const SUGGESTIONS = {
"delete-save": {
title: "Delete your save file.",
description: `Go to ${code(
"Documents/My Games/Blade & Sorcery/Saves/Default"
)} and delete all files present there.`,
},
"check-dll": {
title: "Check your scripted mods for missing DLL files.",
description:
"Sometimes, antivirus software can treat DLL files (which is where mod scripting and logic lives) as suspicious files. " +
"Double-check that your scripted mods each contain a .dll file.",
cols: ["mod", "possible_missing_dll_name"],
},
"missing-method": {
title:
"Ensure your mods are up to date, or remove ones that aren't yet updated.",
description:
"One or more of your mods attempted to run code that doesn't exist in the version of the game you are running.<br>" +
"This may be because a minor version update broke it - e.g. if the mod worked on 12.2, but you updated to 12.3.",
cols: ["mods", "method"],
},
"broken-json": {
title: "Fix syntax errors in your JSON file(s).",
description:
"One or more of your mods broke the game's JSON parser (likely due to a syntax error). If this is your mod, or if you've made changes to one of these JSON files, make sure they are valid.<br>" +
`You can paste your JSON file into <a href="https://jsonlint.com/">jsonlint.com</a> to debug syntax errors.`,
cols: ["mod", "json_file", "error"]
},
pirated: {
title:
icon("warning") +
"Buy Blade and Sorcery legitimately on Steam or Oculus." +
icon("warning"),
description:
"<strong>Do not ask for help with modding if you own an illegitimate copy of the game.</strong><br>" +
"If you have pirated the game you should <em>not</em> expect mods to work.",
},
incompatible: {
title:
"Make sure you have installed mods that are for the correct version of the game.",
description:
"One or more of your mods is not for this version of the game. They have not been loaded.",
},
"duplicate-bundle": {
title: "Ensure you have not installed a mod multiple times.",
description: "Your log file suggests that you have installed a mod more than once. "
+ "Make sure you haven't installed any extra copies, especially ones hiding inside other mod folders.",
cols: ["mod", "duplicate_bundle_found"]
},
"bundle-version": {
title: "Ensure your mods are built for the right version of Unity.",
description: () => `It looks like the following bundles have not been built for the correct version of Unity.`
+ "<ul>"
+ `<li>If this is your mod, ensure that you are exporting your mod from the correct Unity editor version; this log was generated from version <code>${game.system.unity_version}</code>.</li>`
+ `<li>If you've attempted to update a mod by just changing the <code>manifest.json</code> file, you are out of luck and you will need to wait for the modder to update their mod.</li>`
+ "</ul>",
cols: ["mod", "bundle"]
}
};
const EXCEPTIONS = {
NullReferenceException:
"This exception is thrown when a property or method is accessed on a null object.",
ArgumentOutOfRangeException:
"This exception is thrown when an argument to a method is outside the allowed range of values.",
DllNotFoundException:
"This exception is thrown when a referenced DLL cannot be found.",
};
const EXCEPTION_TAGS = {
unmodded: {
icon: "info-circle",
text: "This exception traceback does not mention any modded code.<br><br>It may be a base-game issue, but more likely it's the game reacting poorly to something a mod has done.",
},
modded: {
icon: "plugin",
text: "This exception likely comes from modded code.",
},
harmony: {
icon: "screw-driver",
text: "This exception likely comes from code injected using Harmony, and is NOT a base-game issue.",
extra: () =>
"Possible causes:<br>" +
game.mods
.filter((mod) => mod.tags.has("harmony"))
.map((mod) => span(" - " + mod.name, "hover-mod-name"))
.join("<br>"),
},
};
const ARG_REPLACEMENTS = {
boolean: "bool",
single: "float",
string: "string",
int32: "int",
};
const capitals = ["dll", "json", "id", "gpu", "vram", "hmd"];
const simpleHash = () => {
var hash = 0,
i,
chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = (hash << 5) - hash + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
};
const cyrb64 = (seed = 0) => {
let str = this;
let h1 = 0xdeadbeef ^ seed, h2 = 0x41c6ce57 ^ seed;
for(let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 2654435761);
h2 = Math.imul(h2 ^ ch, 1597334677);
}
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);
h1 ^= Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);
h2 ^= Math.imul(h1 ^ (h1 >>> 13), 3266489909);
// For a single 53-bit numeric return value we could return
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
// but we instead return the full 64-bit value:
// return [h2>>>0, h1>>>0];
};
const cyrb64Hash = (str, seed = 0) => {
const [h2, h1] = cyrb64(str, seed);
return h2.toString(36).padStart(7, '0') + h1.toString(36).padStart(7, '0');
}
const murmurHash = function() {
return new MurmurHash3().hash(this).result();
}
String.prototype.hashCode = murmurHash;
const fileInput = document.querySelector("#file-input");
const fileClickInput = document.getElementById("file-click-input");
const statusDiv = document.getElementById("status")
const progressBar = document.getElementById("progress-bar")
fileInput.addEventListener("dragenter", (_) => {
fileInput.classList.add("dragging");
});
fileInput.addEventListener("dragleave", (_) => {
fileInput.classList.remove("dragging");
});
fileInput.addEventListener("dragover", (e) => {
e.preventDefault();
e.stopPropagation();
});
fileInput.addEventListener("drop", (e) => {
e.preventDefault();
e.stopPropagation();
loadFile(e.dataTransfer.files[0]);
});
fileInput.addEventListener("click", (e) => {
fileClickInput.click();
});
fileClickInput.addEventListener("change", async (e) => {
await loadFile(e.target.files[0]);
});
var lastBreak = Date.now()
let startTime = Date.now();
let parseStart = 0;
let isClicking = false;
let takeABreak = () => new Promise((resolve) => setTimeout(resolve));
async function maybeTakeABreak() {
let date = Date.now();
let delay = ((date - startTime) / 10000) * 100;
if (date - delay > lastBreak) {
lastBreak = Date.now();
await takeABreak();
}
}
async function readFileText(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsText(file);
reader.onload = () => {
resolve(reader.result);
}
});
}
const SPEED = 8;
const SLICE_SIZE = Math.pow(2, (SPEED + 9));
const BATCH_SIZE = 1;
async function readFileLines(file, callback) {
let leftover = "";
let index = 0;
let slices = [];
while (index < file.size) {
let slice = await file.slice(index, index + SLICE_SIZE).text();
slices = slice.replace(/\r/g, "").split("\n");
for (let i = 0; i < slices.length - 1; i++) {
let part = slices[i];
let line = leftover + part;
await callback(line, index, file.size);
leftover = "";
}
leftover = slices[slices.length - 1];
index += SLICE_SIZE;
}
}
async function sleep(duration) {
await new Promise(resolve => setTimeout(() => resolve(), duration))
}
function hideStatus() {
statusDiv.style.display = "none";
}
function setStatus(text) {
statusDiv.style.display = "block";
statusDiv.innerText = text + (text.endsWith('%') ? '' : "...");
}
let isSmooth = true;
function setProgress(amount, force = false) {
if (amount == 0) progressBar.style.opacity = 1;
if (amount == 100) progressBar.style.opacity = 0;
if (force != isSmooth) {
progressBar.style.transition = force ? "none" : "opacity 0.2s ease-in-out";
isSmooth = force;
}
progressBar.style.maxWidth = amount + '%';
}
function cleanup() {
containers.mods.replaceChildren();
containers.details.replaceChildren();
}
function renderFunc(stringOrFunc) {
if (typeof stringOrFunc == "function") {
return stringOrFunc();
}
return stringOrFunc;
}
async function loadFile(file) {
startTime = Date.now();
cleanup();
document.querySelector(".help").style.opacity = 0;
setTimeout(() => {
document.querySelector(".help").style.maxHeight = 0;
document.querySelector(".help").style.marginBottom = 0;
document.querySelector("main").style.maxWidth = "100vw";
document.querySelector("h1").style.display = "none";
document.querySelector("#file-input").style.display = "none";
}, 200);
setProgress(0, true);
// let lines = await readFileText(file);
// lines = lines.replace(/\r\n/g, "\n")
// .split(/\n/)
// .map((line) =>
// line.replace(/^\d+-\d+-\d+T\d+:\d+:\d+\.\d+: [A-Z]+ .+? *: /g, "")
// .replace(/^\d+-\d+-\d+T\d+:\d+:\d+\.\d+ \d+:\d+:\d+.\d+\s+\d+\s+\d+ [A-Z] Unity\s+: /g, "")
// // 2023-11-19T01:45:22.635 INFO UnityEngine.SetupCoroutine.InvokeMoveNext : Load options...
// );
let totalTimeStart = parseStart = Date.now();
setStatus("Parsing log lines")
await parse(file);
startTime = Date.now();
parseStart = Date.now();
setStatus("Sorting mods")
await game.sort();
game.info.sort_time = (Date.now() - parseStart) / 1000;
setStatus("Rendering page")
setProgress(PROGRESS_READ + PROGRESS_FINISH + PROGRESS_SORT);
parseStart = Date.now();
await game.render();
game.info.render_time = (Date.now() - parseStart) / 1000;
hideStatus();
setProgress(100);
game.info.total_time = (Date.now() - totalTimeStart) / 1000;
await clickButton("selector-system-info", false);
}
function getTimestamp(metadata) {
if (metadata.year === undefined) return null;
let {year, month, day, hour, minute, second, ms, level} = metadata;
return code(`${year}-${month}-${day} ${hour}:${minute}${second}.${ms} ${span(level, "color-text-" + level.toLowerCase())}`, "dim")
}
function niceify(string) {
return string
.replace(/^lns_/g, "Logs & Sorcery: ")
.replace(/_/g, " ")
.replace(/(\d+),(\d+)/g, "$1.$2")
.split(" ")
.map((word) =>
capitals.includes(word.toLowerCase())
? word.toUpperCase()
: word[0].toUpperCase() + word.substr(1)
)
.join(" ");
}
function slugify(string) {
return string
.replace(/[_ ]/g, "-")
.replace(/[^\w-]/g, "")
.toLowerCase();
}
function renderValue(value) {
switch (typeof value) {
case "function":
return renderValue(value());
case "string":
if (!isNaN(parseFloat(value)))
return code(value);
return value.match(/^[A-Z]:[\/\\]/) ||
(!value.match(/ /) && value.match(/\./))
? code(value)
: value.replace(/(\d+),(\d+)/g, "$1.$2");
case "object":
if (Array.isArray(value)) {
return value.map(renderValue).join(", ");
}
return code(JSON.stringify(value, undefined, " "));
}
return value;
}
function expandException(elem) {
let error = elem.querySelector(".event-details");
if (error == null) return;
if (!error.classList.contains("event-hidden")) {
error.classList.add("event-hidden");
} else {
error.classList.remove("event-hidden");
}
}
async function clickButton(id, doProgress = true) {
if (isClicking) return;
startTime = Date.now();
containers.details.replaceChildren();
isClicking = true;
if (doProgress)
setProgress(0, true)
await takeABreak();
document
.querySelectorAll("#mod-list > .mod")
.forEach((elem) => elem.classList.remove("selected"));
document.querySelector("#" + id).classList.add("selected");
let target = await game.selectors[id].call(game);
if (doProgress) {
hideStatus();
setProgress(100)
}
isClicking = false;
document.getElementById("search")?.focus();
if (target == null) return;
let text, callback;
if (Array.isArray(target)) {
[text, callback] = target;
} else {
text = target;
}
containers.details.innerHTML = text;
if (callback)
callback();
}
function objectToTable(obj, title, includeEmpty = true, includeZero = true) {
return (
(title ? heading(title) : "") +
'<table class="auto-table">' +
Object.entries(obj)
.map(([key, value]) => {
if (typeof value == "function")
value = value();
return (includeEmpty ||
(value != "" && value != null && value != undefined)) &&
(includeZero || (value != 0 && value != "0"))
? `<tr><td>${niceify(key)}</td><td id="td-${key}">${renderValue(value)}</td></tr>`
: ""}
)
.join("") +
"</table>"
);
}
function objectListToTable(list, keys, title, note) {
if (!list || list.length == 0) return "";
keys ??= list.length > 0 ? [...Object.keys(list[0])] : [];
return (
(title ? heading(title) : "") +
(note ? `<p class="dim italic">${note}</p>` : "") +
'<table class="auto-table">' +
`<tr>${keys.map((key) => `<th>${niceify(key)}</th>`).join("")}</tr>` +
list
.map(
(obj) =>
`<tr>${keys
.map((key) => `<td>${renderValue(obj[key])}</td>`)
.join("")}</tr>`
)
.join("") +
"</table>"
);
}
function heading(text, level = 2, className = undefined) {
return `<h${level}${className ? ' class="' + className + '"' : ""}>${text}</h${level}>`;
}
function modCertainty(score) {
if (score == 0) return "certain";
if (score <= 0.15) return "sure";
if (score <= 0.5) return "likely";
return "unsure";
}
function modCertaintyIcon(score) {
if (score == 0) return '<i class="indent icofont-ui-rating"></i>';
if (score <= 0.15) return '<i class="indent icofont-check"></i>';
if (score <= 0.5) return '<i class="indent icofont-question"></i>';
return '<i class="indent icofont-ui-close"></i>';
}
function getReason(reason, score) {
return REASONS[reason].replace("[[score]]", Math.round(score * 100) / 100) ?? "";
}
function getCertainty(score) {
return CERTAINTY[modCertainty(score)] ?? "";
}
async function searchBar(container) {
let search = createElement("input", "search", {
id: "search",
type: "text",
placeholder: "search...",
oninput: (evt) => updateSearch(container, evt.target.value),
});
return search;
}
let currentQuery = "";
async function updateSearch(container, search) {
currentQuery = search;
let queries = search.toLowerCase().split(" ");
startTime = Date.now();
setProgress(0, true);
await takeABreak();
const children = container.children;
for (let i = 0; i < children.length; i++) {
if (search != currentQuery) return;
let child = children[i];
if (
search == "" ||
queries.every((query) => child.dataset.keywords?.match(query))
) {
child.classList.remove("search-hidden");
} else {
child.classList.add("search-hidden");
}
setProgress((i / children.length) * 100);
await maybeTakeABreak();
}
setProgress(100);
}
function screenshot(event, element, title) {
event.preventDefault();
event.stopPropagation();
if (element.querySelector(".event-hidden")) {
expandException(element);
}
html2canvas(element
// , {
// ignoreElements: element => {
// try {
// element.style.transition = "";
// } catch {}
// return true;
// }
//}
).then((canvas) => {
canvas.toBlob(function (blob) {
saveAs(blob, `${title}.png`);
});
});
}
function code(string, className) {
if (string.startsWith("<code>")) return string;
return `<code${className ? ' class="' + className + '"' : ""}>${string}</code>`;
}
function italic(string) {
return `<span class="italic">${string}</span>`;
}
function bold(string) {
return `<strong>${string}</strong>`;
}
function safe(unsafe) {
return unsafe.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"').replaceAll("'", ''');
}
function icon(name, tooltip, color) {
return `<i class="pad icofont-${name}"${
color ? ` style="color: ${color}` : ""
}">${tooltip ? `<p>${tooltip}</p>` : ""}</i>`;
}
function hr() {
return '<div class="hsep"></div>';
}
let createHR = () => createDiv("hsep");
function createElement(tag, classes, args, contents) {
let element = document.createElement(tag);
if (classes) {
for (let eachClass of classes.split(" ")) {
element.classList.add(eachClass);
}
}
if (args) {
if (args.id) element.id = args.id;
if (args.onclick) element.onclick = args.onclick;
if (args.oninput) element.oninput = args.oninput;
if (args.type) element.setAttribute("type", args.type);
if (args.placeholder) element.setAttribute("placeholder", args.placeholder);
}
if (contents != null && contents != undefined) {
if (Array.isArray(contents)) {
element.replaceChildren(...contents.filter(content => content));
} else {
element.replaceChildren(contents);
}
}
return element;
}
function newElement(content) {
const parent = document.createElement("div");
parent.innerHTML = content;
return parent.firstChild;
}
function createIcon(icon, classes) {
return createElement("i", ["icofont-" + icon, ...classes.split(" ")].join(" "))
}
function createSpan(classes, args, contents) {
return createElement("span", classes, args, contents);
}
function createDiv(classes, args, contents){
return createElement("div", classes, args, contents);
}
function div(string, className) {
return `<div${className ? ' class="' + className + '"' : ""}>${string ?? ""}</div>`;
}
function pre(string, className) {
return `<pre${className ? ' class="' + className + '"' : ""}>${string ?? ""}</pre>`;
}
function p(string, className) {
return `<p${className ? ' class="' + className + '"' : ""}>${string}</p>`;
}
function span(string, className, params, style) {
return `<span${
className ? ' class="' + className + '"' : ""
}${
style ? ' style="' + style + '"' : ""
}${
params ? Object.entries(params).map(([key, value]) => `${key}="${value}"`).join(" ") : ""
}>${string}</span>`;
}
function emph(string) {
return `<em>${string}</em>`;
}
function li(string) {
return `<li>${string}</li>`;
}
function ul(elements) {
return `<ul>${elements.map(li).join("")}</ul>`;
}
function wrapDetails(title, contents, description) {
return `<div class="pad">
${heading(title)}
${description ? p(description) : ""}
${contents}
</div>`;
}
function replaceNamespaces(namespace) {
return COMMON_NAMESPACES[namespace] ?? namespace;
}
function loadTimings() {
let labels = [];
let data = [];
for (const [key, value] of Object.entries(game.timing)) {
labels.push(key);
data.push(value);
}
(async function () {
new Chart(document.getElementById('timing'), {
type: "doughnut",
label: "Load times",
data: {
labels: labels,
datasets: [
{
data: data,
},
],
},
});
})();
}
function foundMod(found, score, reason) {
return {found, score, reason};
}
async function renderListOfEvents(container, list, title) {
container.replaceChildren();
let length = list.length;
const heading = createElement("h2", "search-title", undefined, title);
container.appendChild(heading);
const parent = createElement("div");
container.lastChild.appendChild(await searchBar(parent));
container.appendChild(parent);
for (let i = 0; i < length; i++) {
const div = document.createElement("div");
div.innerHTML = list[i].render();
parent.appendChild(div.firstChild);
div.remove();
setProgress(i / length * 100)
await maybeTakeABreak();
}
}
class Game {
constructor() {
this.startMetadata = {};
this.metadata = undefined;
this.lastMetadata = undefined;
this.currentCount = 0;
this.maxCount = 0;
this.timing = {}
this.mods = [];
this.areas = [];
this.missingDamagers = {};
this.inventories = {};
this.lastLevel = "";
this.baseGame = null;
this.exceptions = [];
this.timeline = [];
this.missingData = [];
this.loadErrors = [];
this.selectors = {};
this.system = { game_directory: null, platform: null };
this.info = {};
this.suggestions = {};
this.levels = []
this.incompatibleMods = [];
this.begun = false;
this.lastEvent = null;
this.lastSeed = 0;
this.lastException = null;
}
findOrCreateMod(name, folder) {
let {found, score, reason} = this.findModByName(name) ?? this.findModByFolder(folder);
if (found) {
if (folder && found.name == found.folder)
found.folder = folder;
return {found, score, reason};
}
let mod = new Mod(name, folder ?? name);
game.mods.push(mod);
return foundMod(mod, 0, "create");
}
findModByName(name) {
let found = this.mods.filter((mod) => mod.name == name);
if (found.length > 0) return foundMod(found[0], 0, "name");
return foundMod();
}
findModByCatalog(catalog) {
let found = this.mods.filter((mod) => mod.catalogs.filter(each => each.catalog.toLowerCase() == `catalog_${catalog.toLowerCase()}.json`).length > 0);
if (found.length > 0) return foundMod(found[0], 0, "catalog");
return foundMod();
}
findModByFolder(folder) {
let found = this.mods.filter((mod) => mod.folder == folder);
if (found.length > 0) return foundMod(found[0], 0, "folder");
return foundMod();
}
findModByNamespace(namespace) {
let found = this.mods.filter(
(mod) =>
Array.from(mod.namespaces).filter(
(each) => each.toLowerCase() == namespace.toLowerCase()
).length > 0
);
if (found.length > 0) return foundMod(found[0], 0, "namespace");
return foundMod();
}
findModByAssembly(assembly) {
let found = this.mods.filter(
(mod) =>
mod.assemblies.filter(
(eachAssembly) => eachAssembly.dll.toLowerCase() == assembly.toLowerCase() + ".dll"
).length > 0
);
if (found.length > 0) return foundMod(found[0], 0, "assembly");
return foundMod();
}
fuzzyFindMod(mod) {
mod = replaceNamespaces(mod.replace(/^Spell/, ""));
if (!game.modFinder)
this.updateModFinder();
let search = game.modFinder.search(mod);
if (search.length > 0) {
return foundMod(search[0].item, search[0].score, "fuzzy");
}
return foundMod();
}
findModByData(id, address) {
if (address.startsWith("Bas.")) return foundMod(game.baseGame, 0, "base_game");
if (address.split(".").length >= 3) {
let [author, mod, ...data] = address.split(".");
if (id.split(".").length > 1) {
id = id.split(".")[id.split(".").length - 1];
}
let results = this.modFinder.search(`'"${mod}"|'"${author}"`);
if (results.length > 0 && results[0].score < 0.2) {
return foundMod(results[0].item, results[0].score, "address");
}
results = this.dataFinder.search(`'"${mod}" '"${author}" '"${id}"`);
if (results.length > 0 && results[0].score < 0.2) {
return this.findModByFolder(results[0].item.folder);
}
}
if (id.split(".").length > 1) {
id = id.split(".")[id.split(".").length - 1];
}
let data = this.dataFinder.search(id);
if (data.length > 0) {
return this.findModByFolder(data[0].item.folder);
}
return foundMod();
}
updateModFinder() {
this.modFinder = new Fuse(this.mods, {
keys: ["assemblies", "name", "folder", "author"],
includeScore: true,
useExtendedSearch: true,
});
}
begin() {
if (this.begun) return;
if (this.system.platform === null) {
this.system.platform =
icon("warning", undefined, "color-warning") + "Unknown - Pirated?";
this.addSuggestion("pirated");
}
this.baseGame = new Mod("Base Game", "N/A");
this.begun = true;
this.updateModFinder();
this.dataFinder = new Fuse(
this.mods.flatMap((mod) =>
mod.json.map((json) => {
return {
name: json.file,
authorFolder: mod.author + "." + mod.folder,
folder: mod.folder,
};
})
),
{
keys: ["authorFolder", "author", "folder", "name"],
includeScore: true,
useExtendedSearch: true,
}
);
}
async incrementProgress(count = 1) {
this.currentCount += count;
setProgress(PROGRESS_READ + this.currentCount / this.maxCount * PROGRESS_FINISH)
await maybeTakeABreak();
}
async finish() {
this.system.installed_mods = this.mods.length;
if (this.startMetadata) {
let {year, month, day, hour, minute, second, ms, level} = this.startMetadata;
this.system.start_time = new Date(year, month, day, hour, minute, second, ms).toString();
}
containers.mods.replaceChildren([]);
containers.mods.appendChild(this.selector("System Info", this.renderGameInfo));
this.maxCount =
this.exceptions.length +
this.mods.length + 1 +
this.timeline.length +
Object.keys(this.suggestions).length +
this.missingData.length;
setStatus(`Processing ${this.exceptions.length} unique exceptions`)
for (const exception of this.exceptions) {
exception.complete()
await this.incrementProgress();
}
setStatus(`Processing base game issues`)
await game.baseGame.complete();
setStatus(`Processing ${this.mods.length} mods`)
let i = 0;
for (const mod of this.mods) {
await mod.complete()
await this.incrementProgress();
}
setStatus(`Collapsing ${[...Object.keys(this.suggestions)].length} suggestions`)
await this.collapseSuggestions();
containers.mods.appendChild(
this.selector(
"Suggestions",
this.renderSuggestions,
[...Object.keys(this.suggestions)].length
)
);
containers.mods.appendChild(
this.selector("Timeline", this.renderTimeline, this.timeline.length)
);
if (this.areas.length > 0) {
containers.mods.appendChild(
this.selector("Areas", this.renderAreaList, this.areas.map(list => list.length - 2).reduce(reduceNumber, 0))
);
}
if (Object.keys(this.inventories).length > 0) {
containers.mods.appendChild(
this.selector("Inventories", this.renderInventories, Object.values(this.inventories).map(list => list.length).reduce(reduceNumber, 0))
);
}
if (Object.keys(this.missingDamagers).length > 0) {
containers.mods.appendChild(
this.selector("Missing Damagers", this.renderMissingDamagers, Object.values(this.missingDamagers).reduce((acc, group) => acc + Array.from(group).length, 0))
);
}
if (this.loadErrors.length > 0) {
containers.mods.appendChild(
this.selector("Unknown Load Errors", this.renderLoadErrors, this.loadErrors.length)
);
}
setStatus(`Matching ${this.missingData.length} missing data entries with mods`)
for (let data of this.missingData) {
let {mod, score, reason} = game.findModByData(data.id, data.address) ?? []
mod?.missingData.push({
address: data.address,
id: data.id,
type: data.type,
});
await this.incrementProgress();
}
}
async sort() {
this.mods
.sort((a, b) =>
a.name.toLowerCase() < b.name.toLowerCase()
? -1
: a.name.toLowerCase() > b.name.toLowerCase()
? 1
: 0
)
.reverse();
await maybeTakeABreak();