merge module ui

This commit is contained in:
Peter 2022-11-27 16:56:11 -05:00
parent 8875f5d10a
commit 112e78f40a
14 changed files with 579 additions and 717 deletions

View file

@ -8116,14 +8116,14 @@
<script src="config/precreated-heightmaps.js"></script> <script src="config/precreated-heightmaps.js"></script>
<script src="modules/heightmap-generator.js"></script> <script src="modules/heightmap-generator.js"></script>
<script src="modules/ocean-layers.js?v=1.87.15"></script> <script src="modules/ocean-layers.js?v=1.87.15"></script>
<script src="modules/resources-generator.js"></script>
<script src="modules/production-generator.js"></script>
<script src="modules/trade-generator.js"></script>
<script src="modules/river-generator.js"></script> <script src="modules/river-generator.js"></script>
<script src="modules/lakes.js"></script> <script src="modules/lakes.js"></script>
<script src="modules/names-generator.js?v=1.87.14"></script> <script src="modules/names-generator.js?v=1.87.14"></script>
<script src="modules/cultures-generator.js?v=1.87.14"></script> <script src="modules/cultures-generator.js?v=1.87.14"></script>
<script src="modules/resources-generator.js"></script>
<script src="modules/burgs-and-states.js?v=1.87.10"></script> <script src="modules/burgs-and-states.js?v=1.87.10"></script>
<script src="modules/production-generator.js"></script>
<script src="modules/trade-generator.js"></script>
<script src="modules/routes-generator.js"></script> <script src="modules/routes-generator.js"></script>
<script src="modules/religions-generator.js"></script> <script src="modules/religions-generator.js"></script>
<script src="modules/military-generator.js"></script> <script src="modules/military-generator.js"></script>

View file

