forked from Quiaaaa/AutoTrimps
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraphs.js
908 lines (852 loc) · 35.4 KB
/
Graphs.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
function safeLocalStorage(name, data) {
try {
if (name === "portalDataCurrent") {
// save at most every 450ms. Stringify is too expensive to run at max speed in timewarp, but still save every zone in liq otherwise
if ((new Date() - lastSave) / 450 < 1) return
else lastSave = new Date();
}
if (typeof data != "string") data = JSON.stringify(data);
localStorage.setItem(name, data);
} catch (e) {
if (e.code == 22 || e.code == 1014) { //
// Storage full, delete oldest portal from history, and try again
delete portalSaveData[Object.keys(portalSaveData)[0]];
savePortalData(true);
safeLocalStorage(name, data)
console.debug("AT Graphs Error: LocalStorage is full. Automatically deleting a graph to clear up space.", e.code, e);
}
}
}
// Save Portal Data to history, or current only
function savePortalData(saveAll = true) {
var currentPortal = getportalID();
if (saveAll) {
safeLocalStorage("portalDataHistory", LZString.compressToBase64(JSON.stringify(portalSaveData)))
}
else {
let portalObj = {}
portalObj[currentPortal] = portalSaveData[currentPortal];
safeLocalStorage("portalDataCurrent", portalObj)
}
}
// Save settings, with or without updating a key
function saveSetting(key, value) {
if (key !== null && value !== null) GRAPHSETTINGS[key] = value;
safeLocalStorage("GRAPHSETTINGS", GRAPHSETTINGS);
}
// Create all of the UI elements and load in scripts needed
// TODO reduce screaming
function init() {
var head = document.getElementsByTagName("head")[0]
var chartscript = document.createElement("script");
chartscript.type = "text/javascript";
chartscript.src = "https://code.highcharts.com/highcharts.js";
head.appendChild(chartscript);
var graphsButton = document.createElement("TD");
graphsButton.appendChild(document.createTextNode("Graphs"))
graphsButton.setAttribute("class", "btn btn-default")
graphsButton.setAttribute("onclick", "autoToggleGraph(); drawGraph(); swapGraphUniverse();");
var settingbarRow = document.getElementById("settingsTable").firstElementChild.firstElementChild;
settingbarRow.insertBefore(graphsButton, settingbarRow.childNodes[10])
document.getElementById("settingsRow").innerHTML += `
<div id="graphParent" style="display: none; height: 600px; overflow: auto; position: relative;">
<div id="graph" style="margin-bottom: 10px;margin-top: 5px; height: 530px;"></div>
<div id="graphFooter" style="height: 50px;font-size: 1em;">
<div id="graphFooterLine1" style="display: -webkit-flex;flex: 0.75;flex-direction: row; height:30px;"></div>
<div id="graphFooterLine2"></div>
</div>
</div>
`;
function createSelector(id, sourceList, textMod = "", onchangeMod = "") {
let selector = document.createElement("select");
selector.id = id;
selector.setAttribute("style", "");
selector.setAttribute("onchange", "saveSetting(this.id, this.value); drawGraph();" + onchangeMod);
for (var item of sourceList) {
let opt = document.createElement("option");
opt.value = item;
opt.text = textMod + item;
selector.appendChild(opt);
}
selector.value = GRAPHSETTINGS[selector.id]
return selector;
}
// Create Universe and Graph selectors
var universeFooter = document.getElementById("graphFooterLine1");
[
["universeSelection", [1, 2], "Universe ", " swapGraphUniverse();"],
["u1graphSelection", graphList.filter((g) => g.universe == 1 || !g.universe).map((g) => g.selectorText)],
["u2graphSelection", graphList.filter((g) => g.universe == 2 || !g.universe).map((g) => g.selectorText)]
].forEach((opts) => universeFooter.appendChild(createSelector(...opts)))
universeFooter.innerHTML += `
<div><button onclick="drawGraph()" style="margin-left:0.5em;">Refresh</button></div>
<div style="flex:0 100 5%;"></div>
<div><input type="checkbox" id="clrChkbox" onclick="toggleClearButton();"></div>
<div style="margin-left: 0.5vw;">
<button id="clrAllDataBtn" onclick="clearData(null,true); drawGraph();" class="btn" disabled="" style="flex:auto; padding: 2px 6px;border: 1px solid white;">
Clear All Previous Data</button></div>
<div style="flex:0 100 5%;"></div>
<div style="flex:0 2 3.5vw;"><input style="width:100%;min-width: 40px;" id="deleteSpecificTextBox"></div>
<div style="flex:auto; margin-left: 0.5vw;"><button onclick="deleteSpecific(); drawGraph();">Delete Specific Portal</button></div>
<div style="float:right; margin-right: 0.5vw;"><button onclick="toggleSpecificGraphs()">Invert Selection</button></div>
<div style="float:right; margin-right: 1vw;"><button onclick="toggleAllGraphs()">All Off/On</button></div>`
// AAAAAAAAAAAAAAAAAAAAAAAAAAAA (Setting the inner HTML of the parent element resets the value of these? what the fuck)
document.querySelector("#universeSelection").value = GRAPHSETTINGS.universeSelection
document.querySelector("#u1graphSelection").value = GRAPHSETTINGS.u1graphSelection
document.querySelector("#u2graphSelection").value = GRAPHSETTINGS.u2graphSelection
let tipsText = "You can zoom by dragging a box around an area. You can turn portals off by clicking them on the legend. Quickly view the last portal by clicking it off, then Invert Selection. Or by clicking All Off, then clicking the portal on. To delete a portal, Type its portal number in the box and press Delete Specific. Using negative numbers in the Delete Specific box will KEEP that many portals (starting counting backwards from the current one), ie: if you have Portals 1000-1015, typing -10 will keep 1005-1015."
document.getElementById("graphFooterLine2").innerHTML += `
<span style="float: left;" onmouseover='tooltip("Tips", "customText", event, "${tipsText}")' onmouseout='tooltip("hide")'>Tips: Hover for usage tips.</span>
<input onclick="toggleDarkGraphs()" style="height: 20px; float: right; margin-right: 0.5vw;" type="checkbox" id="blackCB">
<span style="float: right; margin-right: 0.5vw;">Black Graphs:</span>
`;
// Add a header with negative float hanging down on the top of the graph, for toggle buttons
var toggleDiv = document.createElement("div");
toggleDiv.id = "toggleDiv";
toggleDiv.setAttribute("style", "position: absolute; top: 1rem; left: 3rem; z-index: 1;")
toggleDiv.innerText = ""
document.querySelector("#graphParent").appendChild(toggleDiv);
// Handle Dark Graphs? Old code
MODULES.graphs.themeChanged = function () {
if (game && game.options.menu.darkTheme.enabled != lastTheme) {
function f(h) {
h.style.color = 2 == game.options.menu.darkTheme.enabled ? "" : "black";
}
function g(h) {
if ("graphSelection" == h.id) return void (2 != game.options.menu.darkTheme.enabled && (h.style.color = "black"));
}
toggleDarkGraphs();
var c = document.getElementsByTagName("input");
var d = document.getElementsByTagName("select");
var e = document.getElementById("graphFooterLine1").children;
for (let h of c) f(h);
for (let h of d) f(h);
for (let h of e) f(h);
for (let h of e) g(h);
}
game && (lastTheme = game.options.menu.darkTheme.enabled);
}
MODULES.graphs.themeChanged();
document.querySelector("#blackCB").checked = GRAPHSETTINGS.darkTheme
}
// Graph constructor
function Graph(dataVar, universe, selectorText, additionalParams = {}) {
// graphTitle, customFunction, useAccumulator, xTitle, yTitle, formatter, xminFloor, yminFloor, yType
this.dataVar = dataVar
this.universe = universe; // false, 1, 2
this.selectorText = selectorText ? selectorText : dataVar;
this.id = selectorText.replace(/ /g, "_")
this.graphTitle = this.selectorText;
this.graphType = "line"
this.customFunction;
this.useAccumulator;
this.xTitle = "Zone";
this.yTitle = this.selectorText;
this.formatter;
this.xminFloor = 1;
this.yminFloor;
this.yType = "Linear";
this.graphData = [];
this.typeCheck = "number"
this.conditional = () => { return true };
for (const [key, value] of Object.entries(additionalParams)) {
this[key] = value;
}
this.baseGraphTitle = this.graphTitle;
// create an object to pass to Highcharts.Chart
this.createHighChartsObj = function () {
// TODO BUGS Max values sometimes clip
return {
chart: {
renderTo: "graph",
zoomType: "xy",
resetZoomButton: {
position: {
align: "right",
verticalAlign: "top",
x: -20,
y: 15,
},
relativeTo: "chart",
},
},
colors: ["#e60049", "#0bb4ff", "#50e991", "#e6d800", "#9b19f5", "#ffa300", "#dc0ab4", "#b3d4ff", "#00bfa0"],
title: {
text: this.graphTitle,
x: -20,
},
plotOptions: {
series: {
lineWidth: 1,
animation: false,
marker: {
enabled: false,
},
},
},
xAxis: {
floor: this.xminFloor,
title: {
text: this.xTitle,
},
},
yAxis: {
floor: this.yminFloor,
title: {
text: this.yTitle,
},
plotLines: [
{
value: 0,
width: 1,
color: "#808080",
},
],
type: this.yType,
labels: {
formatter: function () {
// These are Trimps format functions for durations(modified) and numbers, respectively
if (this.dateTimeLabelFormat) return formatDuration(this.value / 1000)
else return prettify(this.value);
}
}
},
tooltip: {
pointFormatter: this.formatter,
},
legend: {
layout: "vertical",
align: "right",
verticalAlign: "middle",
borderWidth: 0,
},
series: this.graphData,
additionalParams: {},
}
}
// Main Graphing function
this.updateGraph = function () {
if (this.graphType == "line") this.lineGraph();
if (this.graphType == "column") this.columnGraph();
this.formatter = this.formatter
|| function () {
var ser = this.series; // 'this' being the highcharts object that uses formatter()
return '<span style="color:' + ser.color + '" >●</span> ' + ser.name + ": <b>" + prettify(this.y) + "</b><br>";
};
saveSelectedGraphs();
chart1 = new Highcharts.Chart(this.createHighChartsObj());
applyRememberedSelections();
}
// prepares data series for Highcharts, and optionally transforms it with toggled options, customFunction and/or useAccumulator
this.lineGraph = function () {
var item = this.dataVar;
this.graphData = [];
this.graphTitle = this.baseGraphTitle;
this.yTitle = this.selectorText;
var maxS3 = Math.max(...Object.values(portalSaveData).map((portal) => portal.s3).filter((s3) => s3));
var activeToggles = [];
if (this.toggles) {
// create save space for the toggles if they don't exist
if (GRAPHSETTINGS.toggles[this.id] === undefined) { GRAPHSETTINGS.toggles[this.id] = {} }
this.toggles.forEach((toggle) => {
if (GRAPHSETTINGS.toggles[this.id][toggle] === undefined) { GRAPHSETTINGS.toggles[this.id][toggle] = false }
})
activeToggles = this.toggles.filter(toggle => GRAPHSETTINGS.toggles[this.id][toggle])
// change the graph title per toggle
if (activeToggles.includes("perZone")) { this.graphTitle += " this Zone" }
if (activeToggles.includes("perHr")) { this.graphTitle += " / Hour" }
if (activeToggles.includes("lifetime")) { this.graphTitle += " % of Lifetime Total"; this.yTitle += " % of lifetime" }
if (activeToggles.includes("s3normalized")) { this.graphTitle += `, Normalized to z${maxS3} S3` }
}
// parse data per portal
for (const portal of Object.values(portalSaveData)) {
if (!(item in portal.perZoneData)) continue; // ignore blank
if (portal.universe != GRAPHSETTINGS.universeSelection) continue; // ignore inactive universe
let cleanData = [];
// parse the requested datavar
for (const index in portal.perZoneData[item]) {
let x = portal.perZoneData[item][index];
let time = portal.perZoneData.currentTime[index];
if (typeof this.customFunction === "function") {
x = this.customFunction(portal, index);
if (x < 0) x = null;
}
// TOGGLES
// Apply the toggled functions to the data. Order matters.
if (activeToggles.includes("perZone")) {
time = portal.perZoneData.zoneTime[index]
if (index > 1) {
x = portal.perZoneData[item][index] - portal.perZoneData[item][index - 1]
}
}
if (activeToggles.includes("lifetime")) {
let initial;
if (item === "heliumOwned") { initial = portal.totalHelium; }
if (item === "radonOwned") { initial = portal.totalRadon; }
if (item === "c23increase") { initial = portal.cinf; }
if (!initial) {
debug("Attempted to calc lifetime percent of an unknown type:" + item);
continue;
}
if (item === "c23increase") {
let totalBonus = (1 + (initial[1] / 100)) * initial[0]; // calc initial cinf
let c2 = initial[0];
let c3 = initial[1];
portal.universe == 1 ? c2 += x : c3 += x;
let newBonus = (1 + (c3 / 100)) * c2; // calc final cinf
x = ((newBonus - totalBonus) / (totalBonus ? totalBonus : 1));
}
else { x = x / (initial ? initial : 1) }
}
if (activeToggles.includes("perHr")) {
x = x / (time / 3600000)
}
if (activeToggles.includes("s3normalized")) {
x = x / 1.03 ** portal.s3 * 1.03 ** maxS3
}
if (this.useAccumulator) x += cleanData.at(-1) !== undefined ? cleanData.at(-1)[1] : 0; // never used, leaving it in just in case
if (this.typeCheck && typeof x != this.typeCheck) x = null;
cleanData.push([Number(index), x]) // highcharts expects number, number, not str, number
}
if (activeToggles.includes("perZone")) {
cleanData.splice(cleanData.length - 1); // current zone is too erratic to include due to weird order of granting resources in Trimps
}
this.graphData.push({
name: `Portal ${portal.totalPortals}: ${portal.challenge}`,
data: cleanData,
})
}
}
// prepares column data series from per-portal data
this.columnGraph = function () {
var item = this.portalVar;
this.xTitle = "Portal"
this.graphData = [];
let cleanData = []
// future use: test for datavar in portal, or in perZoneData, if you ever want to make column graphs based on max(perZoneData)
for (const portal of Object.values(portalSaveData)) {
if (portal.universe == GRAPHSETTINGS.universeSelection) {
cleanData.push([portal.totalPortals, portal[item]])
}
}
this.graphData.push({
name: this.yTitle,
data: cleanData,
type: "column",
});
}
}
// returns _d _h _m _s or _._s
function formatDuration(timeSince) {
let timeObj = {
d: Math.floor(timeSince / 86400),
h: Math.floor(timeSince / 3600) % 24,
m: Math.floor(timeSince / 60) % 60,
s: Math.floor(timeSince % 60),
}
let milliseconds = Math.floor(timeSince % 1 * 10)
let timeString = "";
let unitsUsed = 0
for (const [unit, value] of Object.entries(timeObj)) {
if (value === 0 && timeString === "") continue;
unitsUsed++;
if (value) timeString += value.toString() + unit + " ";
}
if (unitsUsed <= 1) {
timeString = [timeObj.s.toString().padStart(1, "0"), milliseconds.toString(), "s"].join(".");
}
return timeString
}
// Show/hide the universe-specific graph selectors
function swapGraphUniverse() {
let universe = GRAPHSETTINGS.universeSelection;
let active = `u${universe}`
let inactive = `u${universe == 1 ? 2 : 1}`
document.getElementById(`${active}graphSelection`).style.display = '';
document.getElementById(`${inactive}graphSelection`).style.display = 'none';
}
// Draws the graph currently selected by the user
function drawGraph() {
function lookupGraph(selectorText) {
for (const graph of graphList) {
if (graph.selectorText === selectorText) return graph;
}
}
// TOGGLES
function makeCheckbox(graph, toggle) {
// create checkbox element labeled with the toggle
var container = document.createElement("span")
var checkbox = document.createElement("input");
var label = document.createElement("span");
container.style.padding = "0rem .5rem";
checkbox.type = "checkbox";
checkbox.id = toggle;
// initialize the checkbox to saved value
checkbox.checked = GRAPHSETTINGS.toggles[graph][toggle];
// set saved value on change, and update the graph
checkbox.setAttribute("onclick", `GRAPHSETTINGS.toggles.${graph}.${toggle} = this.checked; drawGraph();`);
label.innerText = toggle;
label.style.color = "#757575";
container.appendChild(checkbox)
container.appendChild(label)
return container;
}
pushData(); // update current zone data on request
let universe = GRAPHSETTINGS.universeSelection;
let selectedGraph = document.getElementById(`u${universe}graphSelection`);
if (selectedGraph.value) {
// draw the graph
let graph = lookupGraph(selectedGraph.value);
graph.updateGraph();
// create toggle elements
toggleDiv = document.querySelector("#toggleDiv")
toggleDiv.innerHTML = "";
if (graph.toggles) {
for (const toggle of graph.toggles) {
toggleDiv.appendChild(makeCheckbox(graph.id, toggle))
}
}
}
showHideUnusedGraphs();
}
// Stores and updates data for an individual portal
function Portal() {
this.universe = getGameData.universe();
this.totalPortals = getTotalPortals();
this.challenge = getGameData.challengeActive() === 'Daily'
? getCurrentChallengePane().split('.')[0].substr(13).slice(0, 16) // names dailies by their start date, only moderately cursed
: getGameData.challengeActive();
this.totalNullifium = getGameData.nullifium();
this.totalVoidMaps = getGameData.totalVoids();
this.cinf = getGameData.cinf();
if (this.universe === 1) {
this.totalHelium = game.global.totalHeliumEarned;
this.initialFluffy = getGameData.fluffy();
this.initialDE = getGameData.essence();
}
if (this.universe === 2) {
this.totalRadon = game.global.totalRadonEarned;
this.initialScruffy = getGameData.scruffy();
this.s3 = getGameData.s3();
}
// create an object to collect only the relevant data per zone, without fromEntries because old JS
this.perZoneData = {};
var perZoneItems = graphList.filter((graph) =>
(graph.universe == this.universe || !graph.universe) // only save data relevant to the current universe
&& graph.conditional() && graph.dataVar) // and for relevant challenges, with datavars
.map((graph) => graph.dataVar)
.concat(["currentTime"]); // always graph time
perZoneItems.forEach((name) => this.perZoneData[name] = []);
// update per zone data and special totals
this.update = function () {
const world = getGameData.world();
// TODO Nu is a rather fragile stat, assumes recycling everything on portal. Max throughout the run makes it slightly less crappy.
// It would be better to store an initial value, and compare to final value + recycle value
this.totalNullifium = Math.max(this.totalNullifium, getGameData.nullifium());
this.totalVoidMaps = getGameData.totalVoids();
for (const [name, data] of Object.entries(this.perZoneData)) {
data[world] = getGameData[name]();
if (world + 1 < data.length) { // FENCEPOSTING
data.splice(world + 1) // trim 'future' zones on reload
}
}
}
}
function clearData(keepN, clrall = false) {
let currentPortalNumber = getTotalPortals();
if (clrall) {
for (const [portalID, portalData] of Object.entries(portalSaveData)) {
if (portalData.totalPortals != currentPortalNumber) {
delete portalSaveData[portalID];
}
}
} else {
let totalSaved = Object.keys(portalSaveData).length;
for (const [portalID, portalData] of Object.entries(portalSaveData)) {
if (totalSaved > keepN && portalData.totalPortals <= currentPortalNumber - keepN) {
delete portalSaveData[portalID];
totalSaved--;
}
}
}
savePortalData(true)
showHideUnusedGraphs();
}
function deleteSpecific() {
let portalNum = Number(document.getElementById("deleteSpecificTextBox").value);
if (parseInt(portalNum) < 0) { clearData(Math.abs(portalNum)); }
else {
for (const [portalID, portalData] of Object.entries(portalSaveData)) {
if (portalData.totalPortals === portalNum) delete portalSaveData[portalID];
}
}
savePortalData(true)
showHideUnusedGraphs();
}
// ####### Here begins old code
function toggleClearButton() {
document.getElementById("clrAllDataBtn").disabled = !document.getElementById("clrChkbox").checked;
}
function toggleDarkGraphs() {
function removeDarkGraphs() {
var darkcss = document.getElementById("dark-graph.css");
darkcss && (document.head.removeChild(darkcss), debug("Removing dark-graph.css file", "graphs"));
}
function addDarkGraphs() {
var darkcss = document.getElementById("dark-graph.css");
if (!darkcss) {
var b = document.createElement("link");
(b.rel = "stylesheet"), (b.type = "text/css"), (b.id = "dark-graph.css"), (b.href = basepath + "dark-graph.css"), document.head.appendChild(b), debug("Adding dark-graph.css file", "graphs");
}
}
if (game) {
var darkcss = document.getElementById("dark-graph.css")
var dark = document.getElementById("blackCB").checked;
saveSetting("darkTheme", dark)
if ((!darkcss && (0 == game.options.menu.darkTheme.enabled || 2 == game.options.menu.darkTheme.enabled)) || MODULES.graphs.useDarkAlways || dark) {
addDarkGraphs()
}
else {
if (darkcss && (1 == game.options.menu.darkTheme.enabled || 3 == game.options.menu.darkTheme.enabled || !dark)) {
removeDarkGraphs();
}
}
}
}
// ####### end scary old code
// Graph Selection
function saveSelectedGraphs() {
if (!chart1) return;
for (let i = 0; i < chart1.series.length; i++) {
GRAPHSETTINGS.rememberSelected[i] = chart1.series[i].visible;
}
saveSetting();
}
function applyRememberedSelections() {
if (chart1.series.length < GRAPHSETTINGS.rememberSelected.length) {
GRAPHSETTINGS.rememberSelected.splice(chart1.series.length); // cleanup after portal deletion
}
for (let i = 0; i < chart1.series.length; i++) {
if (GRAPHSETTINGS.rememberSelected[i] === false) { chart1.series[i].hide(); }
}
}
function toggleSpecificGraphs() {
for (const chart of chart1.series) {
chart.visible ? chart.hide() : chart.show();
}
}
// toggle all graphs to the opposite of the average visible/hidden state
function toggleAllGraphs() {
let visCount = 0;
chart1.series.forEach(chart => visCount += chart.visible)
for (const chart of chart1.series) {
visCount > chart1.series.length / 2 ? chart.hide() : chart.show();
}
}
// show graph window
function autoToggleGraph() {
if (game.options.displayed) {
toggleSettingsMenu();
}
var autoSettings = document.getElementById("autoSettings");
if (autoSettings && autoSettings.style.display === "block") {
autoSettings.style.display = "none";
}
var ATMenu = document.getElementById("autoTrimpsTabBarMenu");
if (ATMenu && ATMenu.style.display === "block") {
ATMenu.style.display = "none";
}
var graphParent = document.getElementById("graphParent");
if ("block" === graphParent.style.display) {
graphParent.style.display = "none";
}
else {
graphParent.style.display = "block";
document.getElementById("deleteSpecificTextBox").focus()
}
}
// focus main game
function escapeATWindows() {
var a = document.getElementById("tooltipDiv");
if ("none" != a.style.display) return void cancelTooltip();
game.options.displayed && toggleSettingsMenu();
var b = document.getElementById("autoSettings");
"block" === b.style.display && (b.style.display = "none");
var b = document.getElementById("autoTrimpsTabBarMenu");
"block" === b.style.display && (b.style.display = "none");
var c = document.getElementById("graphParent");
"block" === c.style.display && (c.style.display = "none");
}
document.addEventListener(
"keydown",
function (a) {
1 != game.options.menu.hotkeys.enabled || game.global.preMapsActive || game.global.lockTooltip
|| ctrlPressed || heirloomsShown || 27 != a.keyCode || escapeATWindows();
if (["1", "2", "3", "4", "5"].includes(a.key)) {
//a.stopPropagation() // does not work, whee
}
},
true
);
function getportalID() { return `u${getGameData.universe()} p${getTotalPortals()}` }
function pushData() {
//debug("Starting Zone " + getGameData.world(), "graphs");
const portalID = getportalID();
if (!portalSaveData[portalID] || getGameData.world() === 1) { // reset portal data if restarting a portal
savePortalData(true) // save old portal to history
portalSaveData[portalID] = new Portal();
}
portalSaveData[portalID].update();
clearData(GRAPHSETTINGS.maxGraphs);
savePortalData(false) // save current portal
}
// Hide graphs that have no collected data
function showHideUnusedGraphs() {
let activeUniverses = [];
for (const graph of graphList) {
if (graph.graphType != "line") continue; // ignore column graphs (pure laziness, the only two always exist anyways)
const universes = graph.universe ? [graph.universe] : [1, 2]
for (const universe of universes) {
let style = "none"
for (portal of Object.values(portalSaveData)) {
if (portal.perZoneData[graph.dataVar] && portal.universe === universe // has collected data, in the right universe
&& new Set(portal.perZoneData[graph.dataVar].filter(x => x)).size > 1) { // and there is nonzero, variable data
style = ""
if (!activeUniverses.includes(universe)) activeUniverses.push(universe);
break;
}
}
// hide unused graphs
document.querySelector(`#u${universe}graphSelection [value="${graph.selectorText}"]`).style.display = style;
}
}
// hide universe selector if graphs are only in one universe
let universeSel = document.querySelector(`#universeSelection`);
if (activeUniverses.length === 1) {
universeSel.style.display = "none";
GRAPHSETTINGS.universeSelection = activeUniverses[0];
swapGraphUniverse()
}
else {
universeSel.style.display = "";
}
}
function loadGraphData() {
var loadedData = LZString.decompressFromBase64(localStorage.getItem("portalDataHistory"));
var currentPortal = JSON.parse(localStorage.getItem("portalDataCurrent"));
if (loadedData != "") {
var loadedData = JSON.parse(loadedData);
if (currentPortal) { loadedData[Object.keys(currentPortal)[0]] = Object.values(currentPortal)[0] }
console.log("Graphs: Found portalSaveData")
// remake object structure
for (const [portalID, portalData] of Object.entries(loadedData)) {
portalSaveData[portalID] = new Portal();
for (const [k, v] of Object.entries(portalData)) {
portalSaveData[portalID][k] = v;
}
}
}
loadedSettings = JSON.parse(localStorage.getItem("GRAPHSETTINGS"));
if (loadedSettings !== null) GRAPHSETTINGS = loadedSettings;
MODULES.graphs = {}
MODULES.graphs.useDarkAlways = false
}
// Custom Function Helpers
// diff between x and x-1, or x and initial
function diff(dataVar, initial) {
return function (portal, i) {
let e1 = portal.perZoneData[dataVar][i];
let e2 = initial ? initial : portal.perZoneData[dataVar][i - 1];
if (e1 === null || e2 === null) return null;
return e1 - e2
}
}
const formatters = {
datetime: function () {
let ser = this.series;
return '<span style="color:' + ser.color + '" >●</span> ' + ser.name + ": <b>" + formatDuration(this.y / 1000) + "</b><br>";
},
}
// Create all the Graph objects
// Graph(dataVar, universe, selectorText, additionalParams)
// additionalParams == graphTitle, conditional, customFunction, useAccumulator, toggles, xTitle, yTitle, formatter
// To add a new graph, add it to graphList with the desired options,
// If using a new dataVar, add that to getGameData
// Toggles are perHr, lifetime, s3normalized
// To make a new toggle, add the switch case and title mod to Graph.lineGraph
const graphList = [
// U1 Graphs
["heliumOwned", 1, "Helium", {
toggles: ["perHr", "perZone", "lifetime"]
}],
["fluffy", 1, "Fluffy Exp", {
conditional: () => { return getGameData.u1hze() >= 300 && getGameData.fluffy() < 3415819248011889 }, // pre unlock, post E10L10
customFunction: (portal, i) => { return diff("fluffy", portal.initialFluffy)(portal, i) },
toggles: ["perHr", "perZone",]
}],
["essence", 1, "Dark Essence", {
conditional: () => { return getGameData.essence() < 5.826e+39 },
customFunction: (portal, i) => { return diff("essence", portal.initialDE)(portal, i) },
toggles: ["perHr", "perZone",]
}],
["lastWarp", 1, "Warpstations", {
graphTitle: "Warpstations built on previous Giga",
conditional: () => { return getGameData.u1hze() > 60 && ((game.global.totalHeliumEarned - game.global.heliumLeftover) < 10 ** 10) }, // Warp unlock, less than 10B He allocated
}],
["amals", 1, "Amalgamators"],
["wonders", 1, "Wonders", {
conditional: () => { return getGameData.challengeActive() === "Experience" }
}],
// U2 Graphs
["radonOwned", 2, "Radon", {
toggles: ["perHr", "perZone", "lifetime", "s3normalized"]
}],
["scruffy", 2, "Scruffy Exp", {
customFunction: (portal, i) => { return diff("scruffy", portal.initialScruffy)(portal, i) },
toggles: ["perHr", "perZone",]
}],
["worshippers", 2, "Worshippers", {
conditional: () => { return getGameData.u2hze() >= 50 }
}],
["smithies", 2, "Smithies"],
["bonfires", 2, "Bonfires", {
graphTitle: "Active Bonfires",
conditional: () => { return getGameData.challengeActive() === "Hypothermia" }
}],
["embers", 2, "Embers", {
conditional: () => { return getGameData.challengeActive() === "Hypothermia" }
}],
["cruffys", 2, "Cruffys", {
conditional: () => { return getGameData.challengeActive() === "Nurture" }
}],
// Generic Graphs
["c23increase", false, "C2 Bonus", {
conditional: () => { return game.global.runningChallengeSquared },
toggles: ["perHr", "perZone", "lifetime"]
}],
["voids", false, "Void Map History", {
graphTitle: "Void Map History (voids finished during the same level acquired are not counted/tracked)",
yTitle: "Number of Void Maps",
}],
[false, false, "Total Voids", {
portalVar: "totalVoidMaps",
graphType: "column",
graphTitle: "Total Void Maps Run"
}],
[false, false, "Nullifium Gained", {
portalVar: "totalNullifium",
graphType: "column",
}],
["coord", false, "Coordinations", {
graphTitle: "Unbought Coordinations",
}],
["overkill", false, "Overkill Cells", {
// Overkill unlock zones (roughly)
conditional: () => {
return ((getGameData.universe() == 1 && getGameData.u1hze() >= 170)
|| getGameData.universe() == 2 && getGameData.u2hze() >= 201)
}
}],
["zoneTime", false, "Clear Time", {
yType: "datetime",
formatter: formatters.datetime
}],
["currentTime", false, "Cumulative Clear Time", {
yType: "datetime",
formatter: formatters.datetime,
}],
["mapbonus", false, "Map Bonus"],
["empower", false, "Empower", {
conditional: () => { return getGameData.challengeActive() === "Daily" && typeof game.global.dailyChallenge.empower !== "undefined" }
}]
].map(opts => new Graph(...opts));
const getGameData = {
currentTime: () => { return getGameTime() - game.global.portalTime }, // portalTime changes on pause, 'when a portal started' is not a static concept
world: () => { return game.global.world },
challengeActive: () => { return game.global.challengeActive },
voids: () => { return game.global.totalVoidMaps },
totalVoids: () => { return game.stats.totalVoidMaps.value },
nullifium: () => { return recycleAllExtraHeirlooms(true) },
coord: () => { return game.upgrades.Coordination.allowed - game.upgrades.Coordination.done },
overkill: () => {
// overly complex check for Liq, overly fragile check for overkill cells. please rewrite this at some point.
if (game.options.menu.overkillColor.enabled == 0) toggleSetting("overkillColor");
if (game.options.menu.liquification.enabled && game.talents.liquification.purchased && !game.global.mapsActive && game.global.gridArray && game.global.gridArray[0] && game.global.gridArray[0].name == "Liquimp")
return 100;
else return document.getElementById("grid").getElementsByClassName("cellColorOverkill").length;
},
zoneTime: () => { return Math.round((getGameTime() - game.global.zoneStarted) * 100) / 100 }, // rounded to x.xs
mapbonus: () => { return game.global.mapBonus },
empower: () => { return game.global.challengeActive == "Daily" && typeof game.global.dailyChallenge.empower !== "undefined" ? game.global.dailyChallenge.empower.stacks : 0 },
lastWarp: () => { return game.global.lastWarp },
essence: () => { return game.global.spentEssence + game.global.essence },
heliumOwned: () => { return game.resources.helium.owned },
//magmite: () => { return game.global.magmite },
//magmamancers: () => { return game.jobs.Magmamancer.owned },
fluffy: () => {
//sum of all previous evo costs + current exp
let exp = game.global.fluffyExp;
for (var evo = 0; evo < Fluffy.getCurrentPrestige(); evo++) {
exp += 111848 * 5 ** (evo + 5);
}
return exp
},
//nursery: () => { return game.buildings.Nursery.purchased },
amals: () => { return game.jobs.Amalgamator.owned },
wonders: () => { return game.challenges.Experience.wonders },
scruffy: () => { return game.global.fluffyExp2 },
smithies: () => { return game.buildings.Smithy.owned },
radonOwned: () => { return game.resources.radon.owned },
worshippers: () => { return game.jobs.Worshipper.owned },
bonfires: () => { return game.challenges.Hypothermia.bonfires },
embers: () => { return game.challenges.Hypothermia.embers },
cruffys: () => { return game.challenges.Nurture.level },
universe: () => { return game.global.universe },
s3: () => { return game.global.lastRadonPortal },
u1hze: () => { return game.global.highestLevelCleared },
u2hze: () => { return game.global.highestRadonLevelCleared },
c23increase: () => { return Math.max(0, getIndividualSquaredReward(game.global.challengeActive, game.global.world) - getIndividualSquaredReward(game.global.challengeActive)) },
cinf: () => { return countChallengeSquaredReward(false, false, true) },
}
// Global vars
var chart1;
var lastSave = new Date()
var GRAPHSETTINGS = {
universeSelection: 1,
u1graphSelection: null,
u2graphSelection: null,
rememberSelected: [],
toggles: {},
darkTheme: true,
maxGraphs: 20, // Highcharts gets a bit angry rendering more graphs, also 30 is the maximum you can fit on the legend before it splits into pages.
}
var portalSaveData = {}
// load and initialize the UI
loadGraphData();
init()
showHideUnusedGraphs()
var lastTheme = -1;
// Wrap the Trimps function for transitioning zones to avoid data loss
var originalnextWorld = nextWorld;
nextWorld = function () {
try {
if (game.options.menu.pauseGame.enabled) return;
if (null === portalSaveData) portalSaveData = {};
if (getGameData.world()) { pushData(); }
}
catch (e) {
debug("Gather info failed: " + e)
}
originalnextWorld(...arguments);
}
// Wrap portal function to update on end of run
var originalactivatePortal = activatePortal;
activatePortal = function () {
try {
pushData();
}
catch (e) {
debug("Gather info failed: " + e)
}
originalactivatePortal(...arguments)
}