forked from Azgaar/Fantasy-Map-Generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
1973 lines (1691 loc) · 65.9 KB
/
main.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
"use strict";
// Azgaar ([email protected]). Minsk, 2017-2023. MIT License
// https://github.com/Azgaar/Fantasy-Map-Generator
// set debug options
const PRODUCTION = location.hostname && location.hostname !== "localhost" && location.hostname !== "127.0.0.1";
const DEBUG = localStorage.getItem("debug");
const INFO = true;
const TIME = true;
const WARN = true;
const ERROR = true;
// detect device
const MOBILE = window.innerWidth < 600 || navigator.userAgentData?.mobile;
// typed arrays max values
const UINT8_MAX = 255;
const UINT16_MAX = 65535;
const UINT32_MAX = 4294967295;
if (PRODUCTION && "serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker.register("./sw.js").catch(err => {
console.error("ServiceWorker registration failed: ", err);
});
});
window.addEventListener(
"beforeinstallprompt",
async event => {
event.preventDefault();
const Installation = await import("./modules/dynamic/installation.js?v=1.89.19");
Installation.init(event);
},
{once: true}
);
}
// append svg layers (in default order)
let svg = d3.select("#map");
let defs = svg.select("#deftemp");
let viewbox = svg.select("#viewbox");
let scaleBar = svg.select("#scaleBar");
let legend = svg.append("g").attr("id", "legend");
let ocean = viewbox.append("g").attr("id", "ocean");
let oceanLayers = ocean.append("g").attr("id", "oceanLayers");
let oceanPattern = ocean.append("g").attr("id", "oceanPattern");
let lakes = viewbox.append("g").attr("id", "lakes");
let landmass = viewbox.append("g").attr("id", "landmass");
let texture = viewbox.append("g").attr("id", "texture");
let terrs = viewbox.append("g").attr("id", "terrs");
let biomes = viewbox.append("g").attr("id", "biomes");
let cells = viewbox.append("g").attr("id", "cells");
let gridOverlay = viewbox.append("g").attr("id", "gridOverlay");
let coordinates = viewbox.append("g").attr("id", "coordinates");
let compass = viewbox.append("g").attr("id", "compass");
let rivers = viewbox.append("g").attr("id", "rivers");
let terrain = viewbox.append("g").attr("id", "terrain");
let relig = viewbox.append("g").attr("id", "relig");
let cults = viewbox.append("g").attr("id", "cults");
let regions = viewbox.append("g").attr("id", "regions");
let statesBody = regions.append("g").attr("id", "statesBody");
let statesHalo = regions.append("g").attr("id", "statesHalo");
let provs = viewbox.append("g").attr("id", "provs");
let zones = viewbox.append("g").attr("id", "zones").style("display", "none");
let borders = viewbox.append("g").attr("id", "borders");
let stateBorders = borders.append("g").attr("id", "stateBorders");
let provinceBorders = borders.append("g").attr("id", "provinceBorders");
let routes = viewbox.append("g").attr("id", "routes");
let roads = routes.append("g").attr("id", "roads");
let trails = routes.append("g").attr("id", "trails");
let searoutes = routes.append("g").attr("id", "searoutes");
let temperature = viewbox.append("g").attr("id", "temperature");
let coastline = viewbox.append("g").attr("id", "coastline");
let ice = viewbox.append("g").attr("id", "ice").style("display", "none");
let prec = viewbox.append("g").attr("id", "prec").style("display", "none");
let population = viewbox.append("g").attr("id", "population");
let emblems = viewbox.append("g").attr("id", "emblems").style("display", "none");
let labels = viewbox.append("g").attr("id", "labels");
let icons = viewbox.append("g").attr("id", "icons");
let burgIcons = icons.append("g").attr("id", "burgIcons");
let anchors = icons.append("g").attr("id", "anchors");
let armies = viewbox.append("g").attr("id", "armies").style("display", "none");
let markers = viewbox.append("g").attr("id", "markers");
let fogging = viewbox
.append("g")
.attr("id", "fogging-cont")
.attr("mask", "url(#fog)")
.append("g")
.attr("id", "fogging")
.style("display", "none");
let ruler = viewbox.append("g").attr("id", "ruler").style("display", "none");
let debug = viewbox.append("g").attr("id", "debug");
lakes.append("g").attr("id", "freshwater");
lakes.append("g").attr("id", "salt");
lakes.append("g").attr("id", "sinkhole");
lakes.append("g").attr("id", "frozen");
lakes.append("g").attr("id", "lava");
lakes.append("g").attr("id", "dry");
coastline.append("g").attr("id", "sea_island");
coastline.append("g").attr("id", "lake_island");
terrs.append("g").attr("id", "oceanHeights");
terrs.append("g").attr("id", "landHeights");
labels.append("g").attr("id", "states");
labels.append("g").attr("id", "addedLabels");
let burgLabels = labels.append("g").attr("id", "burgLabels");
burgIcons.append("g").attr("id", "cities");
burgLabels.append("g").attr("id", "cities");
anchors.append("g").attr("id", "cities");
burgIcons.append("g").attr("id", "towns");
burgLabels.append("g").attr("id", "towns");
anchors.append("g").attr("id", "towns");
// population groups
population.append("g").attr("id", "rural");
population.append("g").attr("id", "urban");
// emblem groups
emblems.append("g").attr("id", "burgEmblems");
emblems.append("g").attr("id", "provinceEmblems");
emblems.append("g").attr("id", "stateEmblems");
// fogging
fogging.append("rect").attr("x", 0).attr("y", 0).attr("width", "100%").attr("height", "100%");
fogging
.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", "100%")
.attr("height", "100%")
.attr("fill", "#e8f0f6")
.attr("filter", "url(#splotch)");
// assign events separately as not a viewbox child
scaleBar.on("mousemove", () => tip("Click to open Units Editor")).on("click", () => editUnits());
legend
.on("mousemove", () => tip("Drag to change the position. Click to hide the legend"))
.on("click", () => clearLegend());
// main data variables
let grid = {}; // initial graph based on jittered square grid and data
let pack = {}; // packed graph and data
let seed;
let mapId;
let mapHistory = [];
let elSelected;
let modules = {};
let notes = [];
let rulers = new Rulers();
let customization = 0;
let biomesData = Biomes.getDefault();
let nameBases = Names.getNameBases(); // cultures-related data
let color = d3.scaleSequential(d3.interpolateSpectral); // default color scheme
const lineGen = d3.line().curve(d3.curveBasis); // d3 line generator with default curve interpolation
// d3 zoom behavior
let scale = 1;
let viewX = 0;
let viewY = 0;
function onZoom() {
const {k, x, y} = d3.event.transform;
const isScaleChanged = Boolean(scale - k);
const isPositionChanged = Boolean(viewX - x || viewY - y);
if (!isScaleChanged && !isPositionChanged) return;
scale = k;
viewX = x;
viewY = y;
handleZoom(isScaleChanged, isPositionChanged);
}
const onZoomDebouced = debounce(onZoom, 50);
const zoom = d3.zoom().scaleExtent([1, 20]).on("zoom", onZoomDebouced);
// default options, based on Earth data
let options = {
pinNotes: false,
winds: [225, 45, 225, 315, 135, 315],
temperatureEquator: 27,
temperatureNorthPole: -30,
temperatureSouthPole: -15,
stateLabelsMode: "auto",
showBurgPreview: true,
villageMaxPopulation: 2000
};
let mapCoordinates = {}; // map coordinates on globe
let populationRate = +document.getElementById("populationRateInput").value;
let distanceScale = +document.getElementById("distanceScaleInput").value;
let urbanization = +document.getElementById("urbanizationInput").value;
let urbanDensity = +document.getElementById("urbanDensityInput").value;
applyStoredOptions();
// voronoi graph extension, cannot be changed after generation
let graphWidth = +mapWidthInput.value;
let graphHeight = +mapHeightInput.value;
// svg canvas resolution, can be changed
let svgWidth = graphWidth;
let svgHeight = graphHeight;
landmass.append("rect").attr("x", 0).attr("y", 0).attr("width", graphWidth).attr("height", graphHeight);
oceanPattern
.append("rect")
.attr("fill", "url(#oceanic)")
.attr("x", 0)
.attr("y", 0)
.attr("width", graphWidth)
.attr("height", graphHeight);
oceanLayers
.append("rect")
.attr("id", "oceanBase")
.attr("x", 0)
.attr("y", 0)
.attr("width", graphWidth)
.attr("height", graphHeight);
document.addEventListener("DOMContentLoaded", async () => {
if (!location.hostname) {
const wiki = "https://github.com/Azgaar/Fantasy-Map-Generator/wiki/Run-FMG-locally";
alertMessage.innerHTML = /* html */ `Fantasy Map Generator cannot run serverless. Follow the <a href="${wiki}" target="_blank">instructions</a> on how you can easily run a local web-server`;
$("#alert").dialog({
resizable: false,
title: "Loading error",
width: "28em",
position: {my: "center center-4em", at: "center", of: "svg"},
buttons: {
OK: function () {
$(this).dialog("close");
}
}
});
} else {
hideLoading();
await checkLoadParameters();
}
restoreDefaultEvents(); // apply default viewbox events
initiateAutosave();
});
function hideLoading() {
d3.select("#loading").transition().duration(3000).style("opacity", 0);
d3.select("#optionsContainer").transition().duration(2000).style("opacity", 1);
d3.select("#tooltip").transition().duration(3000).style("opacity", 1);
}
function showLoading() {
d3.select("#loading").transition().duration(200).style("opacity", 1);
d3.select("#optionsContainer").transition().duration(100).style("opacity", 0);
d3.select("#tooltip").transition().duration(200).style("opacity", 0);
}
// decide which map should be loaded or generated on page load
async function checkLoadParameters() {
const url = new URL(window.location.href);
const params = url.searchParams;
// of there is a valid maplink, try to load .map/.gz file from URL
if (params.get("maplink")) {
WARN && console.warn("Load map from URL");
const maplink = params.get("maplink");
const pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
const valid = pattern.test(maplink);
if (valid) {
setTimeout(() => {
loadMapFromURL(maplink, 1);
}, 1000);
return;
} else showUploadErrorMessage("Map link is not a valid URL", maplink);
}
// if there is a seed (user of MFCG provided), generate map for it
if (params.get("seed")) {
WARN && console.warn("Generate map for seed");
await generateMapOnLoad();
return;
}
// check if there is a map saved to indexedDB
if (byId("onloadBehavior").value === "lastSaved") {
try {
const blob = await ldb.get("lastMap");
if (blob) {
WARN && console.warn("Loading last stored map");
uploadMap(blob);
return;
}
} catch (error) {
ERROR && console.error(error);
}
}
// else generate random map
WARN && console.warn("Generate random map");
generateMapOnLoad();
}
async function generateMapOnLoad() {
await applyStyleOnLoad(); // apply previously selected default or custom style
await generate(); // generate map
applyPreset(); // apply saved layers preset
fitMapToScreen();
focusOn(); // based on searchParams focus on point, cell or burg from MFCG
}
// focus on coordinates, cell or burg provided in searchParams
function focusOn() {
const url = new URL(window.location.href);
const params = url.searchParams;
const fromMGCG = params.get("from") === "MFCG" && document.referrer;
if (fromMGCG) {
if (params.get("seed").length === 13) {
// show back burg from MFCG
const burgSeed = params.get("seed").slice(-4);
params.set("burg", burgSeed);
} else {
// select burg for MFCG
findBurgForMFCG(params);
return;
}
}
const scaleParam = params.get("scale");
const cellParam = params.get("cell");
const burgParam = params.get("burg");
if (scaleParam || cellParam || burgParam) {
const scale = +scaleParam || 8;
if (cellParam) {
const cell = +params.get("cell");
const [x, y] = pack.cells.p[cell];
zoomTo(x, y, scale, 1600);
return;
}
if (burgParam) {
const burg = isNaN(+burgParam) ? pack.burgs.find(burg => burg.name === burgParam) : pack.burgs[+burgParam];
if (!burg) return;
const {x, y} = burg;
zoomTo(x, y, scale, 1600);
return;
}
const x = +params.get("x") || graphWidth / 2;
const y = +params.get("y") || graphHeight / 2;
zoomTo(x, y, scale, 1600);
}
}
// find burg for MFCG and focus on it
function findBurgForMFCG(params) {
const cells = pack.cells,
burgs = pack.burgs;
if (pack.burgs.length < 2) {
ERROR && console.error("Cannot select a burg for MFCG");
return;
}
// used for selection
const size = +params.get("size");
const coast = +params.get("coast");
const port = +params.get("port");
const river = +params.get("river");
let selection = defineSelection(coast, port, river);
if (!selection.length) selection = defineSelection(coast, !port, !river);
if (!selection.length) selection = defineSelection(!coast, 0, !river);
if (!selection.length) selection = [burgs[1]]; // select first if nothing is found
function defineSelection(coast, port, river) {
if (port && river) return burgs.filter(b => b.port && cells.r[b.cell]);
if (!port && coast && river) return burgs.filter(b => !b.port && cells.t[b.cell] === 1 && cells.r[b.cell]);
if (!coast && !river) return burgs.filter(b => cells.t[b.cell] !== 1 && !cells.r[b.cell]);
if (!coast && river) return burgs.filter(b => cells.t[b.cell] !== 1 && cells.r[b.cell]);
if (coast && river) return burgs.filter(b => cells.t[b.cell] === 1 && cells.r[b.cell]);
return [];
}
// select a burg with closest population from selection
const selected = d3.scan(selection, (a, b) => Math.abs(a.population - size) - Math.abs(b.population - size));
const burgId = selection[selected].i;
if (!burgId) {
ERROR && console.error("Cannot select a burg for MFCG");
return;
}
const b = burgs[burgId];
const referrer = new URL(document.referrer);
for (let p of referrer.searchParams) {
if (p[0] === "name") b.name = p[1];
else if (p[0] === "size") b.population = +p[1];
else if (p[0] === "seed") b.MFCG = +p[1];
else if (p[0] === "shantytown") b.shanty = +p[1];
else b[p[0]] = +p[1]; // other parameters
}
if (params.get("name") && params.get("name") != "null") b.name = params.get("name");
const label = burgLabels.select("[data-id='" + burgId + "']");
if (label.size()) {
label
.text(b.name)
.classed("drag", true)
.on("mouseover", function () {
d3.select(this).classed("drag", false);
label.on("mouseover", null);
});
}
zoomTo(b.x, b.y, 8, 1600);
invokeActiveZooming();
tip("Here stands the glorious city of " + b.name, true, "success", 15000);
}
function handleZoom(isScaleChanged, isPositionChanged) {
viewbox.attr("transform", `translate(${viewX} ${viewY}) scale(${scale})`);
if (isPositionChanged) drawCoordinates();
if (isScaleChanged) {
invokeActiveZooming();
drawScaleBar(scaleBar, scale);
fitScaleBar(scaleBar, svgWidth, svgHeight);
}
// zoom image converter overlay
if (customization === 1) {
const canvas = document.getElementById("canvas");
if (!canvas || canvas.style.opacity === "0") return;
const img = document.getElementById("imageToConvert");
if (!img) return;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.setTransform(scale, 0, 0, scale, viewX, viewY);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
}
}
// Zoom to a specific point
function zoomTo(x, y, z = 8, d = 2000) {
const transform = d3.zoomIdentity.translate(x * -z + graphWidth / 2, y * -z + graphHeight / 2).scale(z);
svg.transition().duration(d).call(zoom.transform, transform);
}
// Reset zoom to initial
function resetZoom(d = 1000) {
svg.transition().duration(d).call(zoom.transform, d3.zoomIdentity);
}
// calculate x y extreme points of viewBox
function getViewBoxExtent() {
return [
[Math.abs(viewX / scale), Math.abs(viewY / scale)],
[Math.abs(viewX / scale) + graphWidth / scale, Math.abs(viewY / scale) + graphHeight / scale]
];
}
// active zooming feature
function invokeActiveZooming() {
const isOptimized = shapeRendering.value === "optimizeSpeed";
if (coastline.select("#sea_island").size() && +coastline.select("#sea_island").attr("auto-filter")) {
// toggle shade/blur filter for coatline on zoom
const filter = scale > 1.5 && scale <= 2.6 ? null : scale > 2.6 ? "url(#blurFilter)" : "url(#dropShadow)";
coastline.select("#sea_island").attr("filter", filter);
}
// rescale labels on zoom
if (labels.style("display") !== "none") {
labels.selectAll("g").each(function () {
if (this.id === "burgLabels") return;
const desired = +this.dataset.size;
const relative = Math.max(rn((desired + desired / scale) / 2, 2), 1);
if (rescaleLabels.checked) this.setAttribute("font-size", relative);
const hidden = hideLabels.checked && (relative * scale < 6 || relative * scale > 60);
if (hidden) this.classList.add("hidden");
else this.classList.remove("hidden");
});
}
// rescale emblems on zoom
if (emblems.style("display") !== "none") {
emblems.selectAll("g").each(function () {
const size = this.getAttribute("font-size") * scale;
const hidden = hideEmblems.checked && (size < 25 || size > 300);
if (hidden) this.classList.add("hidden");
else this.classList.remove("hidden");
if (!hidden && window.COArenderer && this.children.length && !this.children[0].getAttribute("href"))
renderGroupCOAs(this);
});
}
// turn off ocean pattern if scale is big (improves performance)
oceanPattern
.select("rect")
.attr("fill", scale > 10 ? "#fff" : "url(#oceanic)")
.attr("opacity", scale > 10 ? 0.2 : null);
// change states halo width
if (!customization && !isOptimized) {
const desired = +statesHalo.attr("data-width");
const haloSize = rn(desired / scale ** 0.8, 2);
statesHalo.attr("stroke-width", haloSize).style("display", haloSize > 0.1 ? "block" : "none");
}
// rescale map markers
+markers.attr("rescale") &&
pack.markers?.forEach(marker => {
const {i, x, y, size = 30, hidden} = marker;
const el = !hidden && document.getElementById(`marker${i}`);
if (!el) return;
const zoomedSize = Math.max(rn(size / 5 + 24 / scale, 2), 1);
el.setAttribute("width", zoomedSize);
el.setAttribute("height", zoomedSize);
el.setAttribute("x", rn(x - zoomedSize / 2, 1));
el.setAttribute("y", rn(y - zoomedSize, 1));
});
// rescale rulers to have always the same size
if (ruler.style("display") !== "none") {
const size = rn((10 / scale ** 0.3) * 2, 2);
ruler.selectAll("text").attr("font-size", size);
}
}
async function renderGroupCOAs(g) {
const [group, type] =
g.id === "burgEmblems"
? [pack.burgs, "burg"]
: g.id === "provinceEmblems"
? [pack.provinces, "province"]
: [pack.states, "state"];
for (let use of g.children) {
const i = +use.dataset.i;
const id = type + "COA" + i;
COArenderer.trigger(id, group[i].coa);
use.setAttribute("href", "#" + id);
}
}
// add drag to upload logic, pull request from @evyatron
void (function addDragToUpload() {
document.addEventListener("dragover", function (e) {
e.stopPropagation();
e.preventDefault();
document.getElementById("mapOverlay").style.display = null;
});
document.addEventListener("dragleave", function (e) {
document.getElementById("mapOverlay").style.display = "none";
});
document.addEventListener("drop", function (e) {
e.stopPropagation();
e.preventDefault();
const overlay = document.getElementById("mapOverlay");
overlay.style.display = "none";
if (e.dataTransfer.items == null || e.dataTransfer.items.length !== 1) return; // no files or more than one
const file = e.dataTransfer.items[0].getAsFile();
if (!file.name.endsWith(".map") && !file.name.endsWith(".gz")) {
alertMessage.innerHTML =
"Please upload a map file (<i>.map</i> or <i>.gz</i> formats) you have previously downloaded";
$("#alert").dialog({
resizable: false,
title: "Invalid file format",
position: {my: "center", at: "center", of: "svg"},
buttons: {
Close: function () {
$(this).dialog("close");
}
}
});
return;
}
// all good - show uploading text and load the map
overlay.style.display = null;
overlay.innerHTML = "Uploading<span>.</span><span>.</span><span>.</span>";
if (closeDialogs) closeDialogs();
uploadMap(file, () => {
overlay.style.display = "none";
overlay.innerHTML = "Drop a map file to open";
});
});
})();
async function generate(options) {
try {
const timeStart = performance.now();
const {seed: precreatedSeed, graph: precreatedGraph} = options || {};
invokeActiveZooming();
setSeed(precreatedSeed);
INFO && console.group("Generated Map " + seed);
applyGraphSize();
randomizeOptions();
if (shouldRegenerateGrid(grid, precreatedSeed)) grid = precreatedGraph || generateGrid();
else delete grid.cells.h;
grid.cells.h = await HeightmapGenerator.generate(grid);
pack = {}; // reset pack
markFeatures();
markupGridOcean();
addLakesInDeepDepressions();
openNearSeaLakes();
OceanLayers();
defineMapSize();
calculateMapCoordinates();
calculateTemperatures();
generatePrecipitation();
reGraph();
drawCoastline();
Rivers.generate();
drawRivers();
Lakes.defineGroup();
Biomes.define();
rankCells();
Cultures.generate();
Cultures.expand();
BurgsAndStates.generate();
Religions.generate();
BurgsAndStates.defineStateForms();
BurgsAndStates.generateProvinces();
BurgsAndStates.defineBurgFeatures();
drawStates();
drawBorders();
drawStateLabels();
Rivers.specify();
Lakes.generateName();
Military.generate();
Markers.generate();
addZones();
drawScaleBar(scaleBar, scale);
Names.getMapName();
WARN && console.warn(`TOTAL: ${rn((performance.now() - timeStart) / 1000, 2)}s`);
showStatistics();
INFO && console.groupEnd("Generated Map " + seed);
} catch (error) {
ERROR && console.error(error);
const parsedError = parseError(error);
clearMainTip();
alertMessage.innerHTML = /* html */ `An error has occurred on map generation. Please retry. <br />If error is critical, clear the stored data and try again.
<p id="errorBox">${parsedError}</p>`;
$("#alert").dialog({
resizable: false,
title: "Generation error",
width: "32em",
buttons: {
"Clear data": function () {
localStorage.clear();
localStorage.setItem("version", version);
},
Regenerate: function () {
regenerateMap("generation error");
$(this).dialog("close");
},
Ignore: function () {
$(this).dialog("close");
}
},
position: {my: "center", at: "center", of: "svg"}
});
}
}
// set map seed (string!)
function setSeed(precreatedSeed) {
if (!precreatedSeed) {
const first = !mapHistory[0];
const params = new URL(window.location.href).searchParams;
const urlSeed = params.get("seed");
if (first && params.get("from") === "MFCG" && urlSeed.length === 13) seed = urlSeed.slice(0, -4);
else if (first && urlSeed) seed = urlSeed;
else seed = generateSeed();
} else {
seed = precreatedSeed;
}
byId("optionsSeed").value = seed;
Math.random = aleaPRNG(seed);
}
// Mark features (ocean, lakes, islands) and calculate distance field
function markFeatures() {
TIME && console.time("markFeatures");
Math.random = aleaPRNG(seed); // get the same result on heightmap edit in Erase mode
const cells = grid.cells;
const heights = grid.cells.h;
cells.f = new Uint16Array(cells.i.length); // cell feature number
cells.t = new Int8Array(cells.i.length); // cell type: 1 = land coast; -1 = water near coast
grid.features = [0];
for (let i = 1, queue = [0]; queue[0] !== -1; i++) {
cells.f[queue[0]] = i; // feature number
const land = heights[queue[0]] >= 20;
let border = false; // true if feature touches map border
while (queue.length) {
const q = queue.pop();
if (cells.b[q]) border = true;
cells.c[q].forEach(c => {
const cLand = heights[c] >= 20;
if (land === cLand && !cells.f[c]) {
cells.f[c] = i;
queue.push(c);
} else if (land && !cLand) {
cells.t[q] = 1;
cells.t[c] = -1;
}
});
}
const type = land ? "island" : border ? "ocean" : "lake";
grid.features.push({i, land, border, type});
queue[0] = cells.f.findIndex(f => !f); // find unmarked cell
}
TIME && console.timeEnd("markFeatures");
}
function markupGridOcean() {
TIME && console.time("markupGridOcean");
markup(grid.cells, -2, -1, -10);
TIME && console.timeEnd("markupGridOcean");
}
// Calculate cell-distance to coast for every cell
function markup(cells, start, increment, limit) {
for (let t = start, count = Infinity; count > 0 && t > limit; t += increment) {
count = 0;
const prevT = t - increment;
for (let i = 0; i < cells.i.length; i++) {
if (cells.t[i] !== prevT) continue;
for (const c of cells.c[i]) {
if (cells.t[c]) continue;
cells.t[c] = t;
count++;
}
}
}
}
function addLakesInDeepDepressions() {
TIME && console.time("addLakesInDeepDepressions");
const {cells, features} = grid;
const {c, h, b} = cells;
const ELEVATION_LIMIT = +document.getElementById("lakeElevationLimitOutput").value;
if (ELEVATION_LIMIT === 80) return;
for (const i of cells.i) {
if (b[i] || h[i] < 20) continue;
const minHeight = d3.min(c[i].map(c => h[c]));
if (h[i] > minHeight) continue;
let deep = true;
const threshold = h[i] + ELEVATION_LIMIT;
const queue = [i];
const checked = [];
checked[i] = true;
// check if elevated cell can potentially pour to water
while (deep && queue.length) {
const q = queue.pop();
for (const n of c[q]) {
if (checked[n]) continue;
if (h[n] >= threshold) continue;
if (h[n] < 20) {
deep = false;
break;
}
checked[n] = true;
queue.push(n);
}
}
// if not, add a lake
if (deep) {
const lakeCells = [i].concat(c[i].filter(n => h[n] === h[i]));
addLake(lakeCells);
}
}
function addLake(lakeCells) {
const f = features.length;
lakeCells.forEach(i => {
cells.h[i] = 19;
cells.t[i] = -1;
cells.f[i] = f;
c[i].forEach(n => !lakeCells.includes(n) && (cells.t[c] = 1));
});
features.push({i: f, land: false, border: false, type: "lake"});
}
TIME && console.timeEnd("addLakesInDeepDepressions");
}
// near sea lakes usually get a lot of water inflow, most of them should break threshold and flow out to sea (see Ancylus Lake)
function openNearSeaLakes() {
if (byId("templateInput").value === "Atoll") return; // no need for Atolls
const cells = grid.cells;
const features = grid.features;
if (!features.find(f => f.type === "lake")) return; // no lakes
TIME && console.time("openLakes");
const LIMIT = 22; // max height that can be breached by water
for (const i of cells.i) {
const lakeFeatureId = cells.f[i];
if (features[lakeFeatureId].type !== "lake") continue; // not a lake
check_neighbours: for (const c of cells.c[i]) {
if (cells.t[c] !== 1 || cells.h[c] > LIMIT) continue; // water cannot break this
for (const n of cells.c[c]) {
const ocean = cells.f[n];
if (features[ocean].type !== "ocean") continue; // not an ocean
removeLake(c, lakeFeatureId, ocean);
break check_neighbours;
}
}
}
function removeLake(thresholdCellId, lakeFeatureId, oceanFeatureId) {
cells.h[thresholdCellId] = 19;
cells.t[thresholdCellId] = -1;
cells.f[thresholdCellId] = oceanFeatureId;
cells.c[thresholdCellId].forEach(function (c) {
if (cells.h[c] >= 20) cells.t[c] = 1; // mark as coastline
});
cells.i.forEach(i => {
if (cells.f[i] === lakeFeatureId) cells.f[i] = oceanFeatureId;
});
features[lakeFeatureId].type = "ocean"; // mark former lake as ocean
}
TIME && console.timeEnd("openLakes");
}
// define map size and position based on template and random factor
function defineMapSize() {
const [size, latitude] = getSizeAndLatitude();
const randomize = new URL(window.location.href).searchParams.get("options") === "default"; // ignore stored options
if (randomize || !locked("mapSize")) mapSizeOutput.value = mapSizeInput.value = rn(size);
if (randomize || !locked("latitude")) latitudeOutput.value = latitudeInput.value = rn(latitude);
function getSizeAndLatitude() {
const template = byId("templateInput").value; // heightmap template
if (template === "africa-centric") return [45, 53];
if (template === "arabia") return [20, 35];
if (template === "atlantics") return [42, 23];
if (template === "britain") return [7, 20];
if (template === "caribbean") return [15, 40];
if (template === "east-asia") return [11, 28];
if (template === "eurasia") return [38, 19];
if (template === "europe") return [20, 16];
if (template === "europe-accented") return [14, 22];
if (template === "europe-and-central-asia") return [25, 10];
if (template === "europe-central") return [11, 22];
if (template === "europe-north") return [7, 18];
if (template === "greenland") return [22, 7];
if (template === "hellenica") return [8, 27];
if (template === "iceland") return [2, 15];
if (template === "indian-ocean") return [45, 55];
if (template === "mediterranean-sea") return [10, 29];
if (template === "middle-east") return [8, 31];
if (template === "north-america") return [37, 17];
if (template === "us-centric") return [66, 27];
if (template === "us-mainland") return [16, 30];
if (template === "world") return [78, 27];
if (template === "world-from-pacific") return [75, 32];
const part = grid.features.some(f => f.land && f.border); // if land goes over map borders
const max = part ? 80 : 100; // max size
const lat = () => gauss(P(0.5) ? 40 : 60, 20, 25, 75); // latitude shift
if (!part) {
if (template === "Pangea") return [100, 50];
if (template === "Shattered" && P(0.7)) return [100, 50];
if (template === "Continents" && P(0.5)) return [100, 50];
if (template === "Archipelago" && P(0.35)) return [100, 50];
if (template === "High Island" && P(0.25)) return [100, 50];
if (template === "Low Island" && P(0.1)) return [100, 50];
}
if (template === "Pangea") return [gauss(70, 20, 30, max), lat()];
if (template === "Volcano") return [gauss(20, 20, 10, max), lat()];
if (template === "Mediterranean") return [gauss(25, 30, 15, 80), lat()];
if (template === "Peninsula") return [gauss(15, 15, 5, 80), lat()];
if (template === "Isthmus") return [gauss(15, 20, 3, 80), lat()];
if (template === "Atoll") return [gauss(5, 10, 2, max), lat()];
return [gauss(30, 20, 15, max), lat()]; // Continents, Archipelago, High Island, Low Island
}
}
// calculate map position on globe
function calculateMapCoordinates() {
const size = +document.getElementById("mapSizeOutput").value;
const latShift = +document.getElementById("latitudeOutput").value;
const latT = rn((size / 100) * 180, 1);
const latN = rn(90 - ((180 - latT) * latShift) / 100, 1);
const latS = rn(latN - latT, 1);
const lon = rn(Math.min(((graphWidth / graphHeight) * latT) / 2, 180));
mapCoordinates = {latT, latN, latS, lonT: lon * 2, lonW: -lon, lonE: lon};
}
// temperature model, trying to follow real-world data
// based on http://www-das.uwyo.edu/~geerts/cwx/notes/chap16/Image64.gif
function calculateTemperatures() {
TIME && console.time("calculateTemperatures");
const cells = grid.cells;
cells.temp = new Int8Array(cells.i.length); // temperature array
const {temperatureEquator, temperatureNorthPole, temperatureSouthPole} = options;
const tropics = [16, -20]; // tropics zone
const tropicalGradient = 0.15;
const tempNorthTropic = temperatureEquator - tropics[0] * tropicalGradient;
const northernGradient = (tempNorthTropic - temperatureNorthPole) / (90 - tropics[0]);
const tempSouthTropic = temperatureEquator + tropics[1] * tropicalGradient;
const southernGradient = (tempSouthTropic - temperatureSouthPole) / (90 + tropics[1]);
const exponent = +heightExponentInput.value;
for (let rowCellId = 0; rowCellId < cells.i.length; rowCellId += grid.cellsX) {
const [, y] = grid.points[rowCellId];
const rowLatitude = mapCoordinates.latN - (y / graphHeight) * mapCoordinates.latT; // [90; -90]
const tempSeaLevel = calculateSeaLevelTemp(rowLatitude);
DEBUG && console.info(`${rn(rowLatitude)}° sea temperature: ${rn(tempSeaLevel)}°C`);
for (let cellId = rowCellId; cellId < rowCellId + grid.cellsX; cellId++) {
const tempAltitudeDrop = getAltitudeTemperatureDrop(cells.h[cellId]);
cells.temp[cellId] = minmax(tempSeaLevel - tempAltitudeDrop, -128, 127);
}
}
function calculateSeaLevelTemp(latitude) {
const isTropical = latitude <= 16 && latitude >= -20;
if (isTropical) return temperatureEquator - Math.abs(latitude) * tropicalGradient;
return latitude > 0
? tempNorthTropic - (latitude - tropics[0]) * northernGradient
: tempSouthTropic + (latitude - tropics[1]) * southernGradient;
}
// temperature drops by 6.5°C per 1km of altitude
function getAltitudeTemperatureDrop(h) {
if (h < 20) return 0;
const height = Math.pow(h - 18, exponent);
return rn((height / 1000) * 6.5);
}
TIME && console.timeEnd("calculateTemperatures");
}