@ -1,5 +1,5 @@
// module stub to store common functions for ui editors // module stub to store common functions for ui editors
'use strict'; "use strict";
modules.editors = true; modules.editors = true;
@ -41,9 +41,9 @@ function clicked() {
function unselect() { function unselect() {
restoreDefaultEvents(); restoreDefaultEvents();
if (!elSelected) return; if (!elSelected) return;
elSelected.call(d3.drag().on('drag', null)).attr('class', null); elSelected.call(d3.drag().on("drag", null)).attr("class", null);
debug.selectAll('*').remove(); debug.selectAll("*").remove();
viewbox.style('cursor', 'default'); viewbox.style("cursor", "default");
elSelected = null; elSelected = null;
} }
@ -65,9 +65,9 @@ function moveCircle(x, y, r = 20) {
const html = /* html */ `<circle id="brushCircle" cx=${x} cy=${y} r=${r}></circle>`; const html = /* html */ `<circle id="brushCircle" cx=${x} cy=${y} r=${r}></circle>`;
byId("debug").insertAdjacentHTML("afterBegin", html); byId("debug").insertAdjacentHTML("afterBegin", html);
} else { } else {
circle.setAttribute('cx', x); circle.setAttribute("cx", x);
circle.setAttribute('cy', y); circle.setAttribute("cy", y);
circle.setAttribute('r', r); circle.setAttribute("r", r);
} }
} }
@ -77,7 +77,7 @@ function removeCircle() {
// get browser-defined fit-content // get browser-defined fit-content
function fitContent() { function fitContent() {
return !window.chrome ? '-moz-max-content' : 'fit-content'; return !window.chrome ? "-moz-max-content" : "fit-content";
} }
// apply sorting behaviour for lines on Editor header click // apply sorting behaviour for lines on Editor header click
@ -117,8 +117,8 @@ function applySorting(headers) {
const header = headers.querySelector("div[class*='icon-sort']"); const header = headers.querySelector("div[class*='icon-sort']");
if (!header) return; if (!header) return;
const sortby = header.dataset.sortby; const sortby = header.dataset.sortby;
const name = header.classList.contains('alphabetically'); const name = header.classList.contains("alphabetically");
const desc = header.className.includes('-down') ? -1 : 1; const desc = header.className.includes("-down") ? -1 : 1;
const list = headers.nextElementSibling; const list = headers.nextElementSibling;
const lines = Array.from(list.children); const lines = Array.from(list.children);
@ -149,7 +149,7 @@ function addBurg(point) {
// generate emblem // generate emblem
const coa = COA.generate(pack.states[state].coa, 0.25, null, type); const coa = COA.generate(pack.states[state].coa, 0.25, null, type);
coa.shield = COA.getShield(culture, state); coa.shield = COA.getShield(culture, state);
COArenderer.add('burg', i, coa, x, y); COArenderer.add("burg", i, coa, x, y);
pack.burgs.push({name, cell, x, y, state, i, culture, feature, capital: 0, port: 0, temple, population, coa, type}); pack.burgs.push({name, cell, x, y, state, i, culture, feature, capital: 0, port: 0, temple, population, coa, type});
cells.burg[cell] = i; cells.burg[cell] = i;
@ -189,9 +189,9 @@ function moveBurgToGroup(id, g) {
document.querySelector("#burgLabels > #" + g).appendChild(label); document.querySelector("#burgLabels > #" + g).appendChild(label);
document.querySelector("#burgIcons > #" + g).appendChild(icon); document.querySelector("#burgIcons > #" + g).appendChild(icon);
const iconSize = icon.parentNode.getAttribute('size'); const iconSize = icon.parentNode.getAttribute("size");
icon.setAttribute('r', iconSize); icon.setAttribute("r", iconSize);
label.setAttribute('dy', `${iconSize * -1.5}px`); label.setAttribute("dy", `${iconSize * -1.5}px`);
if (anchor) { if (anchor) {
document.querySelector("#anchors > #" + g).appendChild(anchor); document.querySelector("#anchors > #" + g).appendChild(anchor);
@ -260,8 +260,8 @@ function toggleCapital(burg) {
pack.states[state].center = pack.burgs[burg].cell; pack.states[state].center = pack.burgs[burg].cell;
pack.burgs[burg].capital = 1; pack.burgs[burg].capital = 1;
pack.burgs[old].capital = 0; pack.burgs[old].capital = 0;
moveBurgToGroup(burg, 'cities'); moveBurgToGroup(burg, "cities");
moveBurgToGroup(old, 'towns'); moveBurgToGroup(old, "towns");
} }
function togglePort(burg) { function togglePort(burg) {
@ -275,7 +275,7 @@ function togglePort(burg) {
const haven = pack.cells.haven[b.cell]; const haven = pack.cells.haven[b.cell];
const port = haven ? pack.cells.f[haven] : -1; const port = haven ? pack.cells.f[haven] : -1;
if (!haven) tip("Port haven is not found, system won't be able to make a searoute", false, 'warn'); if (!haven) tip("Port haven is not found, system won't be able to make a searoute", false, "warn");
b.port = port; b.port = port;
const g = b.capital ? "cities" : "towns"; const g = b.capital ? "cities" : "towns";
@ -358,11 +358,11 @@ function getMFCGlink(burg) {
// draw legend box // draw legend box
function drawLegend(name, data) { function drawLegend(name, data) {
legend.selectAll('*').remove(); // fully redraw every time legend.selectAll("*").remove(); // fully redraw every time
legend.attr('data', data.join('|')); // store data legend.attr("data", data.join("|")); // store data
const itemsInCol = +styleLegendColItems.value; const itemsInCol = +styleLegendColItems.value;
const fontSize = +legend.attr('font-size'); const fontSize = +legend.attr("font-size");
const backClr = styleLegendBack.value; const backClr = styleLegendBack.value;
const opacity = +styleLegendOpacity.value; const opacity = +styleLegendOpacity.value;
@ -429,9 +429,9 @@ function drawLegend(name, data) {
// fit Legend box to canvas size // fit Legend box to canvas size
function fitLegendBox() { function fitLegendBox() {
if (!legend.selectAll('*').size()) return; if (!legend.selectAll("*").size()) return;
const px = isNaN(+legend.attr('data-x')) ? 99 : legend.attr('data-x') / 100; const px = isNaN(+legend.attr("data-x")) ? 99 : legend.attr("data-x") / 100;
const py = isNaN(+legend.attr('data-y')) ? 93 : legend.attr('data-y') / 100; const py = isNaN(+legend.attr("data-y")) ? 93 : legend.attr("data-y") / 100;
const bbox = legend.node().getBBox(); const bbox = legend.node().getBBox();
const x = rn(svgWidth * px - bbox.width), const x = rn(svgWidth * px - bbox.width),
y = rn(svgHeight * py - bbox.height); y = rn(svgHeight * py - bbox.height);
@ -464,13 +464,12 @@ function dragLegendBox() {
} }
function clearLegend() { function clearLegend() {
legend.selectAll('*').remove(); legend.selectAll("*").remove();
legend.attr('data', null); legend.attr("data", null);
} }
// draw color (fill) picker // draw color (fill) picker
function createPicker() { function createPicker() {
const COLORS_IN_ROW = 14;
const pos = () => tip("Drag to change the picker position"); const pos = () => tip("Drag to change the picker position");
const cl = () => tip("Click to close the picker"); const cl = () => tip("Click to close the picker");
const closePicker = () => container.style("display", "none"); const closePicker = () => container.style("display", "none");
@ -500,12 +499,12 @@ function createPicker() {
.on("start", dragPicker) .on("start", dragPicker)
); );
const controls = picker.append('g').attr('id', 'pickerControls'); const controls = picker.append("g").attr("id", "pickerControls");
const h = controls.append('g'); const h = controls.append("g");
h.append('text').attr('x', 4).attr('y', 14).text('H:'); h.append("text").attr("x", 4).attr("y", 14).text("H:");
h.append('line').attr('x1', 18).attr('y1', 10).attr('x2', 107).attr('y2', 10); h.append("line").attr("x1", 18).attr("y1", 10).attr("x2", 107).attr("y2", 10);
h.append('circle').attr('cx', 75).attr('cy', 10).attr('r', 5).attr('id', 'pickerH'); h.append("circle").attr("cx", 75).attr("cy", 10).attr("r", 5).attr("id", "pickerH");
h.on('mousemove', () => tip('Set palette hue')); h.on("mousemove", () => tip("Set palette hue"));
const s = controls.append("g"); const s = controls.append("g");
s.append("text").attr("x", 113).attr("y", 14).text("S:"); s.append("text").attr("x", 113).attr("y", 14).text("S:");
@ -513,14 +512,14 @@ function createPicker() {
s.append("circle").attr("cx", 181.4).attr("cy", 10).attr("r", 5).attr("id", "pickerS"); s.append("circle").attr("cx", 181.4).attr("cy", 10).attr("r", 5).attr("id", "pickerS");
s.on("mousemove", () => tip("Set palette saturation")); s.on("mousemove", () => tip("Set palette saturation"));
const l = controls.append('g'); const l = controls.append("g");
l.append('text').attr('x', 213).attr('y', 14).text('L:'); l.append("text").attr("x", 213).attr("y", 14).text("L:");
l.append('line').attr('x1', 226).attr('y1', 10).attr('x2', 306).attr('y2', 10); l.append("line").attr("x1", 226).attr("y1", 10).attr("x2", 306).attr("y2", 10);
l.append('circle').attr('cx', 282).attr('cy', 10).attr('r', 5).attr('id', 'pickerL'); l.append("circle").attr("cx", 282).attr("cy", 10).attr("r", 5).attr("id", "pickerL");
l.on('mousemove', () => tip('Set palette lightness')); l.on("mousemove", () => tip("Set palette lightness"));
controls.selectAll('line').on('click', clickPickerControl); controls.selectAll("line").on("click", clickPickerControl);
controls.selectAll('circle').call(d3.drag().on('start', dragPickerControl)); controls.selectAll("circle").call(d3.drag().on("start", dragPickerControl));
const spaces = picker const spaces = picker
.append("foreignObject") .append("foreignObject")
@ -659,7 +658,7 @@ function updateSpaces() {
} }
function updatePickerColors() { function updatePickerColors() {
const colors = d3.select('#picker > #pickerColors').selectAll('rect'); const colors = d3.select("#picker > #pickerColors").selectAll("rect");
const number = colors.size(); const number = colors.size();
const h = getPickerControl(pickerH, 360); const h = getPickerControl(pickerH, 360);
@ -673,10 +672,12 @@ function updatePickerColors() {
}); });
} }
function openPicker(fill, callback, options = {allowHatching: true}) { function openPicker(fill, callback) {
createPicker(options.allowHatching); const picker = d3.select("#picker");
if (!picker.size()) createPicker();
d3.select("#pickerContainer").style("display", "block");
if (fill[0] === '#') { if (fill[0] === "#") {
const hsl = d3.hsl(fill); const hsl = d3.hsl(fill);
if (!isNaN(hsl.h)) setPickerControl(pickerH, hsl.h, 360); if (!isNaN(hsl.h)) setPickerControl(pickerH, hsl.h, 360);
if (!isNaN(hsl.s)) setPickerControl(pickerS, hsl.s, 1); if (!isNaN(hsl.s)) setPickerControl(pickerS, hsl.s, 1);
@ -695,10 +696,10 @@ function openPicker(fill, callback, options = {allowHatching: true}) {
} }
function setPickerControl(control, value, max) { function setPickerControl(control, value, max) {
const min = +control.previousSibling.getAttribute('x1'); const min = +control.previousSibling.getAttribute("x1");
const delta = +control.previousSibling.getAttribute('x2') - min; const delta = +control.previousSibling.getAttribute("x2") - min;
const percent = value / max; const percent = value / max;
control.setAttribute('cx', min + delta * percent); control.setAttribute("cx", min + delta * percent);
} }
function getPickerControl(control, max) { function getPickerControl(control, max) {
@ -724,7 +725,7 @@ function dragPicker() {
} }
function pickerFillClicked() { function pickerFillClicked() {
const fill = this.getAttribute('fill'); const fill = this.getAttribute("fill");
updateSelectedRect(fill); updateSelectedRect(fill);
openPicker.updateFill(); openPicker.updateFill();
@ -736,19 +737,19 @@ function pickerFillClicked() {
function clickPickerControl() { function clickPickerControl() {
const min = this.getScreenCTM().e; const min = this.getScreenCTM().e;
this.nextSibling.setAttribute('cx', d3.event.x - min); this.nextSibling.setAttribute("cx", d3.event.x - min);
updateSpaces(); updateSpaces();
updatePickerColors(); updatePickerColors();
openPicker.updateFill(); openPicker.updateFill();
} }
function dragPickerControl() { function dragPickerControl() {
const min = +this.previousSibling.getAttribute('x1'); const min = +this.previousSibling.getAttribute("x1");
const max = +this.previousSibling.getAttribute('x2'); const max = +this.previousSibling.getAttribute("x2");
d3.event.on("drag", function () { d3.event.on("drag", function () {
const x = Math.max(Math.min(d3.event.x, max), min); const x = Math.max(Math.min(d3.event.x, max), min);
this.setAttribute('cx', x); this.setAttribute("cx", x);
updateSpaces(); updateSpaces();
updatePickerColors(); updatePickerColors();
openPicker.updateFill(); openPicker.updateFill();
@ -799,9 +800,9 @@ function fog(id, path) {
.transition(fadeIn) .transition(fadeIn)
.attr("opacity", 1); .attr("opacity", 1);
} else { } else {
defs.select('#fog').append('path').attr('d', path).attr('id', id).attr('opacity', 1); defs.select("#fog").append("path").attr("d", path).attr("id", id).attr("opacity", 1);
const opacity = fogging.attr('opacity'); const opacity = fogging.attr("opacity");
fogging.style('display', 'block').attr('opacity', 0).transition(fadeIn).attr('opacity', opacity); fogging.style("display", "block").attr("opacity", 0).transition(fadeIn).attr("opacity", opacity);
} }
} }
@ -811,13 +812,13 @@ function unfog(id) {
if (!id || !el.size()) el = defs.select("#fog").selectAll("path"); if (!id || !el.size()) el = defs.select("#fog").selectAll("path");
el.remove(); el.remove();
if (!defs.selectAll('#fog path').size()) fogging.style('display', 'none'); if (!defs.selectAll("#fog path").size()) fogging.style("display", "none");
} }
function getFileName(dataType) { function getFileName(dataType) {
const formatTime = time => (time < 10 ? "0" + time : time); const formatTime = time => (time < 10 ? "0" + time : time);
const name = mapName.value; const name = mapName.value;
const type = dataType ? dataType + ' ' : ''; const type = dataType ? dataType + " " : "";
const date = new Date(); const date = new Date();
const year = date.getFullYear(); const year = date.getFullYear();
const month = formatTime(date.getMonth() + 1); const month = formatTime(date.getMonth() + 1);
@ -828,10 +829,10 @@ function getFileName(dataType) {
return name + " " + type + dateString; return name + " " + type + dateString;
} }
function downloadFile(data, name, type = 'text/plain') { function downloadFile(data, name, type = "text/plain") {
const dataBlob = new Blob([data], {type}); const dataBlob = new Blob([data], {type});
const url = window.URL.createObjectURL(dataBlob); const url = window.URL.createObjectURL(dataBlob);
const link = document.createElement('a'); const link = document.createElement("a");
link.download = name; link.download = name;
link.href = url; link.href = url;
link.click(); link.click();
@ -840,9 +841,9 @@ function downloadFile(data, name, type = 'text/plain') {
function uploadFile(el, callback) { function uploadFile(el, callback) {
const fileReader = new FileReader(); const fileReader = new FileReader();
fileReader.readAsText(el.files[0], 'UTF-8'); fileReader.readAsText(el.files[0], "UTF-8");
el.value = ''; el.value = "";
fileReader.onload = (loaded) => callback(loaded.target.result); fileReader.onload = loaded => callback(loaded.target.result);
} }
function getBBox(element) { function getBBox(element) {
@ -887,7 +888,7 @@ function highlightElement(element, zoom) {
function selectIcon(initial, callback) { function selectIcon(initial, callback) {
if (!callback) return; if (!callback) return;
$('#iconSelector').dialog(); $("#iconSelector").dialog();
const table = byId("iconTable"); const table = byId("iconTable");
const input = byId("iconInput"); const input = byId("iconInput");
@ -1190,22 +1191,3 @@ async function editReligions() {
const Editor = await import("../dynamic/editors/religions-editor.js?v=1.87.01"); const Editor = await import("../dynamic/editors/religions-editor.js?v=1.87.01");
Editor.open(); Editor.open();
} }
// dynamically loaded editors
async function editStates() {
if (customization) return;
const StateEditor = await import("../dynamic/editors/states-editor.js");
StateEditor.open();
}
async function editCultures() {
if (customization) return;
const Editor = await import("../dynamic/editors/cultures-editor.js?v=05062022");
Editor.open();
}
async function editReligions() {
if (customization) return;
const Editor = await import("../dynamic/editors/religions-editor.js?v=06062022");
Editor.open();
}

View file

@ -87,8 +87,8 @@ function editHeightmap(options) {
allowErosionBox.style.display = mode === "keep" ? "none" : "inline-block"; allowErosionBox.style.display = mode === "keep" ? "none" : "inline-block";
// show finalize button // show finalize button
if (!sessionStorage.getItem('noExitButtonAnimation')) { if (!sessionStorage.getItem("noExitButtonAnimation")) {
sessionStorage.setItem('noExitButtonAnimation', true); sessionStorage.setItem("noExitButtonAnimation", true);
exitCustomization.style.opacity = 0; exitCustomization.style.opacity = 0;
const width = 12 * uiSizeOutput.value * 11; const width = 12 * uiSizeOutput.value * 11;
exitCustomization.style.right = (svgWidth - width) / 2 + "px"; exitCustomization.style.right = (svgWidth - width) / 2 + "px";
@ -145,7 +145,7 @@ function editHeightmap(options) {
if (h >= 20) height = Math.pow(h - 18, +heightExponentInput.value); if (h >= 20) height = Math.pow(h - 18, +heightExponentInput.value);
else if (h < 20 && h > 0) height = ((h - 20) / h) * 50; else if (h < 20 && h > 0) height = ((h - 20) / h) * 50;
return rn(height * unitRatio) + ' ' + unit; return rn(height * unitRatio) + " " + unit;
} }
// Exit customization mode // Exit customization mode
@ -166,7 +166,7 @@ function editHeightmap(options) {
customizationMenu.style.display = "none"; customizationMenu.style.display = "none";
if (byId("options").querySelector(".tab > button.active").id === "toolsTab") toolsContent.style.display = "block"; if (byId("options").querySelector(".tab > button.active").id === "toolsTab") toolsContent.style.display = "block";
layersPreset.disabled = false; layersPreset.disabled = false;
exitCustomization.style.display = 'none'; // hide finalize button exitCustomization.style.display = "none"; // hide finalize button
restoreDefaultEvents(); restoreDefaultEvents();
clearMainTip(); clearMainTip();
closeDialogs(); closeDialogs();
@ -176,9 +176,9 @@ function editHeightmap(options) {
if (byId("canvas3d")) enterStandardView(); if (byId("canvas3d")) enterStandardView();
const mode = heightmapEditMode.innerHTML; const mode = heightmapEditMode.innerHTML;
if (mode === 'erase') regenerateErasedData(); if (mode === "erase") regenerateErasedData();
else if (mode === 'keep') restoreKeptData(); else if (mode === "keep") restoreKeptData();
else if (mode === 'risk') restoreRiskedData(); else if (mode === "risk") restoreRiskedData();
// restore initial layers // restore initial layers
//viewbox.select("#heights").remove(); //viewbox.select("#heights").remove();
@ -196,8 +196,8 @@ function editHeightmap(options) {
} }
function regenerateErasedData() { function regenerateErasedData() {
INFO && console.group('Edit Heightmap'); INFO && console.group("Edit Heightmap");
TIME && console.time('regenerateErasedData'); TIME && console.time("regenerateErasedData");
const erosionAllowed = allowErosion.checked; const erosionAllowed = allowErosion.checked;
markFeatures(); markFeatures();
@ -247,12 +247,12 @@ function editHeightmap(options) {
Military.generate(); Military.generate();
Markers.generate(); Markers.generate();
addZones(); addZones();
TIME && console.timeEnd('regenerateErasedData'); TIME && console.timeEnd("regenerateErasedData");
INFO && console.groupEnd('Edit Heightmap'); INFO && console.groupEnd("Edit Heightmap");
} }
function restoreKeptData() { function restoreKeptData() {
viewbox.selectAll('#landmass, #lakes').style('display', null); viewbox.selectAll("#landmass, #lakes").style("display", null);
for (const i of pack.cells.i) { for (const i of pack.cells.i) {
pack.cells.h[i] = grid.cells.h[pack.cells.g[i]]; pack.cells.h[i] = grid.cells.h[pack.cells.g[i]];
} }
@ -318,11 +318,11 @@ function editHeightmap(options) {
// recalculate zones to grid // recalculate zones to grid
zones.selectAll("g").each(function () { zones.selectAll("g").each(function () {
const zone = d3.select(this); const zone = d3.select(this);
const dataCells = zone.attr('data-cells'); const dataCells = zone.attr("data-cells");
const cells = dataCells ? dataCells.split(',').map((i) => +i) : []; const cells = dataCells ? dataCells.split(",").map(i => +i) : [];
const g = cells.map((i) => pack.cells.g[i]); const g = cells.map(i => pack.cells.g[i]);
zone.attr('data-cells', g); zone.attr("data-cells", g);
zone.selectAll('*').remove(); zone.selectAll("*").remove();
}); });
markFeatures(); markFeatures();
@ -404,7 +404,7 @@ function editHeightmap(options) {
for (const p of pack.provinces) { for (const p of pack.provinces) {
if (!p.i || p.removed) continue; if (!p.i || p.removed) continue;
const provCells = pack.cells.i.filter((i) => pack.cells.province[i] === p.i); const provCells = pack.cells.i.filter(i => pack.cells.province[i] === p.i);
if (!provCells.length) { if (!provCells.length) {
const state = p.state; const state = p.state;
const stateProvs = pack.states[state].provinces; const stateProvs = pack.states[state].provinces;
@ -438,9 +438,9 @@ function editHeightmap(options) {
// restore zones from grid // restore zones from grid
zones.selectAll("g").each(function () { zones.selectAll("g").each(function () {
const zone = d3.select(this); const zone = d3.select(this);
const g = zone.attr('data-cells'); const g = zone.attr("data-cells");
const gCells = g ? g.split(',').map((i) => +i) : []; const gCells = g ? g.split(",").map(i => +i) : [];
const cells = pack.cells.i.filter((i) => gCells.includes(pack.cells.g[i])); const cells = pack.cells.i.filter(i => gCells.includes(pack.cells.g[i]));
zone.attr("data-cells", cells); zone.attr("data-cells", cells);
zone.selectAll("*").remove(); zone.selectAll("*").remove();
@ -454,8 +454,8 @@ function editHeightmap(options) {
.attr("id", d => base + d); .attr("id", d => base + d);
}); });
TIME && console.timeEnd('restoreRiskedData'); TIME && console.timeEnd("restoreRiskedData");
INFO && console.groupEnd('Edit Heightmap'); INFO && console.groupEnd("Edit Heightmap");
} }
// trigger heightmap redraw and history update if at least 1 cell is changed // trigger heightmap redraw and history update if at least 1 cell is changed
@ -478,7 +478,7 @@ function editHeightmap(options) {
// draw or update heightmap // draw or update heightmap
function mockHeightmap() { function mockHeightmap() {
const data = renderOcean.checked ? grid.cells.i : grid.cells.i.filter((i) => grid.cells.h[i] >= 20); const data = renderOcean.checked ? grid.cells.i : grid.cells.i.filter(i => grid.cells.h[i] >= 20);
const scheme = getColorScheme(); const scheme = getColorScheme();
viewbox viewbox
.select("#heights") .select("#heights")
@ -600,12 +600,7 @@ function editHeightmap(options) {
if (!pressed) return; if (!pressed) return;
pressed.classList.remove("pressed"); pressed.classList.remove("pressed");
function exitBrushMode() { viewbox.style("cursor", "default").on(".drag", null);
const pressed = document.querySelector('#brushesButtons > button.pressed');
if (!pressed) return;
pressed.classList.remove('pressed');
viewbox.style('cursor', 'default').on('.drag', null);
removeCircle(); removeCircle();
byId("brushesSliders").style.display = "none"; byId("brushesSliders").style.display = "none";
} }
@ -627,17 +622,17 @@ function editHeightmap(options) {
const [x, y] = d3.mouse(this); const [x, y] = d3.mouse(this);
const start = findGridCell(x, y, grid); const start = findGridCell(x, y, grid);
d3.event.on('drag', () => { d3.event.on("drag", () => {
const p = d3.mouse(this); const p = d3.mouse(this);
moveCircle(p[0], p[1], r, '#333'); moveCircle(p[0], p[1], r, "#333");
if (~~d3.event.sourceEvent.timeStamp % 5 != 0) return; // slow down the edit if (~~d3.event.sourceEvent.timeStamp % 5 != 0) return; // slow down the edit
const inRadius = findGridAll(p[0], p[1], r); const inRadius = findGridAll(p[0], p[1], r);
const selection = changeOnlyLand.checked ? inRadius.filter((i) => grid.cells.h[i] >= 20) : inRadius; const selection = changeOnlyLand.checked ? inRadius.filter(i => grid.cells.h[i] >= 20) : inRadius;
if (selection && selection.length) changeHeightForSelection(selection, start); if (selection && selection.length) changeHeightForSelection(selection, start);
}); });
d3.event.on('end', updateHeightmap); d3.event.on("end", updateHeightmap);
} }
function changeHeightForSelection(s, start) { function changeHeightForSelection(s, start) {
@ -674,9 +669,9 @@ function editHeightmap(options) {
} }
function changeOnlyLandClick(e) { function changeOnlyLandClick(e) {
if (heightmapEditMode.innerHTML !== 'keep') return; if (heightmapEditMode.innerHTML !== "keep") return;
e.preventDefault(); e.preventDefault();
tip("You cannot change the coastline in 'Keep' edit mode", false, 'error'); tip("You cannot change the coastline in 'Keep' edit mode", false, "error");
} }
function rescale(v) { function rescale(v) {
@ -687,7 +682,7 @@ function editHeightmap(options) {
} }
function rescaleWithCondition() { function rescaleWithCondition() {
const range = rescaleLower.value + '-' + rescaleHigher.value; const range = rescaleLower.value + "-" + rescaleHigher.value;
const operator = conditionSign.value; const operator = conditionSign.value;
const operand = rescaleModifier.valueAsNumber; const operand = rescaleModifier.valueAsNumber;
if (Number.isNaN(operand)) return tip("Operand should be a number", false, "error"); if (Number.isNaN(operand)) return tip("Operand should be a number", false, "error");
@ -725,7 +720,7 @@ function editHeightmap(options) {
return tip("Heightmap is already cleared, please do not click twice if not required", false, "error"); return tip("Heightmap is already cleared, please do not click twice if not required", false, "error");
grid.cells.h = new Uint8Array(grid.cells.i.length); grid.cells.h = new Uint8Array(grid.cells.i.length);
viewbox.select('#heights').selectAll('*').remove(); viewbox.select("#heights").selectAll("*").remove();
updateHistory(); updateHistory();
} }
} }
@ -762,9 +757,9 @@ function editHeightmap(options) {
$body.dataset.changed = 1; $body.dataset.changed = 1;
return; return;
} }
if (el.classList.contains('icon-check-empty')) { if (el.classList.contains("icon-check-empty")) {
el.classList.add('icon-check'); el.classList.add("icon-check");
el.classList.remove('icon-check-empty'); el.classList.remove("icon-check-empty");
el.parentElement.style.opacity = 1; el.parentElement.style.opacity = 1;
return; return;
} }
@ -928,7 +923,7 @@ function editHeightmap(options) {
} }
function setRange(event) { function setRange(event) {
if (event.target.value !== 'interval') return; if (event.target.value !== "interval") return;
prompt("Set a height interval. Avoid space, use hyphen as a separator", {default: "17-20"}, v => { prompt("Set a height interval. Avoid space, use hyphen as a separator", {default: "17-20"}, v => {
const opt = document.createElement("option"); const opt = document.createElement("option");
@ -982,14 +977,11 @@ function editHeightmap(options) {
const steps = byId("templateBody").querySelectorAll("#templateBody > div"); const steps = byId("templateBody").querySelectorAll("#templateBody > div");
if (!steps.length) return; if (!steps.length) return;
grid.cells.h = createTypedArray({maxValue: 100, length: grid.points.length});
HeightmapGenerator.setGraph(grid);
restartHistory();
const seed = byId("templateSeed").value; const seed = byId("templateSeed").value;
if (seed) Math.random = aleaPRNG(seed); if (seed) Math.random = aleaPRNG(seed);
HeightmapGenerator.resetHeights(); grid.cells.h = createTypedArray({maxValue: 100, length: grid.points.length});
HeightmapGenerator.setGraph(grid);
restartHistory(); restartHistory();
for (const step of steps) { for (const step of steps) {
@ -1027,10 +1019,10 @@ function editHeightmap(options) {
function downloadTemplate() { function downloadTemplate() {
const body = byId("templateBody"); const body = byId("templateBody");
body.dataset.changed = 0; body.dataset.changed = 0;
const steps = body.querySelectorAll('#templateBody > div'); const steps = body.querySelectorAll("#templateBody > div");
if (!steps.length) return; if (!steps.length) return;
let data = ''; let data = "";
for (const s of steps) { for (const s of steps) {
if (s.style.opacity === "0.5") continue; if (s.style.opacity === "0.5") continue;
@ -1042,7 +1034,7 @@ function editHeightmap(options) {
data += `${type} ${count} ${arg3} ${x} ${y}\r\n`; data += `${type} ${count} ${arg3} ${x} ${y}\r\n`;
} }
const name = 'template_' + Date.now() + '.txt'; const name = "template_" + Date.now() + ".txt";
downloadFile(data, name); downloadFile(data, name);
} }
@ -1065,7 +1057,7 @@ function editHeightmap(options) {
function openImageConverter() { function openImageConverter() {
if ($("#imageConverter").is(":visible")) return; if ($("#imageConverter").is(":visible")) return;
imageToLoad.click(); imageToLoad.click();
closeDialogs('#imageConverter'); closeDialogs("#imageConverter");
$("#imageConverter").dialog({ $("#imageConverter").dialog({
title: "Image Converter", title: "Image Converter",
@ -1077,8 +1069,8 @@ function editHeightmap(options) {
}); });
// create canvas for image // create canvas for image
const canvas = document.createElement('canvas'); const canvas = document.createElement("canvas");
canvas.id = 'canvas'; canvas.id = "canvas";
canvas.width = graphWidth; canvas.width = graphWidth;
canvas.height = graphHeight; canvas.height = graphHeight;
document.body.insertBefore(canvas, optionsContainer); document.body.insertBefore(canvas, optionsContainer);
@ -1089,7 +1081,7 @@ function editHeightmap(options) {
// remove all heights // remove all heights
grid.cells.h = new Uint8Array(grid.cells.i.length); grid.cells.h = new Uint8Array(grid.cells.i.length);
viewbox.select('#heights').selectAll('*').remove(); viewbox.select("#heights").selectAll("*").remove();
updateHistory(); updateHistory();
if (modules.openImageConverter) return; if (modules.openImageConverter) return;
@ -1126,7 +1118,7 @@ function editHeightmap(options) {
}); });
function showPalleteHeight() { function showPalleteHeight() {
const height = +this.getAttribute('data-color'); const height = +this.getAttribute("data-color");
colorsSelectValue.innerHTML = height; colorsSelectValue.innerHTML = height;
colorsSelectFriendly.innerHTML = getHeight(height); colorsSelectFriendly.innerHTML = getHeight(height);
const former = imageConverterPalette.querySelector(".hoveredColor"); const former = imageConverterPalette.querySelector(".hoveredColor");
@ -1136,7 +1128,7 @@ function editHeightmap(options) {
function loadImage() { function loadImage() {
const file = this.files[0]; const file = this.files[0];
this.value = ''; // reset input value to get triggered if the file is re-uploaded this.value = ""; // reset input value to get triggered if the file is re-uploaded
const reader = new FileReader(); const reader = new FileReader();
const img = new Image(); const img = new Image();
@ -1167,11 +1159,11 @@ function editHeightmap(options) {
const data = q.reduce(sampleCanvas); const data = q.reduce(sampleCanvas);
const pallete = q.palette(true); const pallete = q.palette(true);
viewbox.select('#heights').selectAll('*').remove(); viewbox.select("#heights").selectAll("*").remove();
d3.select('#imageConverter').selectAll('div.color-div').remove(); d3.select("#imageConverter").selectAll("div.color-div").remove();
colorsSelect.style.display = 'block'; colorsSelect.style.display = "block";
colorsUnassigned.style.display = 'block'; colorsUnassigned.style.display = "block";
colorsAssigned.style.display = 'none'; colorsAssigned.style.display = "none";
sampleCanvas.remove(); // no need to keep sampleCanvas.remove(); // no need to keep
viewbox viewbox
@ -1199,27 +1191,27 @@ function editHeightmap(options) {
} }
function mapClicked() { function mapClicked() {
const fill = this.getAttribute('fill'); const fill = this.getAttribute("fill");
const palleteColor = imageConverter.querySelector(`div[data-color="${fill}"]`); const palleteColor = imageConverter.querySelector(`div[data-color="${fill}"]`);
palleteColor.click(); palleteColor.click();
} }
function colorClicked() { function colorClicked() {
viewbox.select('#heights').selectAll('.selectedCell').attr('class', null); viewbox.select("#heights").selectAll(".selectedCell").attr("class", null);
const unselect = this.classList.contains('selectedColor'); const unselect = this.classList.contains("selectedColor");
const selectedColor = imageConverter.querySelector('div.selectedColor'); const selectedColor = imageConverter.querySelector("div.selectedColor");
if (selectedColor) selectedColor.classList.remove('selectedColor'); if (selectedColor) selectedColor.classList.remove("selectedColor");
const hoveredColor = imageConverterPalette.querySelector('div.hoveredColor'); const hoveredColor = imageConverterPalette.querySelector("div.hoveredColor");
if (hoveredColor) hoveredColor.classList.remove('hoveredColor'); if (hoveredColor) hoveredColor.classList.remove("hoveredColor");
colorsSelectValue.innerHTML = colorsSelectFriendly.innerHTML = 0; colorsSelectValue.innerHTML = colorsSelectFriendly.innerHTML = 0;
if (unselect) return; if (unselect) return;
this.classList.add('selectedColor'); this.classList.add("selectedColor");
if (this.dataset.height) { if (this.dataset.height) {
const height = +this.dataset.height; const height = +this.dataset.height;
imageConverterPalette.querySelector(`div[data-color="${height}"]`).classList.add('hoveredColor'); imageConverterPalette.querySelector(`div[data-color="${height}"]`).classList.add("hoveredColor");
colorsSelectValue.innerHTML = height; colorsSelectValue.innerHTML = height;
colorsSelectFriendly.innerHTML = getHeight(height); colorsSelectFriendly.innerHTML = getHeight(height);
} }
@ -1237,8 +1229,8 @@ function editHeightmap(options) {
const rgb = color(1 - (height < 20 ? height - 5 : height) / 100); const rgb = color(1 - (height < 20 ? height - 5 : height) / 100);
const selectedColor = imageConverter.querySelector("div.selectedColor"); const selectedColor = imageConverter.querySelector("div.selectedColor");
selectedColor.style.backgroundColor = rgb; selectedColor.style.backgroundColor = rgb;
selectedColor.setAttribute('data-color', rgb); selectedColor.setAttribute("data-color", rgb);
selectedColor.setAttribute('data-height', height); selectedColor.setAttribute("data-height", height);
viewbox viewbox
.select("#heights") .select("#heights")
@ -1291,7 +1283,7 @@ function editHeightmap(options) {
}; };
const assinged = []; // store assigned heights const assinged = []; // store assigned heights
unassigned.forEach((el) => { unassigned.forEach(el => {
const clr = el.dataset.color; const clr = el.dataset.color;
const height = const height =
type === "hue" ? getHeightByHue(clr) : type === "lum" ? getHeightByLum(clr) : getHeightByScheme(clr); type === "hue" ? getHeightByHue(clr) : type === "lum" ? getHeightByLum(clr) : getHeightByScheme(clr);
@ -1351,7 +1343,7 @@ function editHeightmap(options) {
grid.cells.h[i] = height; grid.cells.h[i] = height;
}); });
viewbox.select('#heights').selectAll('polygon').remove(); viewbox.select("#heights").selectAll("polygon").remove();
updateHeightmap(); updateHeightmap();
restoreImageConverterState(); restoreImageConverterState();
} }
@ -1373,9 +1365,9 @@ function editHeightmap(options) {
colorsAssigned.style.display = "none"; colorsAssigned.style.display = "none";
colorsUnassigned.style.display = "none"; colorsUnassigned.style.display = "none";
colorsSelectValue.innerHTML = colorsSelectFriendly.innerHTML = 0; colorsSelectValue.innerHTML = colorsSelectFriendly.innerHTML = 0;
viewbox.style('cursor', 'default').on('.drag', null); viewbox.style("cursor", "default").on(".drag", null);
tip('Heightmap edit mode is active. Click on "Exit Customization" to finalize the heightmap', true); tip('Heightmap edit mode is active. Click on "Exit Customization" to finalize the heightmap', true);
$('#imageConverter').dialog('destroy'); $("#imageConverter").dialog("destroy");
openBrushesPanel(); openBrushesPanel();
} }
@ -1412,8 +1404,8 @@ function editHeightmap(options) {
byId("preview").remove(); byId("preview").remove();
return; return;
} }
const preview = document.createElement('canvas'); const preview = document.createElement("canvas");
preview.id = 'preview'; preview.id = "preview";
preview.width = grid.cellsX; preview.width = grid.cellsX;
preview.height = grid.cellsY; preview.height = grid.cellsY;
document.body.insertBefore(preview, optionsContainer); document.body.insertBefore(preview, optionsContainer);
@ -1463,4 +1455,3 @@ function editHeightmap(options) {
}; };
} }
} }
}

View file

@ -1,5 +1,5 @@
// UI module stub to control map layers // UI module stub to control map layers
'use strict'; "use strict";
let presets = {}; // global object let presets = {}; // global object
restoreCustomPresets(); // run on-load restoreCustomPresets(); // run on-load
@ -85,7 +85,7 @@ function getDefaultPresets() {
function restoreCustomPresets() { function restoreCustomPresets() {
presets = getDefaultPresets(); presets = getDefaultPresets();
const storedPresets = JSON.parse(localStorage.getItem('presets')); const storedPresets = JSON.parse(localStorage.getItem("presets"));
if (!storedPresets) return; if (!storedPresets) return;
for (const preset in storedPresets) { for (const preset in storedPresets) {
@ -98,7 +98,7 @@ function restoreCustomPresets() {
// run on map generation // run on map generation
function applyPreset() { function applyPreset() {
const preset = localStorage.getItem('preset') || document.getElementById('layersPreset').value; const preset = localStorage.getItem("preset") || document.getElementById("layersPreset").value;
changePreset(preset); changePreset(preset);
} }
@ -113,12 +113,12 @@ function changePreset(preset) {
else if (!layers.includes(e.id) && layerIsOn(e.id)) e.click(); else if (!layers.includes(e.id) && layerIsOn(e.id)) e.click();
}); });
layersPreset.value = preset; layersPreset.value = preset;
localStorage.setItem('preset', preset); localStorage.setItem("preset", preset);
const isDefault = getDefaultPresets()[preset]; const isDefault = getDefaultPresets()[preset];
removePresetButton.style.display = isDefault ? 'none' : 'inline-block'; removePresetButton.style.display = isDefault ? "none" : "inline-block";
savePresetButton.style.display = 'none'; savePresetButton.style.display = "none";
if (document.getElementById('canvas3d')) setTimeout(ThreeD.update(), 400); if (document.getElementById("canvas3d")) setTimeout(ThreeD.update(), 400);
} }
function savePreset() { function savePreset() {
@ -127,24 +127,24 @@ function savePreset() {
.map(node => node.id) .map(node => node.id)
.sort(); .sort();
layersPreset.add(new Option(preset, preset, false, true)); layersPreset.add(new Option(preset, preset, false, true));
localStorage.setItem('presets', JSON.stringify(presets)); localStorage.setItem("presets", JSON.stringify(presets));
localStorage.setItem('preset', preset); localStorage.setItem("preset", preset);
removePresetButton.style.display = 'inline-block'; removePresetButton.style.display = "inline-block";
savePresetButton.style.display = 'none'; savePresetButton.style.display = "none";
}); });
} }
function removePreset() { function removePreset() {
const preset = layersPreset.value; const preset = layersPreset.value;
delete presets[preset]; delete presets[preset];
const index = Array.from(layersPreset.options).findIndex((o) => o.value === preset); const index = Array.from(layersPreset.options).findIndex(o => o.value === preset);
layersPreset.options.remove(index); layersPreset.options.remove(index);
layersPreset.value = 'custom'; layersPreset.value = "custom";
removePresetButton.style.display = 'none'; removePresetButton.style.display = "none";
savePresetButton.style.display = 'inline-block'; savePresetButton.style.display = "inline-block";
localStorage.setItem('presets', JSON.stringify(presets)); localStorage.setItem("presets", JSON.stringify(presets));
localStorage.removeItem('preset'); localStorage.removeItem("preset");
} }
function getCurrentPreset() { function getCurrentPreset() {
@ -156,14 +156,14 @@ function getCurrentPreset() {
for (const preset in presets) { for (const preset in presets) {
if (JSON.stringify(presets[preset]) !== JSON.stringify(layers)) continue; if (JSON.stringify(presets[preset]) !== JSON.stringify(layers)) continue;
layersPreset.value = preset; layersPreset.value = preset;
removePresetButton.style.display = defaultPresets[preset] ? 'none' : 'inline-block'; removePresetButton.style.display = defaultPresets[preset] ? "none" : "inline-block";
savePresetButton.style.display = 'none'; savePresetButton.style.display = "none";
return; return;
} }
layersPreset.value = 'custom'; layersPreset.value = "custom";
removePresetButton.style.display = 'none'; removePresetButton.style.display = "none";
savePresetButton.style.display = 'inline-block'; savePresetButton.style.display = "inline-block";
} }
// run on map regeneration // run on map regeneration
@ -193,14 +193,14 @@ function restoreLayers() {
function toggleHeight(event) { function toggleHeight(event) {
if (customization === 1) { if (customization === 1) {
tip('You cannot turn off the layer when heightmap is in edit mode', false, 'error'); tip("You cannot turn off the layer when heightmap is in edit mode", false, "error");
return; return;
} }
if (!terrs.selectAll('*').size()) { if (!terrs.selectAll("*").size()) {
turnButtonOn('toggleHeight'); turnButtonOn("toggleHeight");
drawHeightmap(); drawHeightmap();
if (event && isCtrlClick(event)) editStyle('terrs'); if (event && isCtrlClick(event)) editStyle("terrs");
} else { } else {
if (event && isCtrlClick(event)) { if (event && isCtrlClick(event)) {
editStyle("terrs"); editStyle("terrs");
@ -218,7 +218,7 @@ function drawHeightmap() {
const {cells, vertices} = pack; const {cells, vertices} = pack;
const n = cells.i.length; const n = cells.i.length;
const used = new Uint8Array(cells.i.length); const used = new Uint8Array(cells.i.length);
const paths = new Array(101).fill(''); const paths = new Array(101).fill("");
const scheme = getColorScheme(terrs.attr("scheme")); const scheme = getColorScheme(terrs.attr("scheme"));
const terracing = terrs.attr("terracing") / 10; // add additional shifted darker layer for pseudo-3d effect const terracing = terrs.attr("terracing") / 10; // add additional shifted darker layer for pseudo-3d effect
@ -247,12 +247,12 @@ function drawHeightmap() {
if (currentLayer > 100) break; // no layers possible with height > 100 if (currentLayer > 100) break; // no layers possible with height > 100
if (h < currentLayer) continue; if (h < currentLayer) continue;
if (used[i]) continue; // already marked if (used[i]) continue; // already marked
const onborder = cells.c[i].some((n) => cells.h[n] < h); const onborder = cells.c[i].some(n => cells.h[n] < h);
if (!onborder) continue; if (!onborder) continue;
const vertex = cells.v[i].find((v) => vertices.c[v].some((i) => cells.h[i] < h)); const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.h[i] < h));
const chain = connectVertices(vertex, h); const chain = connectVertices(vertex, h);
if (chain.length < 3) continue; if (chain.length < 3) continue;
const points = simplifyLine(chain).map((v) => vertices.p[v]); const points = simplifyLine(chain).map(v => vertices.p[v]);
paths[h] += round(lineGen(points)); paths[h] += round(lineGen(points));
} }
@ -305,7 +305,7 @@ function drawHeightmap() {
return chain.filter((d, i) => i % n === 0); return chain.filter((d, i) => i % n === 0);
} }
TIME && console.timeEnd('drawHeightmap'); TIME && console.timeEnd("drawHeightmap");
} }
function getColorScheme(scheme) { function getColorScheme(scheme) {
@ -321,10 +321,10 @@ function getColor(value, scheme = getColorScheme()) {
} }
function toggleTemp(event) { function toggleTemp(event) {
if (!temperature.selectAll('*').size()) { if (!temperature.selectAll("*").size()) {
turnButtonOn('toggleTemp'); turnButtonOn("toggleTemp");
drawTemp(); drawTemp();
if (event && isCtrlClick(event)) editStyle('temperature'); if (event && isCtrlClick(event)) editStyle("temperature");
} else { } else {
if (event && isCtrlClick(event)) { if (event && isCtrlClick(event)) {
editStyle("temperature"); editStyle("temperature");
@ -336,8 +336,8 @@ function toggleTemp(event) {
} }
function drawTemp() { function drawTemp() {
TIME && console.time('drawTemp'); TIME && console.time("drawTemp");
temperature.selectAll('*').remove(); temperature.selectAll("*").remove();
lineGen.curve(d3.curveBasisClosed); lineGen.curve(d3.curveBasisClosed);
const scheme = d3.scaleSequential(d3.interpolateSpectral); const scheme = d3.scaleSequential(d3.interpolateSpectral);
const tMax = +temperatureEquatorOutput.max, const tMax = +temperatureEquatorOutput.max,
@ -366,7 +366,7 @@ function drawTemp() {
const chain = connectVertices(start, t); // vertices chain to form a path const chain = connectVertices(start, t); // vertices chain to form a path
const relaxed = chain.filter((v, i) => i % 4 === 0 || vertices.c[v].some(c => c >= n)); const relaxed = chain.filter((v, i) => i % 4 === 0 || vertices.c[v].some(c => c >= n));
if (relaxed.length < 6) continue; if (relaxed.length < 6) continue;
const points = relaxed.map((v) => vertices.p[v]); const points = relaxed.map(v => vertices.p[v]);
chains.push([t, points]); chains.push([t, points]);
addLabel(points, t); addLabel(points, t);
} }
@ -401,8 +401,8 @@ function drawTemp() {
// find cell with temp < isotherm and find vertex to start path detection // find cell with temp < isotherm and find vertex to start path detection
function findStart(i, t) { function findStart(i, t) {
if (cells.b[i]) return cells.v[i].find((v) => vertices.c[v].some((c) => c >= n)); // map border cell if (cells.b[i]) return cells.v[i].find(v => vertices.c[v].some(c => c >= n)); // map border cell
return cells.v[i][cells.c[i].findIndex((c) => cells.temp[c] < t || !cells.temp[c])]; return cells.v[i][cells.c[i].findIndex(c => cells.temp[c] < t || !cells.temp[c])];
} }
function addLabel(points, t) { function addLabel(points, t) {
@ -448,14 +448,14 @@ function drawTemp() {
chain.push(start); chain.push(start);
return chain; return chain;
} }
TIME && console.timeEnd('drawTemp'); TIME && console.timeEnd("drawTemp");
} }
function toggleBiomes(event) { function toggleBiomes(event) {
if (!biomes.selectAll('path').size()) { if (!biomes.selectAll("path").size()) {
turnButtonOn('toggleBiomes'); turnButtonOn("toggleBiomes");
drawBiomes(); drawBiomes();
if (event && isCtrlClick(event)) editStyle('biomes'); if (event && isCtrlClick(event)) editStyle("biomes");
} else { } else {
if (event && isCtrlClick(event)) { if (event && isCtrlClick(event)) {
editStyle("biomes"); editStyle("biomes");
@ -472,15 +472,15 @@ function drawBiomes() {
vertices = pack.vertices, vertices = pack.vertices,
n = cells.i.length; n = cells.i.length;
const used = new Uint8Array(cells.i.length); const used = new Uint8Array(cells.i.length);
const paths = new Array(biomesData.i.length).fill(''); const paths = new Array(biomesData.i.length).fill("");
for (const i of cells.i) { for (const i of cells.i) {
if (!cells.biome[i]) continue; // no need to mark marine biome (liquid water) if (!cells.biome[i]) continue; // no need to mark marine biome (liquid water)
if (used[i]) continue; // already marked if (used[i]) continue; // already marked
const b = cells.biome[i]; const b = cells.biome[i];
const onborder = cells.c[i].some((n) => cells.biome[n] !== b); const onborder = cells.c[i].some(n => cells.biome[n] !== b);
if (!onborder) continue; if (!onborder) continue;
const edgeVerticle = cells.v[i].find((v) => vertices.c[v].some((i) => cells.biome[i] !== b)); const edgeVerticle = cells.v[i].find(v => vertices.c[v].some(i => cells.biome[i] !== b));
const chain = connectVertices(edgeVerticle, b); const chain = connectVertices(edgeVerticle, b);
if (chain.length < 3) continue; if (chain.length < 3) continue;
const points = clipPoly( const points = clipPoly(
@ -525,10 +525,10 @@ function drawBiomes() {
} }
function togglePrec(event) { function togglePrec(event) {
if (!prec.selectAll('circle').size()) { if (!prec.selectAll("circle").size()) {
turnButtonOn('togglePrec'); turnButtonOn("togglePrec");
drawPrec(); drawPrec();
if (event && isCtrlClick(event)) editStyle('prec'); if (event && isCtrlClick(event)) editStyle("prec");
} else { } else {
if (event && isCtrlClick(event)) { if (event && isCtrlClick(event)) {
editStyle("prec"); editStyle("prec");
@ -536,9 +536,9 @@ function togglePrec(event) {
} }
turnButtonOff("togglePrec"); turnButtonOff("togglePrec");
const hide = d3.transition().duration(1000).ease(d3.easeSinIn); const hide = d3.transition().duration(1000).ease(d3.easeSinIn);
prec.selectAll('text').attr('opacity', 1).transition(hide).attr('opacity', 0); prec.selectAll("text").attr("opacity", 1).transition(hide).attr("opacity", 0);
prec.selectAll('circle').transition(hide).attr('r', 0).remove(); prec.selectAll("circle").transition(hide).attr("r", 0).remove();
prec.transition().delay(1000).style('display', 'none'); prec.transition().delay(1000).style("display", "none");
} }
} }
@ -548,7 +548,7 @@ function drawPrec() {
prec.style("display", "block"); prec.style("display", "block");
const show = d3.transition().duration(800).ease(d3.easeSinIn); const show = d3.transition().duration(800).ease(d3.easeSinIn);
prec.selectAll('text').attr('opacity', 0).transition(show).attr('opacity', 1); prec.selectAll("text").attr("opacity", 0).transition(show).attr("opacity", 1);
const cellsNumberModifier = (pointsInput.dataset.cells / 10000) ** 0.25; const cellsNumberModifier = (pointsInput.dataset.cells / 10000) ** 0.25;
const data = cells.i.filter(i => cells.h[i] >= 20 && cells.prec[i]); const data = cells.i.filter(i => cells.h[i] >= 20 && cells.prec[i]);
@ -567,10 +567,10 @@ function drawPrec() {
} }
function togglePopulation(event) { function togglePopulation(event) {
if (!population.selectAll('line').size()) { if (!population.selectAll("line").size()) {
turnButtonOn('togglePopulation'); turnButtonOn("togglePopulation");
drawPopulation(); drawPopulation();
if (event && isCtrlClick(event)) editStyle('population'); if (event && isCtrlClick(event)) editStyle("population");
} else { } else {
if (event && isCtrlClick(event)) { if (event && isCtrlClick(event)) {
editStyle("population"); editStyle("population");
@ -580,7 +580,7 @@ function togglePopulation(event) {
const isD3data = population.select("line").datum(); const isD3data = population.select("line").datum();
if (!isD3data) { if (!isD3data) {
// just remove // just remove
population.selectAll('line').remove(); population.selectAll("line").remove();
} else { } else {
// remove with animation // remove with animation
const hide = d3.transition().duration(1000).ease(d3.easeSinIn); const hide = d3.transition().duration(1000).ease(d3.easeSinIn);
@ -642,10 +642,10 @@ function drawPopulation(event) {
} }
function toggleCells(event) { function toggleCells(event) {
if (!cells.selectAll('path').size()) { if (!cells.selectAll("path").size()) {
turnButtonOn('toggleCells'); turnButtonOn("toggleCells");
drawCells(); drawCells();
if (event && isCtrlClick(event)) editStyle('cells'); if (event && isCtrlClick(event)) editStyle("cells");
} else { } else {
if (event && isCtrlClick(event)) { if (event && isCtrlClick(event)) {
editStyle("cells"); editStyle("cells");
@ -657,7 +657,7 @@ function toggleCells(event) {
} }
function drawCells() { function drawCells() {
cells.selectAll('path').remove(); cells.selectAll("path").remove();
const data = customization === 1 ? grid.cells.i : pack.cells.i; const data = customization === 1 ? grid.cells.i : pack.cells.i;
const polygon = customization === 1 ? getGridPolygon : getPackPolygon; const polygon = customization === 1 ? getGridPolygon : getPackPolygon;
let path = ""; let path = "";
@ -701,19 +701,19 @@ function drawIce() {
if (t <= shieldMin) { if (t <= shieldMin) {
// very cold: ice shield // very cold: ice shield
if (used[i]) continue; // already rendered if (used[i]) continue; // already rendered
const onborder = cells.c[i].some((n) => temp[n] > shieldMin); const onborder = cells.c[i].some(n => temp[n] > shieldMin);
if (!onborder) continue; // need to start from onborder cell if (!onborder) continue; // need to start from onborder cell
const vertex = cells.v[i].find((v) => vertices.c[v].some((i) => temp[i] > shieldMin)); const vertex = cells.v[i].find(v => vertices.c[v].some(i => temp[i] > shieldMin));
const chain = connectVertices(vertex); const chain = connectVertices(vertex);
if (chain.length < 3) continue; if (chain.length < 3) continue;
const points = clipPoly(chain.map((v) => vertices.p[v])); const points = clipPoly(chain.map(v => vertices.p[v]));
ice.append('polygon').attr('points', points).attr('type', 'iceShield'); ice.append("polygon").attr("points", points).attr("type", "iceShield");
continue; continue;
} }
// mildly cold: iceberd // mildly cold: iceberd
if (P(normalize(t, -7, 2.5))) continue; // t[-5; 2] cold: skip some cells if (P(normalize(t, -7, 2.5))) continue; // t[-5; 2] cold: skip some cells
if (grid.features[cells.f[i]].type === 'lake') continue; // lake: no icebers if (grid.features[cells.f[i]].type === "lake") continue; // lake: no icebers
let size = (6.5 + t) / 10; // iceberg size: 0 = full size, 1 = zero size let size = (6.5 + t) / 10; // iceberg size: 0 = full size, 1 = zero size
if (cells.t[i] === -1) size *= 1.3; // coasline: smaller icebers if (cells.t[i] === -1) size *= 1.3; // coasline: smaller icebers
size = Math.min(size * (0.4 + rand() * 1.2), 0.95); // randomize iceberg size size = Math.min(size * (0.4 + rand() * 1.2), 0.95); // randomize iceberg size
@ -755,12 +755,12 @@ function drawIce() {
} }
function toggleCultures(event) { function toggleCultures(event) {
const cultures = pack.cultures.filter((c) => c.i && !c.removed); const cultures = pack.cultures.filter(c => c.i && !c.removed);
const empty = !cults.selectAll('path').size(); const empty = !cults.selectAll("path").size();
if (empty && cultures.length) { if (empty && cultures.length) {
turnButtonOn('toggleCultures'); turnButtonOn("toggleCultures");
drawCultures(); drawCultures();
if (event && isCtrlClick(event)) editStyle('cults'); if (event && isCtrlClick(event)) editStyle("cults");
} else { } else {
if (event && isCtrlClick(event)) { if (event && isCtrlClick(event)) {
editStyle("cults"); editStyle("cults");
@ -772,26 +772,26 @@ function toggleCultures(event) {
} }
function drawCultures() { function drawCultures() {
TIME && console.time('drawCultures'); TIME && console.time("drawCultures");
cults.selectAll("path").remove(); cults.selectAll("path").remove();
const {cells, vertices, cultures} = pack; const {cells, vertices, cultures} = pack;
const n = cells.i.length; const n = cells.i.length;
const used = new Uint8Array(cells.i.length); const used = new Uint8Array(cells.i.length);
const paths = new Array(cultures.length).fill(''); const paths = new Array(cultures.length).fill("");
for (const i of cells.i) { for (const i of cells.i) {
if (!cells.culture[i]) continue; if (!cells.culture[i]) continue;
if (used[i]) continue; if (used[i]) continue;
used[i] = 1; used[i] = 1;
const c = cells.culture[i]; const c = cells.culture[i];
const onborder = cells.c[i].some((n) => cells.culture[n] !== c); const onborder = cells.c[i].some(n => cells.culture[n] !== c);
if (!onborder) continue; if (!onborder) continue;
const vertex = cells.v[i].find((v) => vertices.c[v].some((i) => cells.culture[i] !== c)); const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.culture[i] !== c));
const chain = connectVertices(vertex, c); const chain = connectVertices(vertex, c);
if (chain.length < 3) continue; if (chain.length < 3) continue;
const points = chain.map((v) => vertices.p[v]); const points = chain.map(v => vertices.p[v]);
paths[c] += 'M' + points.join('L') + 'Z'; paths[c] += "M" + points.join("L") + "Z";
} }
const data = paths.map((p, i) => [p, i]).filter(d => d[0].length > 10); const data = paths.map((p, i) => [p, i]).filter(d => d[0].length > 10);
@ -826,15 +826,15 @@ function drawCultures() {
} }
return chain; return chain;
} }
TIME && console.timeEnd('drawCultures'); TIME && console.timeEnd("drawCultures");
} }
function toggleReligions(event) { function toggleReligions(event) {
const religions = pack.religions.filter((r) => r.i && !r.removed); const religions = pack.religions.filter(r => r.i && !r.removed);
if (!relig.selectAll('path').size() && religions.length) { if (!relig.selectAll("path").size() && religions.length) {
turnButtonOn('toggleReligions'); turnButtonOn("toggleReligions");
drawReligions(); drawReligions();
if (event && isCtrlClick(event)) editStyle('relig'); if (event && isCtrlClick(event)) editStyle("relig");
} else { } else {
if (event && isCtrlClick(event)) { if (event && isCtrlClick(event)) {
editStyle("relig"); editStyle("relig");
@ -846,7 +846,7 @@ function toggleReligions(event) {
} }
function drawReligions() { function drawReligions() {
TIME && console.time('drawReligions'); TIME && console.time("drawReligions");
relig.selectAll("path").remove(); relig.selectAll("path").remove();
const {cells, vertices, religions} = pack; const {cells, vertices, religions} = pack;
@ -854,21 +854,21 @@ function drawReligions() {
const used = new Uint8Array(cells.i.length); const used = new Uint8Array(cells.i.length);
const vArray = new Array(religions.length); // store vertices array const vArray = new Array(religions.length); // store vertices array
const body = new Array(religions.length).fill(''); // store path around each religion const body = new Array(religions.length).fill(""); // store path around each religion
const gap = new Array(religions.length).fill(''); // store path along water for each religion to fill the gaps const gap = new Array(religions.length).fill(""); // store path along water for each religion to fill the gaps
for (const i of cells.i) { for (const i of cells.i) {
if (!cells.religion[i]) continue; if (!cells.religion[i]) continue;
if (used[i]) continue; if (used[i]) continue;
used[i] = 1; used[i] = 1;
const r = cells.religion[i]; const r = cells.religion[i];
const onborder = cells.c[i].filter((n) => cells.religion[n] !== r); const onborder = cells.c[i].filter(n => cells.religion[n] !== r);
if (!onborder.length) continue; if (!onborder.length) continue;
const borderWith = cells.c[i].map((c) => cells.religion[c]).find((n) => n !== r); const borderWith = cells.c[i].map(c => cells.religion[c]).find(n => n !== r);
const vertex = cells.v[i].find((v) => vertices.c[v].some((i) => cells.religion[i] === borderWith)); const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.religion[i] === borderWith));
const chain = connectVertices(vertex, r, borderWith); const chain = connectVertices(vertex, r, borderWith);
if (chain.length < 3) continue; if (chain.length < 3) continue;
const points = chain.map((v) => vertices.p[v[0]]); const points = chain.map(v => vertices.p[v[0]]);
if (!vArray[r]) vArray[r] = []; if (!vArray[r]) vArray[r] = [];
vArray[r].push(points); vArray[r].push(points);
body[r] += "M" + points.join("L") + "Z"; body[r] += "M" + points.join("L") + "Z";
@ -938,15 +938,15 @@ function drawReligions() {
} }
return chain; return chain;
} }
TIME && console.timeEnd('drawReligions'); TIME && console.timeEnd("drawReligions");
} }
function toggleStates(event) { function toggleStates(event) {
if (!layerIsOn('toggleStates')) { if (!layerIsOn("toggleStates")) {
turnButtonOn('toggleStates'); turnButtonOn("toggleStates");
regions.style('display', null); regions.style("display", null);
drawStates(); drawStates();
if (event && isCtrlClick(event)) editStyle('regions'); if (event && isCtrlClick(event)) editStyle("regions");
} else { } else {
if (event && isCtrlClick(event)) { if (event && isCtrlClick(event)) {
editStyle("regions"); editStyle("regions");
@ -958,8 +958,8 @@ function toggleStates(event) {
} }
function drawStates() { function drawStates() {
TIME && console.time('drawStates'); TIME && console.time("drawStates");
regions.selectAll('path').remove(); regions.selectAll("path").remove();
const {cells, vertices, features} = pack; const {cells, vertices, features} = pack;
const states = pack.states; const states = pack.states;
@ -1058,7 +1058,7 @@ function drawStates() {
.join(""); .join("");
statesBody.html(bodyString + gapString); statesBody.html(bodyString + gapString);
defs.select('#statePaths').html(clipString); defs.select("#statePaths").html(clipString);
statesHalo.html(haloString); statesHalo.html(haloString);
// connect vertices to chain // connect vertices to chain
@ -1102,7 +1102,7 @@ function drawStates() {
} }
invokeActiveZooming(); invokeActiveZooming();
TIME && console.timeEnd('drawStates'); TIME && console.timeEnd("drawStates");
} }
function toggleBorders(event) { function toggleBorders(event) {
@ -1122,8 +1122,8 @@ function toggleBorders(event) {
// draw state and province borders // draw state and province borders
function drawBorders() { function drawBorders() {
TIME && console.time('drawBorders'); TIME && console.time("drawBorders");
borders.selectAll('path').remove(); borders.selectAll("path").remove();
const {cells, vertices} = pack; const {cells, vertices} = pack;
const n = cells.i.length; const n = cells.i.length;
@ -1146,34 +1146,34 @@ function drawBorders() {
if (provToCell) { if (provToCell) {
const provTo = cells.province[provToCell]; const provTo = cells.province[provToCell];
pUsed[p][provToCell] = provTo; pUsed[p][provToCell] = provTo;
const vertex = cells.v[i].find((v) => vertices.c[v].some((i) => cells.province[i] === provTo)); const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.province[i] === provTo));
const chain = connectVertices(vertex, p, cells.province, provTo, pUsed); const chain = connectVertices(vertex, p, cells.province, provTo, pUsed);
if (chain.length > 1) { if (chain.length > 1) {
pPath.push('M' + chain.map((c) => vertices.p[c]).join(' ')); pPath.push("M" + chain.map(c => vertices.p[c]).join(" "));
i--; i--;
continue; continue;
} }
} }
// if cell is on state border // if cell is on state border
const stateToCell = cells.c[i].find((n) => cells.h[n] >= 20 && s > cells.state[n] && sUsed[s][n] !== cells.state[n]); const stateToCell = cells.c[i].find(n => cells.h[n] >= 20 && s > cells.state[n] && sUsed[s][n] !== cells.state[n]);
if (stateToCell !== undefined) { if (stateToCell !== undefined) {
const stateTo = cells.state[stateToCell]; const stateTo = cells.state[stateToCell];
sUsed[s][stateToCell] = stateTo; sUsed[s][stateToCell] = stateTo;
const vertex = cells.v[i].find((v) => vertices.c[v].some((i) => cells.h[i] >= 20 && cells.state[i] === stateTo)); const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.h[i] >= 20 && cells.state[i] === stateTo));
const chain = connectVertices(vertex, s, cells.state, stateTo, sUsed); const chain = connectVertices(vertex, s, cells.state, stateTo, sUsed);
if (chain.length > 1) { if (chain.length > 1) {
sPath.push('M' + chain.map((c) => vertices.p[c]).join(' ')); sPath.push("M" + chain.map(c => vertices.p[c]).join(" "));
i--; i--;
continue; continue;
} }
} }
} }
stateBorders.append('path').attr('d', sPath.join(' ')); stateBorders.append("path").attr("d", sPath.join(" "));
provinceBorders.append('path').attr('d', pPath.join(' ')); provinceBorders.append("path").attr("d", pPath.join(" "));
// connect vertices to chain // connect vertices to chain
function connectVertices(current, f, array, t, used) { function connectVertices(current, f, array, t, used) {
@ -1224,14 +1224,14 @@ function drawBorders() {
return chain; return chain;
} }
TIME && console.timeEnd('drawBorders'); TIME && console.timeEnd("drawBorders");
} }
function toggleProvinces(event) { function toggleProvinces(event) {
if (!layerIsOn('toggleProvinces')) { if (!layerIsOn("toggleProvinces")) {
turnButtonOn('toggleProvinces'); turnButtonOn("toggleProvinces");
drawProvinces(); drawProvinces();
if (event && isCtrlClick(event)) editStyle('provs'); if (event && isCtrlClick(event)) editStyle("provs");
} else { } else {
if (event && isCtrlClick(event)) { if (event && isCtrlClick(event)) {
editStyle("provs"); editStyle("provs");
@ -1243,9 +1243,9 @@ function toggleProvinces(event) {
} }
function drawProvinces() { function drawProvinces() {
TIME && console.time('drawProvinces'); TIME && console.time("drawProvinces");
const labelsOn = provs.attr('data-labels') == 1; const labelsOn = provs.attr("data-labels") == 1;
provs.selectAll('*').remove(); provs.selectAll("*").remove();
const provinces = pack.provinces; const provinces = pack.provinces;
const {body, gap} = getProvincesVertices(); const {body, gap} = getProvincesVertices();
@ -1283,7 +1283,7 @@ function drawProvinces() {
.attr("id", d => "provinceLabel" + d.i) .attr("id", d => "provinceLabel" + d.i)
.text(d => d.name); .text(d => d.name);
TIME && console.timeEnd('drawProvinces'); TIME && console.timeEnd("drawProvinces");
} }
function getProvincesVertices() { function getProvincesVertices() {
@ -1293,20 +1293,20 @@ function getProvincesVertices() {
n = cells.i.length; n = cells.i.length;
const used = new Uint8Array(cells.i.length); const used = new Uint8Array(cells.i.length);
const vArray = new Array(provinces.length); // store vertices array const vArray = new Array(provinces.length); // store vertices array
const body = new Array(provinces.length).fill(''); // store path around each province const body = new Array(provinces.length).fill(""); // store path around each province
const gap = new Array(provinces.length).fill(''); // store path along water for each province to fill the gaps const gap = new Array(provinces.length).fill(""); // store path along water for each province to fill the gaps
for (const i of cells.i) { for (const i of cells.i) {
if (!cells.province[i] || used[i]) continue; if (!cells.province[i] || used[i]) continue;
const p = cells.province[i]; const p = cells.province[i];
const onborder = cells.c[i].some((n) => cells.province[n] !== p); const onborder = cells.c[i].some(n => cells.province[n] !== p);
if (!onborder) continue; if (!onborder) continue;
const borderWith = cells.c[i].map((c) => cells.province[c]).find((n) => n !== p); const borderWith = cells.c[i].map(c => cells.province[c]).find(n => n !== p);
const vertex = cells.v[i].find((v) => vertices.c[v].some((i) => cells.province[i] === borderWith)); const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.province[i] === borderWith));
const chain = connectVertices(vertex, p, borderWith); const chain = connectVertices(vertex, p, borderWith);
if (chain.length < 3) continue; if (chain.length < 3) continue;
const points = chain.map((v) => vertices.p[v[0]]); const points = chain.map(v => vertices.p[v[0]]);
if (!vArray[p]) vArray[p] = []; if (!vArray[p]) vArray[p] = [];
vArray[p].push(points); vArray[p].push(points);
body[p] += "M" + points.join("L"); body[p] += "M" + points.join("L");
@ -1367,8 +1367,8 @@ function getProvincesVertices() {
} }
function toggleGrid(event) { function toggleGrid(event) {
if (!gridOverlay.selectAll('*').size()) { if (!gridOverlay.selectAll("*").size()) {
turnButtonOn('toggleGrid'); turnButtonOn("toggleGrid");
drawGrid(); drawGrid();
calculateFriendlyGridSize(); calculateFriendlyGridSize();
@ -1413,10 +1413,10 @@ function drawGrid() {
} }
function toggleCoordinates(event) { function toggleCoordinates(event) {
if (!coordinates.selectAll('*').size()) { if (!coordinates.selectAll("*").size()) {
turnButtonOn('toggleCoordinates'); turnButtonOn("toggleCoordinates");
drawCoordinates(); drawCoordinates();
if (event && isCtrlClick(event)) editStyle('coordinates'); if (event && isCtrlClick(event)) editStyle("coordinates");
} else { } else {
if (event && isCtrlClick(event)) { if (event && isCtrlClick(event)) {
editStyle("coordinates"); editStyle("coordinates");
@ -1446,11 +1446,11 @@ function drawCoordinates() {
.stepMinor([step, step]); .stepMinor([step, step]);
const projection = d3.geoEquirectangular().fitSize([graphWidth, graphHeight], graticule()); const projection = d3.geoEquirectangular().fitSize([graphWidth, graphHeight], graticule());
const grid = coordinates.append('g').attr('id', 'coordinateGrid'); const grid = coordinates.append("g").attr("id", "coordinateGrid");
const labels = coordinates.append('g').attr('id', 'coordinateLabels'); const labels = coordinates.append("g").attr("id", "coordinateLabels");
const p = getViewPoint(scale + desired + 2, scale + desired / 2); // on border point on viexBox const p = getViewPoint(scale + desired + 2, scale + desired / 2); // on border point on viexBox
const data = graticule.lines().map((d) => { const data = graticule.lines().map(d => {
const lat = d.coordinates[0][1] === d.coordinates[1][1]; // check if line is latitude or longitude const lat = d.coordinates[0][1] === d.coordinates[1][1]; // check if line is latitude or longitude
const c = d.coordinates[0], const c = d.coordinates[0],
pos = projection(c); // map coordinates pos = projection(c); // map coordinates
@ -1499,7 +1499,7 @@ function toggleCompass(event) {
compass.append("use").attr("xlink:href", "#rose"); compass.append("use").attr("xlink:href", "#rose");
shiftCompass(); shiftCompass();
} }
if (event && isCtrlClick(event)) editStyle('compass'); if (event && isCtrlClick(event)) editStyle("compass");
} else { } else {
if (event && isCtrlClick(event)) { if (event && isCtrlClick(event)) {
editStyle("compass"); editStyle("compass");
@ -1527,8 +1527,8 @@ function toggleRelief(event) {
} }
function toggleTexture(event) { function toggleTexture(event) {
if (!layerIsOn('toggleTexture')) { if (!layerIsOn("toggleTexture")) {
turnButtonOn('toggleTexture'); turnButtonOn("toggleTexture");
// append default texture image selected by default. Don't append on load to not harm performance // append default texture image selected by default. Don't append on load to not harm performance
if (!texture.selectAll("*").size()) { if (!texture.selectAll("*").size()) {
const x = +styleTextureShiftX.value; const x = +styleTextureShiftX.value;
@ -1545,7 +1545,7 @@ function toggleTexture(event) {
} }
$("#texture").fadeIn(); $("#texture").fadeIn();
zoom.scaleBy(svg, 1.00001); // enforce browser re-draw zoom.scaleBy(svg, 1.00001); // enforce browser re-draw
if (event && isCtrlClick(event)) editStyle('texture'); if (event && isCtrlClick(event)) editStyle("texture");
} else { } else {
if (event && isCtrlClick(event)) return editStyle("texture"); if (event && isCtrlClick(event)) return editStyle("texture");
$("#texture").fadeOut(); $("#texture").fadeOut();
@ -1681,7 +1681,7 @@ function toggleLabels(event) {
turnButtonOn("toggleLabels"); turnButtonOn("toggleLabels");
labels.style("display", null); labels.style("display", null);
invokeActiveZooming(); invokeActiveZooming();
if (event && isCtrlClick(event)) editStyle('labels'); if (event && isCtrlClick(event)) editStyle("labels");
} else { } else {
if (event && isCtrlClick(event)) { if (event && isCtrlClick(event)) {
editStyle("labels"); editStyle("labels");
@ -1708,11 +1708,11 @@ function toggleIcons(event) {
} }
function toggleRulers(event) { function toggleRulers(event) {
if (!layerIsOn('toggleRulers')) { if (!layerIsOn("toggleRulers")) {
turnButtonOn('toggleRulers'); turnButtonOn("toggleRulers");
if (event && isCtrlClick(event)) editStyle('ruler'); if (event && isCtrlClick(event)) editStyle("ruler");
rulers.draw(); rulers.draw();
ruler.style('display', null); ruler.style("display", null);
} else { } else {
if (event && isCtrlClick(event)) { if (event && isCtrlClick(event)) {
editStyle("ruler"); editStyle("ruler");
@ -1771,12 +1771,12 @@ function toggleEmblems(event) {
} }
function drawEmblems() { function drawEmblems() {
TIME && console.time('drawEmblems'); TIME && console.time("drawEmblems");
const {states, provinces, burgs} = pack; const {states, provinces, burgs} = pack;
const validStates = states.filter((s) => s.i && !s.removed && s.coa && s.coaSize != 0); const validStates = states.filter(s => s.i && !s.removed && s.coa && s.coaSize != 0);
const validProvinces = provinces.filter((p) => p.i && !p.removed && p.coa && p.coaSize != 0); const validProvinces = provinces.filter(p => p.i && !p.removed && p.coa && p.coaSize != 0);
const validBurgs = burgs.filter((b) => b.i && !b.removed && b.coa && b.coaSize != 0); const validBurgs = burgs.filter(b => b.i && !b.removed && b.coa && b.coaSize != 0);
const getStateEmblemsSize = () => { const getStateEmblemsSize = () => {
const startSize = minmax((graphHeight + graphWidth) / 40, 10, 100); const startSize = minmax((graphHeight + graphWidth) / 40, 10, 100);
@ -1800,7 +1800,7 @@ function drawEmblems() {
}; };
const sizeBurgs = getBurgEmblemSize(); const sizeBurgs = getBurgEmblemSize();
const burgCOAs = validBurgs.map((burg) => { const burgCOAs = validBurgs.map(burg => {
const {x, y} = burg; const {x, y} = burg;
const size = burg.coaSize || 1; const size = burg.coaSize || 1;
const shift = (sizeBurgs * size) / 2; const shift = (sizeBurgs * size) / 2;
@ -1808,7 +1808,7 @@ function drawEmblems() {
}); });
const sizeProvinces = getProvinceEmblemsSize(); const sizeProvinces = getProvinceEmblemsSize();
const provinceCOAs = validProvinces.map((province) => { const provinceCOAs = validProvinces.map(province => {
if (!province.pole) getProvincesVertices(); if (!province.pole) getProvincesVertices();
const [x, y] = province.pole || pack.cells.p[province.center]; const [x, y] = province.pole || pack.cells.p[province.center];
const size = province.coaSize || 1; const size = province.coaSize || 1;
@ -1817,7 +1817,7 @@ function drawEmblems() {
}); });
const sizeStates = getStateEmblemsSize(); const sizeStates = getStateEmblemsSize();
const stateCOAs = validStates.map((state) => { const stateCOAs = validStates.map(state => {
const [x, y] = state.pole || pack.cells.p[state.center]; const [x, y] = state.pole || pack.cells.p[state.center];
const size = state.coaSize || 1; const size = state.coaSize || 1;
const shift = (sizeStates * size) / 2; const shift = (sizeStates * size) / 2;
@ -1896,49 +1896,6 @@ function toggleResources(event) {
} }
} }
function drawResources() {
console.time("drawResources");
const someArePinned = pack.resources.some((resource) => resource.pinned);
const drawCircle = +goods.attr("data-circle");
let resourcesHTML = "";
for (const i of pack.cells.i) {
if (!pack.cells.resource[i]) continue;
const resource = Resources.get(pack.cells.resource[i]);
if (someArePinned && !resource.pinned) continue;
const [x, y] = pack.cells.p[i];
const stroke = Resources.getStroke(resource.color);
// if (!drawCircle) {
// resourcesHTML += `<use data-i="${resource.i}" href="#${resource.icon}" x="${x - 3}" y="${y - 3}" width="6" height="6"/>`;
// continue;
// }
resourcesHTML += `<g>
<circle data-i="${resource.i}" cx=${x} cy=${y} r="3" fill="${resource.color}" stroke="${stroke}" />
<use href="#${resource.icon}" x="${x - 3}" y="${y - 3}" width="6" height="6"/>
</g>`;
}
goods.html(resourcesHTML);
console.timeEnd('drawResources');
}
function toggleResources(event) {
if (!layerIsOn('toggleResources')) {
turnButtonOn('toggleResources');
drawResources();
if (event && isCtrlClick(event)) editStyle('goods');
} else {
if (event && isCtrlClick(event)) {
editStyle('goods');
return;
}
goods.selectAll('*').remove();
turnButtonOff('toggleResources');
}
}
function drawResources() { function drawResources() {
console.time('drawResources'); console.time('drawResources');
const someArePinned = pack.resources.some((resource) => resource.pinned); const someArePinned = pack.resources.some((resource) => resource.pinned);
@ -1968,24 +1925,24 @@ function drawResources() {
} }
function layerIsOn(el) { function layerIsOn(el) {
const buttonoff = document.getElementById(el).classList.contains('buttonoff'); const buttonoff = document.getElementById(el).classList.contains("buttonoff");
return !buttonoff; return !buttonoff;
} }
function turnButtonOff(el) { function turnButtonOff(el) {
document.getElementById(el).classList.add('buttonoff'); document.getElementById(el).classList.add("buttonoff");
getCurrentPreset(); getCurrentPreset();
} }
function turnButtonOn(el) { function turnButtonOn(el) {
document.getElementById(el).classList.remove('buttonoff'); document.getElementById(el).classList.remove("buttonoff");
getCurrentPreset(); getCurrentPreset();
} }
// move layers on mapLayers dragging (jquery sortable) // move layers on mapLayers dragging (jquery sortable)
$('#mapLayers').sortable({items: 'li:not(.solid)', containment: 'parent', cancel: '.solid', update: moveLayer}); $("#mapLayers").sortable({items: "li:not(.solid)", containment: "parent", cancel: ".solid", update: moveLayer});
function moveLayer(event, ui) { function moveLayer(event, ui) {
const el = getLayer(ui.item.attr('id')); const el = getLayer(ui.item.attr("id"));
if (!el) return; if (!el) return;
const prev = getLayer(ui.item.prev().attr("id")); const prev = getLayer(ui.item.prev().attr("id"));
const next = getLayer(ui.item.next().attr("id")); const next = getLayer(ui.item.next().attr("id"));

View file

@ -10,8 +10,6 @@ function editMarker(markerI) {
if (document.getElementById("notesEditor").offsetParent) editNotes(element.id, element.id); if (document.getElementById("notesEditor").offsetParent) editNotes(element.id, element.id);
elSelected = d3.select(element).raise().call(d3.drag().on("start", dragMarker)).classed("draggable", true);
// dom elements // dom elements
const markerType = document.getElementById("markerType"); const markerType = document.getElementById("markerType");
const markerIcon = document.getElementById("markerIcon"); const markerIcon = document.getElementById("markerIcon");

View file

@ -45,7 +45,6 @@ function overviewMarkers() {
if (el.classList.contains("icon-pin")) return pinMarker(el, i); if (el.classList.contains("icon-pin")) return pinMarker(el, i);
if (el.classList.contains("locks")) return toggleLockStatus(el, i); if (el.classList.contains("locks")) return toggleLockStatus(el, i);
if (el.classList.contains("icon-trash-empty")) return triggerRemove(i); if (el.classList.contains("icon-trash-empty")) return triggerRemove(i);
// TODO: hidden attribute
} }
function addLines() { function addLines() {

View file

@ -1,14 +1,14 @@
'use strict'; "use strict";
function overviewMilitary() { function overviewMilitary() {
if (customization) return; if (customization) return;
closeDialogs('#militaryOverview, .stable'); closeDialogs("#militaryOverview, .stable");
if (!layerIsOn('toggleStates')) toggleStates(); if (!layerIsOn("toggleStates")) toggleStates();
if (!layerIsOn('toggleBorders')) toggleBorders(); if (!layerIsOn("toggleBorders")) toggleBorders();
if (!layerIsOn('toggleMilitary')) toggleMilitary(); if (!layerIsOn("toggleMilitary")) toggleMilitary();
const body = document.getElementById('militaryBody'); const body = document.getElementById("militaryBody");
addLines(); addLines();
$('#militaryOverview').dialog(); $("#militaryOverview").dialog();
if (modules.overviewMilitary) return; if (modules.overviewMilitary) return;
modules.overviewMilitary = true; modules.overviewMilitary = true;
@ -22,13 +22,13 @@ function overviewMilitary() {
}); });
// add listeners // add listeners
document.getElementById('militaryOverviewRefresh').addEventListener('click', addLines); document.getElementById("militaryOverviewRefresh").addEventListener("click", addLines);
document.getElementById('militaryPercentage').addEventListener('click', togglePercentageMode); document.getElementById("militaryPercentage").addEventListener("click", togglePercentageMode);
document.getElementById('militaryOptionsButton').addEventListener('click', militaryCustomize); document.getElementById("militaryOptionsButton").addEventListener("click", militaryCustomize);
document.getElementById('militaryRegimentsList').addEventListener('click', () => overviewRegiments(-1)); document.getElementById("militaryRegimentsList").addEventListener("click", () => overviewRegiments(-1));
document.getElementById('militaryOverviewRecalculate').addEventListener('click', militaryRecalculate); document.getElementById("militaryOverviewRecalculate").addEventListener("click", militaryRecalculate);
document.getElementById('militaryExport').addEventListener('click', downloadMilitaryData); document.getElementById("militaryExport").addEventListener("click", downloadMilitaryData);
document.getElementById('militaryWiki').addEventListener('click', () => wiki('Military-Forces')); document.getElementById("militaryWiki").addEventListener("click", () => wiki("Military-Forces"));
body.addEventListener("change", function (ev) { body.addEventListener("change", function (ev) {
const el = ev.target, const el = ev.target,
@ -65,9 +65,9 @@ function overviewMilitary() {
// add line for each state // add line for each state
function addLines() { function addLines() {
body.innerHTML = ''; body.innerHTML = "";
let lines = ''; let lines = "";
const states = pack.states.filter((s) => s.i && !s.removed); const states = pack.states.filter(s => s.i && !s.removed);
for (const s of states) { for (const s of states) {
const population = rn((s.rural + s.urban * urbanization) * populationRate); const population = rn((s.rural + s.urban * urbanization) * populationRate);
@ -75,8 +75,8 @@ function overviewMilitary() {
const total = options.military.reduce((s, u) => s + getForces(u) * u.crew, 0); const total = options.military.reduce((s, u) => s + getForces(u) * u.crew, 0);
const rate = (total / population) * 100; const rate = (total / population) * 100;
const sortData = options.military.map((u) => `data-${u.name}="${getForces(u)}"`).join(' '); const sortData = options.military.map(u => `data-${u.name}="${getForces(u)}"`).join(" ");
const lineData = options.military.map((u) => `<div data-type="${u.name}" data-tip="State ${u.name} units number">${getForces(u)}</div>`).join(' '); const lineData = options.military.map(u => `<div data-type="${u.name}" data-tip="State ${u.name} units number">${getForces(u)}</div>`).join(" ");
lines += /* html */ `<div lines += /* html */ `<div
class="states" class="states"
@ -105,12 +105,12 @@ function overviewMilitary() {
<span data-tip="Show regiments list" class="icon-list-bullet pointer"></span> <span data-tip="Show regiments list" class="icon-list-bullet pointer"></span>
</div>`; </div>`;
} }
body.insertAdjacentHTML('beforeend', lines); body.insertAdjacentHTML("beforeend", lines);
updateFooter(); updateFooter();
// add listeners // add listeners
body.querySelectorAll('div.states').forEach((el) => el.addEventListener('mouseenter', (ev) => stateHighlightOn(ev))); body.querySelectorAll("div.states").forEach(el => el.addEventListener("mouseenter", ev => stateHighlightOn(ev)));
body.querySelectorAll('div.states').forEach((el) => el.addEventListener('mouseleave', (ev) => stateHighlightOff(ev))); body.querySelectorAll("div.states").forEach(el => el.addEventListener("mouseleave", ev => stateHighlightOff(ev)));
if (body.dataset.type === "percentage") { if (body.dataset.type === "percentage") {
body.dataset.type = "absolute"; body.dataset.type = "absolute";
@ -137,7 +137,7 @@ function overviewMilitary() {
const total = (line.dataset.total = options.military.reduce((s, u) => s + getForces(u) * u.crew, 0)); const total = (line.dataset.total = options.military.reduce((s, u) => s + getForces(u) * u.crew, 0));
const rate = (line.dataset.rate = (total / population) * 100); const rate = (line.dataset.rate = (total / population) * 100);
line.querySelector("div[data-type='total']").innerHTML = si(total); line.querySelector("div[data-type='total']").innerHTML = si(total);
line.querySelector("div[data-type='rate']").innerHTML = rn(rate, 2) + '%'; line.querySelector("div[data-type='rate']").innerHTML = rn(rate, 2) + "%";
updateFooter(); updateFooter();
} }
@ -148,8 +148,8 @@ function overviewMilitary() {
const total = d3.sum(lines.map(el => el.dataset.total)); const total = d3.sum(lines.map(el => el.dataset.total));
militaryFooterForcesTotal.innerHTML = si(total); militaryFooterForcesTotal.innerHTML = si(total);
militaryFooterForces.innerHTML = si(total / statesNumber); militaryFooterForces.innerHTML = si(total / statesNumber);
militaryFooterRate.innerHTML = rn(d3.sum(lines.map((el) => el.dataset.rate)) / statesNumber, 2) + '%'; militaryFooterRate.innerHTML = rn(d3.sum(lines.map(el => el.dataset.rate)) / statesNumber, 2) + "%";
militaryFooterAlert.innerHTML = rn(d3.sum(lines.map((el) => el.dataset.alert)) / statesNumber, 2); militaryFooterAlert.innerHTML = rn(d3.sum(lines.map(el => el.dataset.alert)) / statesNumber, 2);
} }
function stateHighlightOn(event) { function stateHighlightOn(event) {
@ -207,7 +207,7 @@ function overviewMilitary() {
const total = function (type) { const total = function (type) {
if (cache[type]) cache[type]; if (cache[type]) cache[type];
cache[type] = d3.sum(array.map((el) => +el.dataset[type])); cache[type] = d3.sum(array.map(el => +el.dataset[type]));
return cache[type]; return cache[type];
}; };
@ -219,7 +219,7 @@ function overviewMilitary() {
}); });
}); });
} else { } else {
body.dataset.type = 'absolute'; body.dataset.type = "absolute";
addLines(); addLines();
} }
} }
@ -388,11 +388,11 @@ function overviewMilitary() {
const unitLines = Array.from(tableBody.querySelectorAll("tr")); const unitLines = Array.from(tableBody.querySelectorAll("tr"));
const names = unitLines.map(r => r.querySelector("input").value.replace(/[&\/\\#, +()$~%.'":*?<>{}]/g, "_")); const names = unitLines.map(r => r.querySelector("input").value.replace(/[&\/\\#, +()$~%.'":*?<>{}]/g, "_"));
if (new Set(names).size !== names.length) { if (new Set(names).size !== names.length) {
tip('All units should have unique names', false, 'error'); tip("All units should have unique names", false, "error");
return; return;
} }
$('#militaryOptions').dialog('close'); $("#militaryOptions").dialog("close");
options.military = unitLines.map((r, i) => { options.military = unitLines.map((r, i) => {
const elements = Array.from(r.querySelectorAll("input, button, select")); const elements = Array.from(r.querySelectorAll("input, button, select"));
const [icon, name, biomes, states, cultures, religions, rural, urban, crew, power, type, separate] = elements.map(el => { const [icon, name, biomes, states, cultures, religions, rural, urban, crew, power, type, separate] = elements.map(el => {
@ -411,7 +411,7 @@ function overviewMilitary() {
if (religions) unit.religions = religions; if (religions) unit.religions = religions;
return unit; return unit;
}); });
localStorage.setItem('military', JSON.stringify(options.military)); localStorage.setItem("military", JSON.stringify(options.military));
Military.generate(); Military.generate();
updateHeaders(); updateHeaders();
addLines(); addLines();
@ -450,7 +450,7 @@ function overviewMilitary() {
data += el.dataset.alert + "\n"; data += el.dataset.alert + "\n";
}); });
const name = getFileName('Military') + '.csv'; const name = getFileName("Military") + ".csv";
downloadFile(data, name); downloadFile(data, name);
} }
} }

View file

@ -1,8 +1,8 @@
'use strict'; "use strict";
function editNamesbase() { function editNamesbase() {
if (customization) return; if (customization) return;
closeDialogs('#namesbaseEditor, .stable'); closeDialogs("#namesbaseEditor, .stable");
$('#namesbaseEditor').dialog(); $("#namesbaseEditor").dialog();
if (modules.editNamesbase) return; if (modules.editNamesbase) return;
modules.editNamesbase = true; modules.editNamesbase = true;
@ -58,8 +58,8 @@ function editNamesbase() {
}); });
function createBasesList() { function createBasesList() {
const select = document.getElementById('namesbaseSelect'); const select = document.getElementById("namesbaseSelect");
select.innerHTML = ''; select.innerHTML = "";
nameBases.forEach((b, i) => select.options.add(new Option(b.name, i))); nameBases.forEach((b, i) => select.options.add(new Option(b.name, i)));
} }
@ -81,13 +81,13 @@ function editNamesbase() {
for (let i = 0; i < 10; i++) { for (let i = 0; i < 10; i++) {
const example = Names.getBase(base); const example = Names.getBase(base);
if (example === undefined) { if (example === undefined) {
examples = 'Cannot generate examples. Please verify the data'; examples = "Cannot generate examples. Please verify the data";
break; break;
} }
if (i) examples += ', '; if (i) examples += ", ";
examples += example; examples += example;
} }
document.getElementById('namesbaseExamples').innerHTML = examples; document.getElementById("namesbaseExamples").innerHTML = examples;
} }
function updateNamesData() { function updateNamesData() {
@ -130,7 +130,7 @@ function editNamesbase() {
} }
function updateBaseDublication() { function updateBaseDublication() {
const base = +document.getElementById('namesbaseSelect').value; const base = +document.getElementById("namesbaseSelect").value;
nameBases[base].d = this.value; nameBases[base].d = this.value;
} }

View file

@ -21,10 +21,10 @@ function editNotes(id, name) {
// select an object // select an object
if (notes.length || id) { if (notes.length || id) {
if (!id) id = notes[0].id; if (!id) id = notes[0].id;
let note = notes.find((note) => note.id === id); let note = notes.find(note => note.id === id);
if (note === undefined) { if (note === undefined) {
if (!name) name = id; if (!name) name = id;
note = {id, name, legend: ''}; note = {id, name, legend: ""};
notes.push(note); notes.push(note);
notesSelect.options.add(new Option(id, id)); notesSelect.options.add(new Option(id, id));
} }
@ -166,70 +166,6 @@ function editNotes(id, name) {
}); });
} }
function updateLegend() {
const note = notes.find(note => note.id === notesSelect.value);
if (note && tinymce?.activeEditor) {
note.legend = tinymce.activeEditor.getContent();
updateNotesBox(note);
}
}
function updateNotesBox(note) {
document.getElementById("notesHeader").innerHTML = note.name;
document.getElementById("notesBody").innerHTML = note.legend;
}
function changeElement() {
const note = notes.find(note => note.id === this.value);
if (!note) return tip("Note element is not found", true, "error", 4000);
notesName.value = note.name;
tinymce.activeEditor.setContent(note.legend);
updateNotesBox(note);
}
function changeName() {
const note = notes.find(note => note.id === notesSelect.value);
if (!note) return tip("Note element is not found", true, "error", 4000);
note.name = this.value;
}
function validateHighlightElement() {
const element = document.getElementById(notesSelect.value);
if (element) return highlightElement(element, 3);
confirmationDialog({
title: "Element not found",
message: "Note element is not found. Would you like to remove the note?",
confirm: "Remove",
cancel: "Keep",
onConfirm: removeLegend
});
}
function downloadLegends() {
const notesData = JSON.stringify(notes);
const name = getFileName("Notes") + ".txt";
downloadFile(notesData, name);
}
function uploadLegends(dataLoaded) {
if (!dataLoaded) return tip("Cannot load the file. Please check the data format", false, "error");
notes = JSON.parse(dataLoaded);
notesSelect.options.length = 0;
editNotes(notes[0].id, notes[0].name);
}
function triggerNotesRemove() {
confirmationDialog({
title: "Remove note",
message: "Are you sure you want to remove the selected note? There is no way to undo this action",
confirm: "Remove",
onConfirm: removeLegend
});
}
function removeLegend() { function removeLegend() {
const index = notes.findIndex(n => n.id === notesSelect.value); const index = notes.findIndex(n => n.id === notesSelect.value);
notes.splice(index, 1); notes.splice(index, 1);

View file

@ -1,41 +1,41 @@
// UI module to control the options (preferences) // UI module to control the options (preferences)
'use strict'; "use strict";
$('#optionsContainer').draggable({handle: '.drag-trigger', snap: 'svg', snapMode: 'both'}); $("#optionsContainer").draggable({handle: ".drag-trigger", snap: "svg", snapMode: "both"});
$('#exitCustomization').draggable({handle: 'div'}); $("#exitCustomization").draggable({handle: "div"});
$('#mapLayers').disableSelection(); $("#mapLayers").disableSelection();
// remove glow if tip is aknowledged // remove glow if tip is aknowledged
if (stored("disable_click_arrow_tooltip")) { if (stored("disable_click_arrow_tooltip")) {
clearMainTip(); clearMainTip();
optionsTrigger.classList.remove('glow'); optionsTrigger.classList.remove("glow");
} }
// Show options pane on trigger click // Show options pane on trigger click
function showOptions(event) { function showOptions(event) {
if (!stored("disable_click_arrow_tooltip")) { if (!stored("disable_click_arrow_tooltip")) {
clearMainTip(); clearMainTip();
localStorage.setItem('disable_click_arrow_tooltip', true); localStorage.setItem("disable_click_arrow_tooltip", true);
optionsTrigger.classList.remove('glow'); optionsTrigger.classList.remove("glow");
} }
regenerate.style.display = 'none'; regenerate.style.display = "none";
document.getElementById('options').style.display = 'block'; document.getElementById("options").style.display = "block";
optionsTrigger.style.display = 'none'; optionsTrigger.style.display = "none";
if (event) event.stopPropagation(); if (event) event.stopPropagation();
} }
// Hide options pane on trigger click // Hide options pane on trigger click
function hideOptions(event) { function hideOptions(event) {
document.getElementById('options').style.display = 'none'; document.getElementById("options").style.display = "none";
optionsTrigger.style.display = 'block'; optionsTrigger.style.display = "block";
if (event) event.stopPropagation(); if (event) event.stopPropagation();
} }
// To toggle options on hotkey press // To toggle options on hotkey press
function toggleOptions(event) { function toggleOptions(event) {
if (document.getElementById('options').style.display === 'none') showOptions(event); if (document.getElementById("options").style.display === "none") showOptions(event);
else hideOptions(event); else hideOptions(event);
} }
@ -158,15 +158,15 @@ optionsContent.addEventListener("click", function (event) {
function mapSizeInputChange() { function mapSizeInputChange() {
changeMapSize(); changeMapSize();
localStorage.setItem('mapWidth', mapWidthInput.value); localStorage.setItem("mapWidth", mapWidthInput.value);
localStorage.setItem('mapHeight', mapHeightInput.value); localStorage.setItem("mapHeight", mapHeightInput.value);
} }
// change svg size on manual size change or window resize, do not change graph size // change svg size on manual size change or window resize, do not change graph size
function changeMapSize() { function changeMapSize() {
svgWidth = Math.min(+mapWidthInput.value, window.innerWidth); svgWidth = Math.min(+mapWidthInput.value, window.innerWidth);
svgHeight = Math.min(+mapHeightInput.value, window.innerHeight); svgHeight = Math.min(+mapHeightInput.value, window.innerHeight);
svg.attr('width', svgWidth).attr('height', svgHeight); svg.attr("width", svgWidth).attr("height", svgHeight);
const maxWidth = Math.max(+mapWidthInput.value, graphWidth); const maxWidth = Math.max(+mapWidthInput.value, graphWidth);
const maxHeight = Math.max(+mapHeightInput.value, graphHeight); const maxHeight = Math.max(+mapHeightInput.value, graphHeight);
@ -207,8 +207,8 @@ function toggleFullscreen() {
if (mapWidthInput.value != window.innerWidth || mapHeightInput.value != window.innerHeight) { if (mapWidthInput.value != window.innerWidth || mapHeightInput.value != window.innerHeight) {
mapWidthInput.value = window.innerWidth; mapWidthInput.value = window.innerWidth;
mapHeightInput.value = window.innerHeight; mapHeightInput.value = window.innerHeight;
localStorage.removeItem('mapHeight'); localStorage.removeItem("mapHeight");
localStorage.removeItem('mapWidth'); localStorage.removeItem("mapWidth");
} else { } else {
mapWidthInput.value = graphWidth; mapWidthInput.value = graphWidth;
mapHeightInput.value = graphHeight; mapHeightInput.value = graphHeight;
@ -236,7 +236,7 @@ const voiceInterval = setInterval(function () {
if (voices.length) clearInterval(voiceInterval); if (voices.length) clearInterval(voiceInterval);
else return; else return;
const select = document.getElementById('speakerVoice'); const select = document.getElementById("speakerVoice");
voices.forEach((voice, i) => { voices.forEach((voice, i) => {
select.options.add(new Option(voice.name, i, false)); select.options.add(new Option(voice.name, i, false));
}); });
@ -250,7 +250,7 @@ function testSpeaker() {
const speaker = new SpeechSynthesisUtterance(text); const speaker = new SpeechSynthesisUtterance(text);
const voices = speechSynthesis.getVoices(); const voices = speechSynthesis.getVoices();
if (voices.length) { if (voices.length) {
const voiceId = +document.getElementById('speakerVoice').value; const voiceId = +document.getElementById("speakerVoice").value;
speaker.voice = voices[voiceId]; speaker.voice = voices[voiceId];
} }
speechSynthesis.speak(speaker); speechSynthesis.speak(speaker);
@ -349,9 +349,9 @@ function changeCultureSet() {
} }
function changeEmblemShape(emblemShape) { function changeEmblemShape(emblemShape) {
const image = document.getElementById('emblemShapeImage'); const image = document.getElementById("emblemShapeImage");
const shapePath = window.COArenderer && COArenderer.shieldPaths[emblemShape]; const shapePath = window.COArenderer && COArenderer.shieldPaths[emblemShape];
shapePath ? image.setAttribute('d', shapePath) : image.removeAttribute('d'); shapePath ? image.setAttribute("d", shapePath) : image.removeAttribute("d");
const specificShape = ["culture", "state", "random"].includes(emblemShape) ? null : emblemShape; const specificShape = ["culture", "state", "random"].includes(emblemShape) ? null : emblemShape;
if (emblemShape === "random") if (emblemShape === "random")
@ -364,25 +364,25 @@ function changeEmblemShape(emblemShape) {
COArenderer.trigger(id, coa); COArenderer.trigger(id, coa);
}; };
pack.states.forEach((state) => { pack.states.forEach(state => {
if (!state.i || state.removed || !state.coa || state.coa === 'custom') return; if (!state.i || state.removed || !state.coa || state.coa === "custom") return;
const newShield = specificShape || COA.getShield(state.culture, null); const newShield = specificShape || COA.getShield(state.culture, null);
if (newShield === state.coa.shield) return; if (newShield === state.coa.shield) return;
state.coa.shield = newShield; state.coa.shield = newShield;
rerenderCOA('stateCOA' + state.i, state.coa); rerenderCOA("stateCOA" + state.i, state.coa);
}); });
pack.provinces.forEach((province) => { pack.provinces.forEach(province => {
if (!province.i || province.removed || !province.coa || province.coa === 'custom') return; if (!province.i || province.removed || !province.coa || province.coa === "custom") return;
const culture = pack.cells.culture[province.center]; const culture = pack.cells.culture[province.center];
const newShield = specificShape || COA.getShield(culture, province.state); const newShield = specificShape || COA.getShield(culture, province.state);
if (newShield === province.coa.shield) return; if (newShield === province.coa.shield) return;
province.coa.shield = newShield; province.coa.shield = newShield;
rerenderCOA('provinceCOA' + province.i, province.coa); rerenderCOA("provinceCOA" + province.i, province.coa);
}); });
pack.burgs.forEach((burg) => { pack.burgs.forEach(burg => {
if (!burg.i || burg.removed || !burg.coa || burg.coa === 'custom') return; if (!burg.i || burg.removed || !burg.coa || burg.coa === "custom") return;
const newShield = specificShape || COA.getShield(burg.culture, burg.state); const newShield = specificShape || COA.getShield(burg.culture, burg.state);
if (newShield === burg.coa.shield) return; if (newShield === burg.coa.shield) return;
burg.coa.shield = newShield; burg.coa.shield = newShield;
@ -521,8 +521,8 @@ function applyStoredOptions() {
// search params overwrite stored and default options // search params overwrite stored and default options
const params = new URL(window.location.href).searchParams; const params = new URL(window.location.href).searchParams;
const width = +params.get('width'); const width = +params.get("width");
const height = +params.get('height'); const height = +params.get("height");
if (width) mapWidthInput.value = width; if (width) mapWidthInput.value = width;
if (height) mapHeightInput.value = height; if (height) mapHeightInput.value = height;
@ -647,7 +647,7 @@ function changeYear() {
function changeEra() { function changeEra() {
if (!eraInput.value) return; if (!eraInput.value) return;
lock('era'); lock("era");
options.era = eraInput.value; options.era = eraInput.value;
} }
@ -810,7 +810,7 @@ function loadURL() {
return; return;
} }
loadMapFromURL(value); loadMapFromURL(value);
$(this).dialog('close'); $(this).dialog("close");
}, },
Cancel: function () { Cancel: function () {
$(this).dialog("close"); $(this).dialog("close");
@ -822,7 +822,7 @@ function loadURL() {
// load map // load map
document.getElementById("mapToLoad").addEventListener("change", function () { document.getElementById("mapToLoad").addEventListener("change", function () {
const fileToLoad = this.files[0]; const fileToLoad = this.files[0];
this.value = ''; this.value = "";
closeDialogs(); closeDialogs();
uploadMap(fileToLoad); uploadMap(fileToLoad);
}); });
@ -904,30 +904,30 @@ function updateTilesOptions() {
} }
// View mode // View mode
viewMode.addEventListener('click', changeViewMode); viewMode.addEventListener("click", changeViewMode);
function changeViewMode(event) { function changeViewMode(event) {
const button = event.target; const button = event.target;
if (button.tagName !== 'BUTTON') return; if (button.tagName !== "BUTTON") return;
const pressed = button.classList.contains('pressed'); const pressed = button.classList.contains("pressed");
enterStandardView(); enterStandardView();
if (!pressed && button.id !== 'viewStandard') { if (!pressed && button.id !== "viewStandard") {
viewStandard.classList.remove('pressed'); viewStandard.classList.remove("pressed");
button.classList.add('pressed'); button.classList.add("pressed");
enter3dView(button.id); enter3dView(button.id);
} }
} }
function enterStandardView() { function enterStandardView() {
viewMode.querySelectorAll('.pressed').forEach((button) => button.classList.remove('pressed')); viewMode.querySelectorAll(".pressed").forEach(button => button.classList.remove("pressed"));
heightmap3DView.classList.remove('pressed'); heightmap3DView.classList.remove("pressed");
viewStandard.classList.add('pressed'); viewStandard.classList.add("pressed");
if (!document.getElementById('canvas3d')) return; if (!document.getElementById("canvas3d")) return;
ThreeD.stop(); ThreeD.stop();
document.getElementById('canvas3d').remove(); document.getElementById("canvas3d").remove();
if (options3dUpdate.offsetParent) $('#options3d').dialog('close'); if (options3dUpdate.offsetParent) $("#options3d").dialog("close");
if (preview3d.offsetParent) $('#preview3d').dialog('close'); if (preview3d.offsetParent) $("#preview3d").dialog("close");
} }
async function enter3dView(type) { async function enter3dView(type) {
@ -935,21 +935,21 @@ async function enter3dView(type) {
canvas.id = "canvas3d"; canvas.id = "canvas3d";
canvas.dataset.type = type; canvas.dataset.type = type;
if (type === 'heightmap3DView') { if (type === "heightmap3DView") {
canvas.width = parseFloat(preview3d.style.width) || graphWidth / 3; canvas.width = parseFloat(preview3d.style.width) || graphWidth / 3;
canvas.height = canvas.width / (graphWidth / graphHeight); canvas.height = canvas.width / (graphWidth / graphHeight);
canvas.style.display = 'block'; canvas.style.display = "block";
} else { } else {
canvas.width = svgWidth; canvas.width = svgWidth;
canvas.height = svgHeight; canvas.height = svgHeight;
canvas.style.position = 'absolute'; canvas.style.position = "absolute";
canvas.style.display = 'none'; canvas.style.display = "none";
} }
const started = await ThreeD.create(canvas, type); const started = await ThreeD.create(canvas, type);
if (!started) return; if (!started) return;
canvas.style.display = 'block'; canvas.style.display = "block";
canvas.onmouseenter = () => { canvas.onmouseenter = () => {
const help = const help =
"Left mouse to change angle, middle mouse / mousewheel to zoom, right mouse to pan. <b>O</b> to toggle options"; "Left mouse to change angle, middle mouse / mousewheel to zoom, right mouse to pan. <b>O</b> to toggle options";
@ -972,7 +972,7 @@ async function enter3dView(type) {
} }
function resize3d() { function resize3d() {
const canvas = document.getElementById('canvas3d'); const canvas = document.getElementById("canvas3d");
canvas.width = parseFloat(preview3d.style.width); canvas.width = parseFloat(preview3d.style.width);
canvas.height = parseFloat(preview3d.style.height) - 2; canvas.height = parseFloat(preview3d.style.height) - 2;
ThreeD.redraw(); ThreeD.redraw();
@ -995,9 +995,9 @@ function toggle3dOptions() {
if (modules.options3d) return; if (modules.options3d) return;
modules.options3d = true; modules.options3d = true;
document.getElementById('options3dUpdate').addEventListener('click', ThreeD.update); document.getElementById("options3dUpdate").addEventListener("click", ThreeD.update);
document.getElementById('options3dSave').addEventListener('click', ThreeD.saveScreenshot); document.getElementById("options3dSave").addEventListener("click", ThreeD.saveScreenshot);
document.getElementById('options3dOBJSave').addEventListener('click', ThreeD.saveOBJ); document.getElementById("options3dOBJSave").addEventListener("click", ThreeD.saveOBJ);
document.getElementById("options3dScaleRange").addEventListener("input", changeHeightScale); document.getElementById("options3dScaleRange").addEventListener("input", changeHeightScale);
document.getElementById("options3dScaleNumber").addEventListener("change", changeHeightScale); document.getElementById("options3dScaleNumber").addEventListener("change", changeHeightScale);
@ -1030,7 +1030,7 @@ function toggle3dOptions() {
options3dGlobeRotationRange.value = options3dGlobeRotationNumber.value = ThreeD.options.rotateGlobe; options3dGlobeRotationRange.value = options3dGlobeRotationNumber.value = ThreeD.options.rotateGlobe;
options3dMeshLabels3d.value = ThreeD.options.labels3d; options3dMeshLabels3d.value = ThreeD.options.labels3d;
options3dMeshSkyMode.value = ThreeD.options.extendedWater; options3dMeshSkyMode.value = ThreeD.options.extendedWater;
options3dColorSection.style.display = ThreeD.options.extendedWater ? 'block' : 'none'; options3dColorSection.style.display = ThreeD.options.extendedWater ? "block" : "none";
options3dMeshSky.value = ThreeD.options.skyColor; options3dMeshSky.value = ThreeD.options.skyColor;
options3dMeshWater.value = ThreeD.options.waterColor; options3dMeshWater.value = ThreeD.options.waterColor;
options3dGlobeResolution.value = ThreeD.options.resolution; options3dGlobeResolution.value = ThreeD.options.resolution;
@ -1065,7 +1065,7 @@ function toggle3dOptions() {
function toggleSkyMode() { function toggleSkyMode() {
const hide = ThreeD.options.extendedWater; const hide = ThreeD.options.extendedWater;
options3dColorSection.style.display = hide ? 'none' : 'block'; options3dColorSection.style.display = hide ? "none" : "block";
ThreeD.toggleSky(); ThreeD.toggleSky();
} }

View file

@ -1,14 +1,14 @@
'use strict'; "use strict";
function editProvinces() { function editProvinces() {
if (customization) return; if (customization) return;
closeDialogs('#provincesEditor, .stable'); closeDialogs("#provincesEditor, .stable");
if (!layerIsOn('toggleProvinces')) toggleProvinces(); if (!layerIsOn("toggleProvinces")) toggleProvinces();
if (!layerIsOn('toggleBorders')) toggleBorders(); if (!layerIsOn("toggleBorders")) toggleBorders();
if (layerIsOn('toggleStates')) toggleStates(); if (layerIsOn("toggleStates")) toggleStates();
if (layerIsOn('toggleCultures')) toggleCultures(); if (layerIsOn("toggleCultures")) toggleCultures();
provs.selectAll('text').call(d3.drag().on('drag', dragLabel)).classed('draggable', true); provs.selectAll("text").call(d3.drag().on("drag", dragLabel)).classed("draggable", true);
const body = document.getElementById('provincesBodySection'); const body = document.getElementById("provincesBodySection");
refreshProvincesEditor(); refreshProvincesEditor();
if (modules.editProvinces) return; if (modules.editProvinces) return;
@ -91,14 +91,14 @@ function editProvinces() {
provinces[p].burgs.push(cells.burg[i]); provinces[p].burgs.push(cells.burg[i]);
} }
provinces.forEach((p) => { provinces.forEach(p => {
if (!p.i || p.removed) return; if (!p.i || p.removed) return;
if (!p.burg && p.burgs.length) p.burg = p.burgs[0]; if (!p.burg && p.burgs.length) p.burg = p.burgs[0];
}); });
} }
function updateFilter() { function updateFilter() {
const stateFilter = document.getElementById('provincesFilterState'); const stateFilter = document.getElementById("provincesFilterState");
const selectedState = stateFilter.value || 1; const selectedState = stateFilter.value || 1;
stateFilter.options.length = 0; // remove all options stateFilter.options.length = 0; // remove all options
stateFilter.options.add(new Option(`all`, -1, false, selectedState == -1)); stateFilter.options.add(new Option(`all`, -1, false, selectedState == -1));
@ -175,10 +175,10 @@ function editProvinces() {
provincesFooterArea.dataset.area = totalArea; provincesFooterArea.dataset.area = totalArea;
provincesFooterPopulation.dataset.population = totalPopulation; provincesFooterPopulation.dataset.population = totalPopulation;
body.querySelectorAll('div.states').forEach((el) => { body.querySelectorAll("div.states").forEach(el => {
el.addEventListener('click', selectProvinceOnLineClick); el.addEventListener("click", selectProvinceOnLineClick);
el.addEventListener('mouseenter', (ev) => provinceHighlightOn(ev)); el.addEventListener("mouseenter", ev => provinceHighlightOn(ev));
el.addEventListener('mouseleave', (ev) => provinceHighlightOff(ev)); el.addEventListener("mouseleave", ev => provinceHighlightOff(ev));
}); });
if (body.dataset.type === "percentage") { if (body.dataset.type === "percentage") {
@ -186,7 +186,7 @@ function editProvinces() {
togglePercentageMode(); togglePercentageMode();
} }
applySorting(provincesHeader); applySorting(provincesHeader);
$('#provincesEditor').dialog({width: fitContent()}); $("#provincesEditor").dialog({width: fitContent()});
} }
function getCapitalOptions(burgs, capital) { function getCapitalOptions(burgs, capital) {
@ -198,9 +198,9 @@ function editProvinces() {
function provinceHighlightOn(event) { function provinceHighlightOn(event) {
const province = +event.target.dataset.id; const province = +event.target.dataset.id;
const el = body.querySelector(`div[data-id='${province}']`); const el = body.querySelector(`div[data-id='${province}']`);
if (el) el.classList.add('active'); if (el) el.classList.add("active");
if (!layerIsOn('toggleProvinces')) return; if (!layerIsOn("toggleProvinces")) return;
if (customization) return; if (customization) return;
const animate = d3.transition().duration(2000).ease(d3.easeSinIn); const animate = d3.transition().duration(2000).ease(d3.easeSinIn);
provs provs
@ -214,7 +214,7 @@ function editProvinces() {
function provinceHighlightOff(event) { function provinceHighlightOff(event) {
const province = +event.target.dataset.id; const province = +event.target.dataset.id;
const el = body.querySelector(`div[data-id='${province}']`); const el = body.querySelector(`div[data-id='${province}']`);
if (el) el.classList.remove('active'); if (el) el.classList.remove("active");
if (!layerIsOn("toggleProvinces")) return; if (!layerIsOn("toggleProvinces")) return;
provs provs
@ -370,7 +370,7 @@ function editProvinces() {
const rural = rn(p.rural * populationRate); const rural = rn(p.rural * populationRate);
const urban = rn(p.urban * populationRate * urbanization); const urban = rn(p.urban * populationRate * urbanization);
const total = rural + urban; const total = rural + urban;
const l = (n) => Number(n).toLocaleString(); const l = n => Number(n).toLocaleString();
alertMessage.innerHTML = /* html */ ` Rural: <input type="number" min="0" step="1" id="ruralPop" value=${rural} style="width:6em" /> Urban: alertMessage.innerHTML = /* html */ ` Rural: <input type="number" min="0" step="1" id="ruralPop" value=${rural} style="width:6em" /> Urban:
<input type="number" min="0" step="1" id="urbanPop" value=${urban} style="width:6em" ${p.burgs.length ? "" : "disabled"} /> <input type="number" min="0" step="1" id="urbanPop" value=${urban} style="width:6em" ${p.burgs.length ? "" : "disabled"} />
@ -450,11 +450,11 @@ function editProvinces() {
unfog("focusProvince" + p); unfog("focusProvince" + p);
const coaId = 'provinceCOA' + p; const coaId = "provinceCOA" + p;
if (document.getElementById(coaId)) document.getElementById(coaId).remove(); if (document.getElementById(coaId)) document.getElementById(coaId).remove();
emblems.select(`#provinceEmblems > use[data-i='${p}']`).remove(); emblems.select(`#provinceEmblems > use[data-i='${p}']`).remove();
pack.provinces[p] = {i: p, removed: true}; pack.provinces[p] = {i: p, removed: true};
const g = provs.select("#provincesBody"); const g = provs.select("#provincesBody");
g.select("#province" + p).remove(); g.select("#province" + p).remove();
@ -497,41 +497,41 @@ function editProvinces() {
modules.editProvinceName = true; modules.editProvinceName = true;
// add listeners // add listeners
document.getElementById('provinceNameEditorShortCulture').addEventListener('click', regenerateShortNameCuture); document.getElementById("provinceNameEditorShortCulture").addEventListener("click", regenerateShortNameCuture);
document.getElementById('provinceNameEditorShortRandom').addEventListener('click', regenerateShortNameRandom); document.getElementById("provinceNameEditorShortRandom").addEventListener("click", regenerateShortNameRandom);
document.getElementById('provinceNameEditorAddForm').addEventListener('click', addCustomForm); document.getElementById("provinceNameEditorAddForm").addEventListener("click", addCustomForm);
document.getElementById('provinceNameEditorFullRegenerate').addEventListener('click', regenerateFullName); document.getElementById("provinceNameEditorFullRegenerate").addEventListener("click", regenerateFullName);
function regenerateShortNameCuture() { function regenerateShortNameCuture() {
const province = +provinceNameEditor.dataset.province; const province = +provinceNameEditor.dataset.province;
const culture = pack.cells.culture[pack.provinces[province].center]; const culture = pack.cells.culture[pack.provinces[province].center];
const name = Names.getState(Names.getCultureShort(culture), culture); const name = Names.getState(Names.getCultureShort(culture), culture);
document.getElementById('provinceNameEditorShort').value = name; document.getElementById("provinceNameEditorShort").value = name;
} }
function regenerateShortNameRandom() { function regenerateShortNameRandom() {
const base = rand(nameBases.length - 1); const base = rand(nameBases.length - 1);
const name = Names.getState(Names.getBase(base), undefined, base); const name = Names.getState(Names.getBase(base), undefined, base);
document.getElementById('provinceNameEditorShort').value = name; document.getElementById("provinceNameEditorShort").value = name;
} }
function addCustomForm() { function addCustomForm() {
const value = provinceNameEditorCustomForm.value; const value = provinceNameEditorCustomForm.value;
const displayed = provinceNameEditorCustomForm.style.display === 'inline-block'; const displayed = provinceNameEditorCustomForm.style.display === "inline-block";
provinceNameEditorCustomForm.style.display = displayed ? 'none' : 'inline-block'; provinceNameEditorCustomForm.style.display = displayed ? "none" : "inline-block";
provinceNameEditorSelectForm.style.display = displayed ? 'inline-block' : 'none'; provinceNameEditorSelectForm.style.display = displayed ? "inline-block" : "none";
if (displayed) applyOption(provinceNameEditorSelectForm, value); if (displayed) applyOption(provinceNameEditorSelectForm, value);
} }
function regenerateFullName() { function regenerateFullName() {
const short = document.getElementById('provinceNameEditorShort').value; const short = document.getElementById("provinceNameEditorShort").value;
const form = document.getElementById('provinceNameEditorSelectForm').value; const form = document.getElementById("provinceNameEditorSelectForm").value;
document.getElementById('provinceNameEditorFull').value = getFullName(); document.getElementById("provinceNameEditorFull").value = getFullName();
function getFullName() { function getFullName() {
if (!form) return short; if (!form) return short;
if (!short && form) return 'The ' + form; if (!short && form) return "The " + form;
return short + ' ' + form; return short + " " + form;
} }
} }
@ -551,8 +551,8 @@ function editProvinces() {
} }
function togglePercentageMode() { function togglePercentageMode() {
if (body.dataset.type === 'absolute') { if (body.dataset.type === "absolute") {
body.dataset.type = 'percentage'; body.dataset.type = "percentage";
const totalArea = +provincesFooterArea.dataset.area; const totalArea = +provincesFooterArea.dataset.area;
const totalPopulation = +provincesFooterPopulation.dataset.population; const totalPopulation = +provincesFooterPopulation.dataset.population;
@ -561,7 +561,7 @@ function editProvinces() {
el.querySelector(".culturePopulation").innerHTML = rn((+el.dataset.population / totalPopulation) * 100) + "%"; el.querySelector(".culturePopulation").innerHTML = rn((+el.dataset.population / totalPopulation) * 100) + "%";
}); });
} else { } else {
body.dataset.type = 'absolute'; body.dataset.type = "absolute";
provincesEditorAddLines(); provincesEditorAddLines();
} }
} }
@ -628,7 +628,7 @@ function editProvinces() {
.on("mouseleave", d => hideInfo(event, d)); .on("mouseleave", d => hideInfo(event, d));
function showInfo(ev, d) { function showInfo(ev, d) {
d3.select(ev.target).select('rect').classed('selected', 1); d3.select(ev.target).select("rect").classed("selected", 1);
const name = d.data.fullName; const name = d.data.fullName;
const state = pack.states[d.data.state].fullName; const state = pack.states[d.data.state].fullName;
@ -651,9 +651,9 @@ function editProvinces() {
function hideInfo(ev) { function hideInfo(ev) {
provinceHighlightOff(ev); provinceHighlightOff(ev);
if (!document.getElementById('provinceInfo')) return; if (!document.getElementById("provinceInfo")) return;
provinceInfo.innerHTML = '&#8205;'; provinceInfo.innerHTML = "&#8205;";
d3.select(ev.target).select('rect').classed('selected', 0); d3.select(ev.target).select("rect").classed("selected", 0);
} }
node node
@ -677,7 +677,7 @@ function editProvinces() {
node.select("text").each(function (d) { node.select("text").each(function (d) {
this.innerHTML = d.data.name; this.innerHTML = d.data.name;
let b = this.getBBox(); let b = this.getBBox();
if (b.y + b.height > d.y1 + 1) this.innerHTML = ''; if (b.y + b.height > d.y1 + 1) this.innerHTML = "";
for (let i = 0; i < 15 && b.width > 0 && b.x + b.width > d.x1; i++) { for (let i = 0; i < 15 && b.width > 0 && b.x + b.width > d.x1; i++) {
if (this.innerHTML.length < 3) { if (this.innerHTML.length < 3) {
@ -730,10 +730,10 @@ function editProvinces() {
} }
function toggleLabels() { function toggleLabels() {
const hidden = provs.select('#provinceLabels').style('display') === 'none'; const hidden = provs.select("#provinceLabels").style("display") === "none";
provs.select('#provinceLabels').style('display', `${hidden ? 'block' : 'none'}`); provs.select("#provinceLabels").style("display", `${hidden ? "block" : "none"}`);
provs.attr('data-labels', +hidden); provs.attr("data-labels", +hidden);
provs.selectAll('text').call(d3.drag().on('drag', dragLabel)).classed('draggable', true); provs.selectAll("text").call(d3.drag().on("drag", dragLabel)).classed("draggable", true);
} }
function triggerProvincesRelease() { function triggerProvincesRelease() {
@ -765,8 +765,8 @@ function editProvinces() {
} }
function enterProvincesManualAssignent() { function enterProvincesManualAssignent() {
if (!layerIsOn('toggleProvinces')) toggleProvinces(); if (!layerIsOn("toggleProvinces")) toggleProvinces();
if (!layerIsOn('toggleBorders')) toggleBorders(); if (!layerIsOn("toggleBorders")) toggleBorders();
// make province and state borders more visible // make province and state borders more visible
provinceBorders.select("path").attr("stroke", "#000").attr("stroke-width", 0.5); provinceBorders.select("path").attr("stroke", "#000").attr("stroke-width", 0.5);
@ -788,15 +788,15 @@ function editProvinces() {
tip("Click on a province to select, drag the circle to change province", true); tip("Click on a province to select, drag the circle to change province", true);
viewbox.style("cursor", "crosshair").on("click", selectProvinceOnMapClick).call(d3.drag().on("start", dragBrush)).on("touchmove mousemove", moveBrush); viewbox.style("cursor", "crosshair").on("click", selectProvinceOnMapClick).call(d3.drag().on("start", dragBrush)).on("touchmove mousemove", moveBrush);
body.querySelector('div').classList.add('selected'); body.querySelector("div").classList.add("selected");
selectProvince(+body.querySelector('div').dataset.id); selectProvince(+body.querySelector("div").dataset.id);
} }
function selectProvinceOnLineClick() { function selectProvinceOnLineClick() {
if (customization !== 11) return; if (customization !== 11) return;
if (this.parentNode.id !== 'provincesBodySection') return; if (this.parentNode.id !== "provincesBodySection") return;
body.querySelector('div.selected').classList.remove('selected'); body.querySelector("div.selected").classList.remove("selected");
this.classList.add('selected'); this.classList.add("selected");
selectProvince(+this.dataset.id); selectProvince(+this.dataset.id);
} }
@ -814,8 +814,8 @@ function editProvinces() {
return; return;
} }
body.querySelector('div.selected').classList.remove('selected'); body.querySelector("div.selected").classList.remove("selected");
editorLine.classList.add('selected'); editorLine.classList.add("selected");
selectProvince(province); selectProvince(province);
} }
@ -828,7 +828,7 @@ function editProvinces() {
function dragBrush() { function dragBrush() {
const r = +provincesManuallyBrush.value; const r = +provincesManuallyBrush.value;
d3.event.on('drag', () => { d3.event.on("drag", () => {
if (!d3.event.dx && !d3.event.dy) return; if (!d3.event.dx && !d3.event.dy) return;
const p = d3.mouse(this); const p = d3.mouse(this);
moveCircle(p[0], p[1], r); moveCircle(p[0], p[1], r);
@ -847,9 +847,9 @@ function editProvinces() {
const provinceNew = +selected.dataset.id; const provinceNew = +selected.dataset.id;
const state = pack.provinces[provinceNew].state; const state = pack.provinces[provinceNew].state;
const fill = pack.provinces[provinceNew].color || '#ffffff'; const fill = pack.provinces[provinceNew].color || "#ffffff";
selection.forEach((i) => { selection.forEach(i => {
if (!pack.cells.state[i] || pack.cells.state[i] !== state) return; if (!pack.cells.state[i] || pack.cells.state[i] !== state) return;
const exists = temp.select("polygon[data-cell='" + i + "']"); const exists = temp.select("polygon[data-cell='" + i + "']");
const provinceOld = exists.size() ? +exists.attr("data-province") : pack.cells.province[i]; const provinceOld = exists.size() ? +exists.attr("data-province") : pack.cells.province[i];
@ -864,7 +864,7 @@ function editProvinces() {
// change of append new element // change of append new element
if (exists.size()) { if (exists.size()) {
if (pack.cells.province[i] === provinceNew) exists.remove(); if (pack.cells.province[i] === provinceNew) exists.remove();
else exists.attr('data-province', provinceNew).attr('fill', fill); else exists.attr("data-province", provinceNew).attr("fill", fill);
} else { } else {
temp temp
.append("polygon") .append("polygon")
@ -903,14 +903,14 @@ function editProvinces() {
function exitProvincesManualAssignment(close) { function exitProvincesManualAssignment(close) {
customization = 0; customization = 0;
provs.select('#temp').remove(); provs.select("#temp").remove();
provs.select('#centers').remove(); provs.select("#centers").remove();
removeCircle(); removeCircle();
// restore borders style // restore borders style
provinceBorders.select('path').attr('stroke', null).attr('stroke-width', null); provinceBorders.select("path").attr("stroke", null).attr("stroke-width", null);
stateBorders.select('path').attr('stroke', null).attr('stroke-width', null); stateBorders.select("path").attr("stroke", null).attr("stroke-width", null);
debug.selectAll('path.selected').remove(); debug.selectAll("path.selected").remove();
document.querySelectorAll("#provincesBottom > *").forEach(el => (el.style.display = "inline-block")); document.querySelectorAll("#provincesBottom > *").forEach(el => (el.style.display = "inline-block"));
document.getElementById("provincesManuallyButtons").style.display = "none"; document.getElementById("provincesManuallyButtons").style.display = "none";
@ -923,8 +923,8 @@ function editProvinces() {
restoreDefaultEvents(); restoreDefaultEvents();
clearMainTip(); clearMainTip();
const selected = body.querySelector('div.selected'); const selected = body.querySelector("div.selected");
if (selected) selected.classList.remove('selected'); if (selected) selected.classList.remove("selected");
} }
function enterAddProvinceMode() { function enterAddProvinceMode() {
@ -969,14 +969,14 @@ function editProvinces() {
const type = BurgsAndStates.getType(center, parent.port); const type = BurgsAndStates.getType(center, parent.port);
const coa = COA.generate(parent, kinship, P(0.1), type); const coa = COA.generate(parent, kinship, P(0.1), type);
coa.shield = COA.getShield(c, state); coa.shield = COA.getShield(c, state);
COArenderer.add('province', province, coa, point[0], point[1]); COArenderer.add("province", province, coa, point[0], point[1]);
provinces.push({i: province, state, center, burg, name, formName, fullName, color, coa}); provinces.push({i: province, state, center, burg, name, formName, fullName, color, coa});
cells.province[center] = province; cells.province[center] = province;
cells.c[center].forEach((c) => { cells.c[center].forEach(c => {
if (cells.h[c] < 20 || cells.state[c] !== state) return; if (cells.h[c] < 20 || cells.state[c] !== state) return;
if (provinces.find((p) => !p.removed && p.center === c)) return; if (provinces.find(p => !p.removed && p.center === c)) return;
cells.province[c] = province; cells.province[c] = province;
}); });
@ -985,7 +985,7 @@ function editProvinces() {
if (!layerIsOn("toggleProvinces")) toggleProvinces(); if (!layerIsOn("toggleProvinces")) toggleProvinces();
else drawProvinces(); else drawProvinces();
collectStatistics(); collectStatistics();
document.getElementById('provincesFilterState').value = state; document.getElementById("provincesFilterState").value = state;
provincesEditorAddLines(); provincesEditorAddLines();
} }
@ -998,9 +998,9 @@ function editProvinces() {
} }
function recolorProvinces() { function recolorProvinces() {
const state = +document.getElementById('provincesFilterState').value; const state = +document.getElementById("provincesFilterState").value;
pack.provinces.forEach((p) => { pack.provinces.forEach(p => {
if (!p || p.removed) return; if (!p || p.removed) return;
if (state !== -1 && p.state !== state) return; if (state !== -1 && p.state !== state) return;
const stateColor = pack.states[p.state].color; const stateColor = pack.states[p.state].color;
@ -1032,7 +1032,7 @@ function editProvinces() {
data += `${Math.round(provincePack.urban * populationRate * urbanization)}\n`; data += `${Math.round(provincePack.urban * populationRate * urbanization)}\n`;
}); });
const name = getFileName('Provinces') + '.csv'; const name = getFileName("Provinces") + ".csv";
downloadFile(data, name); downloadFile(data, name);
} }
@ -1045,10 +1045,9 @@ function editProvinces() {
Remove: function () { Remove: function () {
$(this).dialog("close"); $(this).dialog("close");
// remove data // remove emblems
pack.provinces = [0]; document.querySelectorAll("[id^='provinceCOA']").forEach(el => el.remove());
pack.cells.province = new Uint16Array(pack.cells.i.length); emblems.select("#provinceEmblems").selectAll("*").remove();
pack.states.forEach((s) => (s.provinces = []));
// remove data // remove data
pack.provinces = [0]; pack.provinces = [0];
@ -1082,8 +1081,8 @@ function editProvinces() {
} }
function closeProvincesEditor() { function closeProvincesEditor() {
provs.selectAll('text').call(d3.drag().on('drag', null)).attr('class', null); provs.selectAll("text").call(d3.drag().on("drag", null)).attr("class", null);
if (customization === 11) exitProvincesManualAssignment('close'); if (customization === 11) exitProvincesManualAssignment("close");
if (customization === 12) exitAddProvinceMode(); if (customization === 12) exitAddProvinceMode();
} }
} }

View file

@ -1,11 +1,11 @@
'use strict'; "use strict";
function editRegiment(selector) { function editRegiment(selector) {
if (customization) return; if (customization) return;
closeDialogs('.stable'); closeDialogs(".stable");
if (!layerIsOn('toggleMilitary')) toggleMilitary(); if (!layerIsOn("toggleMilitary")) toggleMilitary();
armies.selectAll(':scope > g').classed('draggable', true); armies.selectAll(":scope > g").classed("draggable", true);
armies.selectAll(':scope > g > g').call(d3.drag().on('drag', dragRegiment)); armies.selectAll(":scope > g > g").call(d3.drag().on("drag", dragRegiment));
elSelected = selector ? document.querySelector(selector) : d3.event.target.parentElement; // select g element elSelected = selector ? document.querySelector(selector) : d3.event.target.parentElement; // select g element
if (!pack.states[elSelected.dataset.state]) return; if (!pack.states[elSelected.dataset.state]) return;
if (!regiment()) return; if (!regiment()) return;
@ -23,22 +23,22 @@ function editRegiment(selector) {
modules.editRegiment = true; modules.editRegiment = true;
// add listeners // add listeners
document.getElementById('regimentNameRestore').addEventListener('click', restoreName); document.getElementById("regimentNameRestore").addEventListener("click", restoreName);
document.getElementById('regimentType').addEventListener('click', changeType); document.getElementById("regimentType").addEventListener("click", changeType);
document.getElementById('regimentName').addEventListener('change', changeName); document.getElementById("regimentName").addEventListener("change", changeName);
document.getElementById('regimentEmblem').addEventListener('input', changeEmblem); document.getElementById("regimentEmblem").addEventListener("input", changeEmblem);
document.getElementById('regimentEmblemSelect').addEventListener('click', selectEmblem); document.getElementById("regimentEmblemSelect").addEventListener("click", selectEmblem);
document.getElementById('regimentAttack').addEventListener('click', toggleAttack); document.getElementById("regimentAttack").addEventListener("click", toggleAttack);
document.getElementById('regimentRegenerateLegend').addEventListener('click', regenerateLegend); document.getElementById("regimentRegenerateLegend").addEventListener("click", regenerateLegend);
document.getElementById('regimentLegend').addEventListener('click', editLegend); document.getElementById("regimentLegend").addEventListener("click", editLegend);
document.getElementById('regimentSplit').addEventListener('click', splitRegiment); document.getElementById("regimentSplit").addEventListener("click", splitRegiment);
document.getElementById('regimentAdd').addEventListener('click', toggleAdd); document.getElementById("regimentAdd").addEventListener("click", toggleAdd);
document.getElementById('regimentAttach').addEventListener('click', toggleAttach); document.getElementById("regimentAttach").addEventListener("click", toggleAttach);
document.getElementById('regimentRemove').addEventListener('click', removeRegiment); document.getElementById("regimentRemove").addEventListener("click", removeRegiment);
// get regiment data element // get regiment data element
function regiment() { function regiment() {
return pack.states[elSelected.dataset.state].military.find((r) => r.i == elSelected.dataset.id); return pack.states[elSelected.dataset.state].military.find(r => r.i == elSelected.dataset.id);
} }
function updateRegimentData(regiment) { function updateRegimentData(regiment) {
@ -56,7 +56,7 @@ function editRegiment(selector) {
}) })
.join(""); .join("");
composition.querySelectorAll('input').forEach((el) => el.addEventListener('change', changeUnit)); composition.querySelectorAll("input").forEach(el => el.addEventListener("change", changeUnit));
} }
function drawBase() { function drawBase() {
@ -117,7 +117,7 @@ function editRegiment(selector) {
const reg = regiment(), const reg = regiment(),
regs = pack.states[elSelected.dataset.state].military; regs = pack.states[elSelected.dataset.state].military;
const name = Military.getName(reg, regs); const name = Military.getName(reg, regs);
elSelected.dataset.name = reg.name = document.getElementById('regimentName').value = name; elSelected.dataset.name = reg.name = document.getElementById("regimentName").value = name;
} }
function selectEmblem() { function selectEmblem() {
@ -128,8 +128,8 @@ function editRegiment(selector) {
} }
function changeEmblem() { function changeEmblem() {
const emblem = document.getElementById('regimentEmblem').value; const emblem = document.getElementById("regimentEmblem").value;
regiment().icon = elSelected.querySelector('.regimentIcon').innerHTML = emblem; regiment().icon = elSelected.querySelector(".regimentIcon").innerHTML = emblem;
} }
function changeUnit() { function changeUnit() {
@ -137,7 +137,7 @@ function editRegiment(selector) {
const reg = regiment(); const reg = regiment();
reg.u[u] = +this.value || 0; reg.u[u] = +this.value || 0;
reg.a = d3.sum(Object.values(reg.u)); reg.a = d3.sum(Object.values(reg.u));
elSelected.querySelector('text').innerHTML = Military.getTotal(reg); elSelected.querySelector("text").innerHTML = Military.getTotal(reg);
if (militaryOverviewRefresh.offsetParent) militaryOverviewRefresh.click(); if (militaryOverviewRefresh.offsetParent) militaryOverviewRefresh.click();
if (regimentsOverviewRefresh.offsetParent) regimentsOverviewRefresh.click(); if (regimentsOverviewRefresh.offsetParent) regimentsOverviewRefresh.click();
} }
@ -193,13 +193,13 @@ function editRegiment(selector) {
} }
function toggleAdd() { function toggleAdd() {
document.getElementById('regimentAdd').classList.toggle('pressed'); document.getElementById("regimentAdd").classList.toggle("pressed");
if (document.getElementById('regimentAdd').classList.contains('pressed')) { if (document.getElementById("regimentAdd").classList.contains("pressed")) {
viewbox.style('cursor', 'crosshair').on('click', addRegimentOnClick); viewbox.style("cursor", "crosshair").on("click", addRegimentOnClick);
tip('Click on map to create new regiment or fleet', true); tip("Click on map to create new regiment or fleet", true);
} else { } else {
clearMainTip(); clearMainTip();
viewbox.on('click', clicked).style('cursor', 'default'); viewbox.on("click", clicked).style("cursor", "default");
} }
} }
@ -222,15 +222,15 @@ function editRegiment(selector) {
} }
function toggleAttack() { function toggleAttack() {
document.getElementById('regimentAttack').classList.toggle('pressed'); document.getElementById("regimentAttack").classList.toggle("pressed");
if (document.getElementById('regimentAttack').classList.contains('pressed')) { if (document.getElementById("regimentAttack").classList.contains("pressed")) {
viewbox.style('cursor', 'crosshair').on('click', attackRegimentOnClick); viewbox.style("cursor", "crosshair").on("click", attackRegimentOnClick);
tip('Click on another regiment to initiate battle', true); tip("Click on another regiment to initiate battle", true);
armies.selectAll(':scope > g').classed('draggable', false); armies.selectAll(":scope > g").classed("draggable", false);
} else { } else {
clearMainTip(); clearMainTip();
armies.selectAll(':scope > g').classed('draggable', true); armies.selectAll(":scope > g").classed("draggable", true);
viewbox.on('click', clicked).style('cursor', 'default'); viewbox.on("click", clicked).style("cursor", "default");
} }
} }
@ -290,19 +290,19 @@ function editRegiment(selector) {
.remove(); .remove();
clearMainTip(); clearMainTip();
$('#regimentEditor').dialog('close'); $("#regimentEditor").dialog("close");
} }
function toggleAttach() { function toggleAttach() {
document.getElementById('regimentAttach').classList.toggle('pressed'); document.getElementById("regimentAttach").classList.toggle("pressed");
if (document.getElementById('regimentAttach').classList.contains('pressed')) { if (document.getElementById("regimentAttach").classList.contains("pressed")) {
viewbox.style('cursor', 'crosshair').on('click', attachRegimentOnClick); viewbox.style("cursor", "crosshair").on("click", attachRegimentOnClick);
tip('Click on another regiment to unite both regiments. The current regiment will be removed', true); tip("Click on another regiment to unite both regiments. The current regiment will be removed", true);
armies.selectAll(':scope > g').classed('draggable', false); armies.selectAll(":scope > g").classed("draggable", false);
} else { } else {
clearMainTip(); clearMainTip();
armies.selectAll(':scope > g').classed('draggable', true); armies.selectAll(":scope > g").classed("draggable", true);
viewbox.on('click', clicked).style('cursor', 'default'); viewbox.on("click", clicked).style("cursor", "default");
} }
} }
@ -323,19 +323,19 @@ function editRegiment(selector) {
} }
const reg = regiment(); // reg to be attached const reg = regiment(); // reg to be attached
const sel = pack.states[newState].military.find((r) => r.i == regSelected.dataset.id); // reg to attach to const sel = pack.states[newState].military.find(r => r.i == regSelected.dataset.id); // reg to attach to
for (const unit of options.military) { for (const unit of options.military) {
const u = unit.name; const u = unit.name;
if (reg.u[u]) sel.u[u] ? (sel.u[u] += reg.u[u]) : (sel.u[u] = reg.u[u]); if (reg.u[u]) sel.u[u] ? (sel.u[u] += reg.u[u]) : (sel.u[u] = reg.u[u]);
} }
sel.a = d3.sum(Object.values(sel.u)); // reg total sel.a = d3.sum(Object.values(sel.u)); // reg total
regSelected.querySelector('text').innerHTML = Military.getTotal(sel); // update selected reg total text regSelected.querySelector("text").innerHTML = Military.getTotal(sel); // update selected reg total text
// remove attached regiment // remove attached regiment
const military = pack.states[oldState].military; const military = pack.states[oldState].military;
military.splice(military.indexOf(reg), 1); military.splice(military.indexOf(reg), 1);
const index = notes.findIndex((n) => n.id === elSelected.id); const index = notes.findIndex(n => n.id === elSelected.id);
if (index != -1) notes.splice(index, 1); if (index != -1) notes.splice(index, 1);
elSelected.remove(); elSelected.remove();
@ -345,7 +345,7 @@ function editRegiment(selector) {
} }
function regenerateLegend() { function regenerateLegend() {
const index = notes.findIndex((n) => n.id === elSelected.id); const index = notes.findIndex(n => n.id === elSelected.id);
if (index != -1) notes.splice(index, 1); if (index != -1) notes.splice(index, 1);
const s = pack.states[elSelected.dataset.state]; const s = pack.states[elSelected.dataset.state];
@ -369,7 +369,7 @@ function editRegiment(selector) {
if (regIndex === -1) return; if (regIndex === -1) return;
military.splice(regIndex, 1); military.splice(regIndex, 1);
const index = notes.findIndex((n) => n.id === elSelected.id); const index = notes.findIndex(n => n.id === elSelected.id);
if (index != -1) notes.splice(index, 1); if (index != -1) notes.splice(index, 1);
elSelected.remove(); elSelected.remove();
@ -388,20 +388,20 @@ function editRegiment(selector) {
d3.select(this).raise(); d3.select(this).raise();
d3.select(this.parentNode).raise(); d3.select(this.parentNode).raise();
const reg = pack.states[this.dataset.state].military.find((r) => r.i == this.dataset.id); const reg = pack.states[this.dataset.state].military.find(r => r.i == this.dataset.id);
const size = +armies.attr('box-size'); const size = +armies.attr("box-size");
const w = reg.n ? size * 4 : size * 6; const w = reg.n ? size * 4 : size * 6;
const h = size * 2; const h = size * 2;
const x1 = (x) => rn(x - w / 2, 2); const x1 = x => rn(x - w / 2, 2);
const y1 = (y) => rn(y - size, 2); const y1 = y => rn(y - size, 2);
const baseRect = this.querySelector('rect'); const baseRect = this.querySelector("rect");
const text = this.querySelector('text'); const text = this.querySelector("text");
const iconRect = this.querySelectorAll('rect')[1]; const iconRect = this.querySelectorAll("rect")[1];
const icon = this.querySelector('.regimentIcon'); const icon = this.querySelector(".regimentIcon");
const self = elSelected === this; const self = elSelected === this;
const baseLine = viewbox.select('g#regimentBase > line'); const baseLine = viewbox.select("g#regimentBase > line");
d3.event.on("drag", function () { d3.event.on("drag", function () {
const x = (reg.x = d3.event.x), const x = (reg.x = d3.event.x),
@ -420,7 +420,7 @@ function editRegiment(selector) {
} }
function dragBase() { function dragBase() {
const baseLine = viewbox.select('g#regimentBase > line'); const baseLine = viewbox.select("g#regimentBase > line");
const reg = regiment(); const reg = regiment();
d3.event.on("drag", function () { d3.event.on("drag", function () {
@ -436,12 +436,12 @@ function editRegiment(selector) {
} }
function closeEditor() { function closeEditor() {
armies.selectAll(':scope > g').classed('draggable', false); armies.selectAll(":scope > g").classed("draggable", false);
armies.selectAll('g>g').call(d3.drag().on('drag', null)); armies.selectAll("g>g").call(d3.drag().on("drag", null));
viewbox.selectAll('g#regimentBase').remove(); viewbox.selectAll("g#regimentBase").remove();
document.getElementById('regimentAdd').classList.remove('pressed'); document.getElementById("regimentAdd").classList.remove("pressed");
document.getElementById('regimentAttack').classList.remove('pressed'); document.getElementById("regimentAttack").classList.remove("pressed");
document.getElementById('regimentAttach').classList.remove('pressed'); document.getElementById("regimentAttach").classList.remove("pressed");
restoreDefaultEvents(); restoreDefaultEvents();
elSelected = null; elSelected = null;
} }

View file

@ -1,10 +1,10 @@
'use strict'; "use strict";
function editReliefIcon() { function editReliefIcon() {
if (customization) return; if (customization) return;
closeDialogs('.stable'); closeDialogs(".stable");
if (!layerIsOn('toggleRelief')) toggleRelief(); if (!layerIsOn("toggleRelief")) toggleRelief();
terrain.selectAll('use').call(d3.drag().on('drag', dragReliefIcon)).classed('draggable', true); terrain.selectAll("use").call(d3.drag().on("drag", dragReliefIcon)).classed("draggable", true);
elSelected = d3.select(d3.event.target); elSelected = d3.select(d3.event.target);
restoreEditMode(); restoreEditMode();
@ -23,24 +23,24 @@ function editReliefIcon() {
modules.editReliefIcon = true; modules.editReliefIcon = true;
// add listeners // add listeners
document.getElementById('reliefIndividual').addEventListener('click', enterIndividualMode); document.getElementById("reliefIndividual").addEventListener("click", enterIndividualMode);
document.getElementById('reliefBulkAdd').addEventListener('click', enterBulkAddMode); document.getElementById("reliefBulkAdd").addEventListener("click", enterBulkAddMode);
document.getElementById('reliefBulkRemove').addEventListener('click', enterBulkRemoveMode); document.getElementById("reliefBulkRemove").addEventListener("click", enterBulkRemoveMode);
document.getElementById('reliefSize').addEventListener('input', changeIconSize); document.getElementById("reliefSize").addEventListener("input", changeIconSize);
document.getElementById('reliefSizeNumber').addEventListener('input', changeIconSize); document.getElementById("reliefSizeNumber").addEventListener("input", changeIconSize);
document.getElementById('reliefEditorSet').addEventListener('change', changeIconsSet); document.getElementById("reliefEditorSet").addEventListener("change", changeIconsSet);
reliefIconsDiv.querySelectorAll('svg').forEach((el) => el.addEventListener('click', changeIcon)); reliefIconsDiv.querySelectorAll("svg").forEach(el => el.addEventListener("click", changeIcon));
document.getElementById('reliefEditStyle').addEventListener('click', () => editStyle('terrain')); document.getElementById("reliefEditStyle").addEventListener("click", () => editStyle("terrain"));
document.getElementById('reliefCopy').addEventListener('click', copyIcon); document.getElementById("reliefCopy").addEventListener("click", copyIcon);
document.getElementById('reliefMoveFront').addEventListener('click', () => elSelected.raise()); document.getElementById("reliefMoveFront").addEventListener("click", () => elSelected.raise());
document.getElementById('reliefMoveBack').addEventListener('click', () => elSelected.lower()); document.getElementById("reliefMoveBack").addEventListener("click", () => elSelected.lower());
document.getElementById('reliefRemove').addEventListener('click', removeIcon); document.getElementById("reliefRemove").addEventListener("click", removeIcon);
function dragReliefIcon() { function dragReliefIcon() {
const dx = +this.getAttribute('x') - d3.event.x; const dx = +this.getAttribute("x") - d3.event.x;
const dy = +this.getAttribute('y') - d3.event.y; const dy = +this.getAttribute("y") - d3.event.y;
d3.event.on("drag", function () { d3.event.on("drag", function () {
const x = d3.event.x, const x = d3.event.x,
@ -68,18 +68,18 @@ function editReliefIcon() {
} }
function updateReliefSizeInput() { function updateReliefSizeInput() {
const size = +elSelected.attr('width'); const size = +elSelected.attr("width");
reliefSize.value = reliefSizeNumber.value = rn(size); reliefSize.value = reliefSizeNumber.value = rn(size);
} }
function enterIndividualMode() { function enterIndividualMode() {
reliefTools.querySelectorAll('button.pressed').forEach((b) => b.classList.remove('pressed')); reliefTools.querySelectorAll("button.pressed").forEach(b => b.classList.remove("pressed"));
reliefIndividual.classList.add('pressed'); reliefIndividual.classList.add("pressed");
reliefSizeDiv.style.display = 'block'; reliefSizeDiv.style.display = "block";
reliefRadiusDiv.style.display = 'none'; reliefRadiusDiv.style.display = "none";
reliefSpacingDiv.style.display = 'none'; reliefSpacingDiv.style.display = "none";
reliefIconsSeletionAny.style.display = 'none'; reliefIconsSeletionAny.style.display = "none";
removeCircle(); removeCircle();
updateReliefSizeInput(); updateReliefSizeInput();
@ -88,13 +88,13 @@ function editReliefIcon() {
} }
function enterBulkAddMode() { function enterBulkAddMode() {
reliefTools.querySelectorAll('button.pressed').forEach((b) => b.classList.remove('pressed')); reliefTools.querySelectorAll("button.pressed").forEach(b => b.classList.remove("pressed"));
reliefBulkAdd.classList.add('pressed'); reliefBulkAdd.classList.add("pressed");
reliefSizeDiv.style.display = 'block'; reliefSizeDiv.style.display = "block";
reliefRadiusDiv.style.display = 'block'; reliefRadiusDiv.style.display = "block";
reliefSpacingDiv.style.display = 'block'; reliefSpacingDiv.style.display = "block";
reliefIconsSeletionAny.style.display = 'none'; reliefIconsSeletionAny.style.display = "none";
const pressedType = reliefIconsDiv.querySelector("svg.pressed"); const pressedType = reliefIconsDiv.querySelector("svg.pressed");
if (pressedType.id === "reliefIconsSeletionAny") { if (pressedType.id === "reliefIconsSeletionAny") {
@ -103,8 +103,8 @@ function editReliefIcon() {
reliefIconsDiv.querySelector("svg").classList.add("pressed"); reliefIconsDiv.querySelector("svg").classList.add("pressed");
} }
viewbox.style('cursor', 'crosshair').call(d3.drag().on('start', dragToAdd)).on('touchmove mousemove', moveBrush); viewbox.style("cursor", "crosshair").call(d3.drag().on("start", dragToAdd)).on("touchmove mousemove", moveBrush);
tip('Drag to place relief icons within radius', true); tip("Drag to place relief icons within radius", true);
} }
function moveBrush() { function moveBrush() {
@ -172,13 +172,13 @@ function editReliefIcon() {
} }
function enterBulkRemoveMode() { function enterBulkRemoveMode() {
reliefTools.querySelectorAll('button.pressed').forEach((b) => b.classList.remove('pressed')); reliefTools.querySelectorAll("button.pressed").forEach(b => b.classList.remove("pressed"));
reliefBulkRemove.classList.add('pressed'); reliefBulkRemove.classList.add("pressed");
reliefSizeDiv.style.display = 'none'; reliefSizeDiv.style.display = "none";
reliefRadiusDiv.style.display = 'block'; reliefRadiusDiv.style.display = "block";
reliefSpacingDiv.style.display = 'none'; reliefSpacingDiv.style.display = "none";
reliefIconsSeletionAny.style.display = 'inline-block'; reliefIconsSeletionAny.style.display = "inline-block";
viewbox.style("cursor", "crosshair").call(d3.drag().on("start", dragToRemove)).on("touchmove mousemove", moveBrush); viewbox.style("cursor", "crosshair").call(d3.drag().on("start", dragToRemove)).on("touchmove mousemove", moveBrush);
tip("Drag to remove relief icons in radius", true); tip("Drag to remove relief icons in radius", true);
@ -201,13 +201,13 @@ function editReliefIcon() {
d3.event.on("drag", function () { d3.event.on("drag", function () {
const p = d3.mouse(this); const p = d3.mouse(this);
moveCircle(p[0], p[1], r); moveCircle(p[0], p[1], r);
tree.findAll(p[0], p[1], r).forEach((f) => f[2].remove()); tree.findAll(p[0], p[1], r).forEach(f => f[2].remove());
}); });
} }
function changeIconSize() { function changeIconSize() {
const size = +reliefSizeNumber.value; const size = +reliefSizeNumber.value;
if (!reliefIndividual.classList.contains('pressed')) return; if (!reliefIndividual.classList.contains("pressed")) return;
const shift = (size - +elSelected.attr("width")) / 2; const shift = (size - +elSelected.attr("width")) / 2;
elSelected.attr("width", size).attr("height", size); elSelected.attr("width", size).attr("height", size);
@ -223,14 +223,14 @@ function editReliefIcon() {
} }
function changeIcon() { function changeIcon() {
if (this.classList.contains('pressed')) return; if (this.classList.contains("pressed")) return;
reliefIconsDiv.querySelectorAll("svg.pressed").forEach(b => b.classList.remove("pressed")); reliefIconsDiv.querySelectorAll("svg.pressed").forEach(b => b.classList.remove("pressed"));
this.classList.add("pressed"); this.classList.add("pressed");
if (reliefIndividual.classList.contains('pressed')) { if (reliefIndividual.classList.contains("pressed")) {
const type = this.dataset.type; const type = this.dataset.type;
elSelected.attr('href', type); elSelected.attr("href", type);
} }
} }
@ -245,8 +245,8 @@ function editReliefIcon() {
y -= 3; y -= 3;
} }
copy.setAttribute('x', x); copy.setAttribute("x", x);
copy.setAttribute('y', y); copy.setAttribute("y", y);
parent.insertBefore(copy, null); parent.insertBefore(copy, null);
} }
@ -280,7 +280,7 @@ function editReliefIcon() {
} }
function closeReliefEditor() { function closeReliefEditor() {
terrain.selectAll('use').call(d3.drag().on('drag', null)).classed('draggable', false); terrain.selectAll("use").call(d3.drag().on("drag", null)).classed("draggable", false);
removeCircle(); removeCircle();
unselect(); unselect();
clearMainTip(); clearMainTip();