mirror of
https://github.com/Azgaar/Fantasy-Map-Generator.git
synced 2025-12-22 03:51:23 +01:00
Merge branch 'Azgaar:master' into mass-burg-assignation
This commit is contained in:
commit
9c206a3813
206 changed files with 34855 additions and 2566 deletions
|
|
@ -1,24 +1,8 @@
|
|||
"use strict";
|
||||
|
||||
const MIN_LAND_HEIGHT = 20;
|
||||
|
||||
const names = [
|
||||
"Marine",
|
||||
"Hot desert",
|
||||
"Cold desert",
|
||||
"Savanna",
|
||||
"Grassland",
|
||||
"Tropical seasonal forest",
|
||||
"Temperate deciduous forest",
|
||||
"Tropical rainforest",
|
||||
"Temperate rainforest",
|
||||
"Taiga",
|
||||
"Tundra",
|
||||
"Glacier",
|
||||
"Wetland"
|
||||
];
|
||||
|
||||
window.Biomes = (function () {
|
||||
const MIN_LAND_HEIGHT = 20;
|
||||
|
||||
const getDefault = () => {
|
||||
const name = [
|
||||
"Marine",
|
||||
|
|
@ -52,7 +36,7 @@ window.Biomes = (function () {
|
|||
"#0b9131"
|
||||
];
|
||||
const habitability = [0, 4, 10, 22, 30, 50, 100, 80, 90, 12, 4, 0, 12];
|
||||
const iconsDensity = [0, 3, 2, 120, 120, 120, 120, 150, 150, 100, 5, 0, 150];
|
||||
const iconsDensity = [0, 3, 2, 120, 120, 120, 120, 150, 150, 100, 5, 0, 250];
|
||||
const icons = [
|
||||
{},
|
||||
{dune: 3, cactus: 6, deadTree: 1},
|
||||
|
|
|
|||
|
|
@ -1,32 +1,25 @@
|
|||
"use strict";
|
||||
|
||||
window.BurgsAndStates = (function () {
|
||||
const generate = function () {
|
||||
window.BurgsAndStates = (() => {
|
||||
const generate = () => {
|
||||
const {cells, cultures} = pack;
|
||||
const n = cells.i.length;
|
||||
|
||||
cells.burg = new Uint16Array(n); // cell burg
|
||||
cells.road = new Uint16Array(n); // cell road power
|
||||
cells.crossroad = new Uint16Array(n); // cell crossroad power
|
||||
|
||||
const burgs = (pack.burgs = placeCapitals());
|
||||
pack.states = createStates();
|
||||
const capitalRoutes = Routes.getRoads();
|
||||
|
||||
placeTowns();
|
||||
expandStates();
|
||||
normalizeStates();
|
||||
const townRoutes = Routes.getTrails();
|
||||
specifyBurgs();
|
||||
|
||||
const oceanRoutes = Routes.getSearoutes();
|
||||
|
||||
collectStatistics();
|
||||
assignColors();
|
||||
|
||||
generateCampaigns();
|
||||
generateDiplomacy();
|
||||
Routes.draw(capitalRoutes, townRoutes, oceanRoutes);
|
||||
drawBurgs();
|
||||
|
||||
function placeCapitals() {
|
||||
|
|
@ -81,7 +74,7 @@ window.BurgsAndStates = (function () {
|
|||
const colors = getColors(burgs.length - 1);
|
||||
const each5th = each(5);
|
||||
|
||||
burgs.forEach(function (b, i) {
|
||||
burgs.forEach((b, i) => {
|
||||
if (!i) return; // skip first element
|
||||
|
||||
// burgs data
|
||||
|
|
@ -138,9 +131,8 @@ window.BurgsAndStates = (function () {
|
|||
while (burgsAdded < burgsNumber && spacing > 1) {
|
||||
for (let i = 0; burgsAdded < burgsNumber && i < sorted.length; i++) {
|
||||
if (cells.burg[sorted[i]]) continue;
|
||||
const cell = sorted[i],
|
||||
x = cells.p[cell][0],
|
||||
y = cells.p[cell][1];
|
||||
const cell = sorted[i];
|
||||
const [x, y] = cells.p[cell];
|
||||
const s = spacing * gauss(1, 0.3, 0.2, 2, 2); // randomize to make placement not uniform
|
||||
if (burgsTree.find(x, y, s) !== undefined) continue; // to close to existing burg
|
||||
const burg = burgs.length;
|
||||
|
|
@ -164,12 +156,10 @@ window.BurgsAndStates = (function () {
|
|||
};
|
||||
|
||||
// define burg coordinates, coa, port status and define details
|
||||
const specifyBurgs = function () {
|
||||
const specifyBurgs = () => {
|
||||
TIME && console.time("specifyBurgs");
|
||||
const cells = pack.cells,
|
||||
vertices = pack.vertices,
|
||||
features = pack.features,
|
||||
temp = grid.cells.temp;
|
||||
const {cells, features} = pack;
|
||||
const temp = grid.cells.temp;
|
||||
|
||||
for (const b of pack.burgs) {
|
||||
if (!b.i || b.lock) continue;
|
||||
|
|
@ -185,12 +175,12 @@ window.BurgsAndStates = (function () {
|
|||
} else b.port = 0;
|
||||
|
||||
// define burg population (keep urbanization at about 10% rate)
|
||||
b.population = rn(Math.max((cells.s[i] + cells.road[i] / 2) / 8 + b.i / 1000 + (i % 100) / 1000, 0.1), 3);
|
||||
b.population = rn(Math.max(cells.s[i] / 8 + b.i / 1000 + (i % 100) / 1000, 0.1), 3);
|
||||
if (b.capital) b.population = rn(b.population * 1.3, 3); // increase capital population
|
||||
|
||||
if (b.port) {
|
||||
b.population = b.population * 1.3; // increase port population
|
||||
const [x, y] = getMiddlePoint(i, haven);
|
||||
const [x, y] = getCloseToEdgePoint(i, haven);
|
||||
b.x = x;
|
||||
b.y = y;
|
||||
}
|
||||
|
|
@ -231,7 +221,24 @@ window.BurgsAndStates = (function () {
|
|||
TIME && console.timeEnd("specifyBurgs");
|
||||
};
|
||||
|
||||
const getType = function (i, port) {
|
||||
function getCloseToEdgePoint(cell1, cell2) {
|
||||
const {cells, vertices} = pack;
|
||||
|
||||
const [x0, y0] = cells.p[cell1];
|
||||
|
||||
const commonVertices = cells.v[cell1].filter(vertex => vertices.c[vertex].some(cell => cell === cell2));
|
||||
const [x1, y1] = vertices.p[commonVertices[0]];
|
||||
const [x2, y2] = vertices.p[commonVertices[1]];
|
||||
const xEdge = (x1 + x2) / 2;
|
||||
const yEdge = (y1 + y2) / 2;
|
||||
|
||||
const x = rn(x0 + 0.95 * (xEdge - x0), 2);
|
||||
const y = rn(y0 + 0.95 * (yEdge - y0), 2);
|
||||
|
||||
return [x, y];
|
||||
}
|
||||
|
||||
const getType = (i, port) => {
|
||||
const cells = pack.cells;
|
||||
if (port) return "Naval";
|
||||
if (cells.haven[i] && pack.features[cells.f[cells.haven[i]]].type === "lake") return "Lake";
|
||||
|
|
@ -246,23 +253,26 @@ window.BurgsAndStates = (function () {
|
|||
return "Generic";
|
||||
};
|
||||
|
||||
const defineBurgFeatures = function (newburg) {
|
||||
const cells = pack.cells;
|
||||
const defineBurgFeatures = burg => {
|
||||
const {cells} = pack;
|
||||
|
||||
pack.burgs
|
||||
.filter(b => (newburg ? b.i == newburg.i : b.i && !b.removed))
|
||||
.filter(b => (burg ? b.i == burg.i : b.i && !b.removed && !b.lock))
|
||||
.forEach(b => {
|
||||
const pop = b.population;
|
||||
b.citadel = b.capital || (pop > 50 && P(0.75)) || P(0.5) ? 1 : 0;
|
||||
b.plaza = pop > 50 || (pop > 30 && P(0.75)) || (pop > 10 && P(0.5)) || P(0.25) ? 1 : 0;
|
||||
b.walls = b.capital || pop > 30 || (pop > 20 && P(0.75)) || (pop > 10 && P(0.5)) || P(0.2) ? 1 : 0;
|
||||
b.shanty = pop > 60 || (pop > 40 && P(0.75)) || (pop > 20 && b.walls && P(0.4)) ? 1 : 0;
|
||||
b.citadel = Number(b.capital || (pop > 50 && P(0.75)) || (pop > 15 && P(0.5)) || P(0.1));
|
||||
b.plaza = Number(pop > 20 || (pop > 10 && P(0.8)) || (pop > 4 && P(0.7)) || P(0.6));
|
||||
b.walls = Number(b.capital || pop > 30 || (pop > 20 && P(0.75)) || (pop > 10 && P(0.5)) || P(0.1));
|
||||
b.shanty = Number(pop > 60 || (pop > 40 && P(0.75)) || (pop > 20 && b.walls && P(0.4)));
|
||||
const religion = cells.religion[b.cell];
|
||||
const theocracy = pack.states[b.state].form === "Theocracy";
|
||||
b.temple = (religion && theocracy) || pop > 50 || (pop > 35 && P(0.75)) || (pop > 20 && P(0.5)) ? 1 : 0;
|
||||
b.temple = Number(
|
||||
(religion && theocracy && P(0.5)) || pop > 50 || (pop > 35 && P(0.75)) || (pop > 20 && P(0.5))
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const drawBurgs = function () {
|
||||
const drawBurgs = () => {
|
||||
TIME && console.time("drawBurgs");
|
||||
|
||||
// remove old data
|
||||
|
|
@ -360,7 +370,7 @@ window.BurgsAndStates = (function () {
|
|||
};
|
||||
|
||||
// expand cultures across the map (Dijkstra-like algorithm)
|
||||
const expandStates = function () {
|
||||
const expandStates = () => {
|
||||
TIME && console.time("expandStates");
|
||||
const {cells, states, cultures, burgs} = pack;
|
||||
|
||||
|
|
@ -456,7 +466,7 @@ window.BurgsAndStates = (function () {
|
|||
TIME && console.timeEnd("expandStates");
|
||||
};
|
||||
|
||||
const normalizeStates = function () {
|
||||
const normalizeStates = () => {
|
||||
TIME && console.time("normalizeStates");
|
||||
const cells = pack.cells,
|
||||
burgs = pack.burgs;
|
||||
|
|
@ -478,7 +488,7 @@ window.BurgsAndStates = (function () {
|
|||
|
||||
// Resets the cultures of all burgs and states to their
|
||||
// cell or center cell's (respectively) culture.
|
||||
const updateCultures = function () {
|
||||
const updateCultures = () => {
|
||||
TIME && console.time("updateCulturesForBurgsAndStates");
|
||||
|
||||
// Assign the culture associated with the burgs cell.
|
||||
|
|
@ -503,7 +513,7 @@ window.BurgsAndStates = (function () {
|
|||
};
|
||||
|
||||
// calculate states data like area, population etc.
|
||||
const collectStatistics = function () {
|
||||
const collectStatistics = () => {
|
||||
TIME && console.time("collectStatistics");
|
||||
const {cells, states} = pack;
|
||||
|
||||
|
|
@ -541,7 +551,7 @@ window.BurgsAndStates = (function () {
|
|||
TIME && console.timeEnd("collectStatistics");
|
||||
};
|
||||
|
||||
const assignColors = function () {
|
||||
const assignColors = () => {
|
||||
TIME && console.time("assignColors");
|
||||
const colors = ["#66c2a5", "#fc8d62", "#8da0cb", "#e78ac3", "#a6d854", "#ffd92f"]; // d3.schemeSet2;
|
||||
|
||||
|
|
@ -577,6 +587,7 @@ window.BurgsAndStates = (function () {
|
|||
Expedition: 1,
|
||||
Crusade: 1
|
||||
};
|
||||
|
||||
const generateCampaign = state => {
|
||||
const neighbors = state.neighbors.length ? state.neighbors : [0];
|
||||
return neighbors
|
||||
|
|
@ -590,7 +601,7 @@ window.BurgsAndStates = (function () {
|
|||
};
|
||||
|
||||
// generate historical conflicts of each state
|
||||
const generateCampaigns = function () {
|
||||
const generateCampaigns = () => {
|
||||
pack.states.forEach(s => {
|
||||
if (!s.i || s.removed) return;
|
||||
s.campaigns = generateCampaign(s);
|
||||
|
|
@ -598,7 +609,7 @@ window.BurgsAndStates = (function () {
|
|||
};
|
||||
|
||||
// generate Diplomatic Relationships
|
||||
const generateDiplomacy = function () {
|
||||
const generateDiplomacy = () => {
|
||||
TIME && console.time("generateDiplomacy");
|
||||
const cells = pack.cells,
|
||||
states = pack.states;
|
||||
|
|
@ -783,7 +794,7 @@ window.BurgsAndStates = (function () {
|
|||
};
|
||||
|
||||
// select a forms for listed or all valid states
|
||||
const defineStateForms = function (list) {
|
||||
const defineStateForms = list => {
|
||||
TIME && console.time("defineStateForms");
|
||||
const states = pack.states.filter(s => s.i && !s.removed && !s.lock);
|
||||
if (states.length < 1) return;
|
||||
|
|
@ -859,9 +870,10 @@ window.BurgsAndStates = (function () {
|
|||
if (P(0.3) && s.diplomacy.includes("Vassal")) return "Protectorate"; // some vassals
|
||||
}
|
||||
|
||||
if (base === 16 && (form === "Empire" || form === "Kingdom")) return "Khaganate"; // Turkic
|
||||
if (base === 31 && (form === "Empire" || form === "Kingdom")) return "Khanate"; // Mongolian
|
||||
if (base === 16 && form === "Principality") return "Beylik"; // Turkic
|
||||
if (base === 5 && (form === "Empire" || form === "Kingdom")) return "Tsardom"; // Ruthenian
|
||||
if ([16, 31].includes(base) && (form === "Empire" || form === "Kingdom")) return "Khaganate"; // Turkic, Mongolian
|
||||
if (base === 16 && (form === "Empire" || form === "Kingdom")) return "Khaganate"; // Turkic
|
||||
if (base === 12 && (form === "Kingdom" || form === "Grand Duchy")) return "Shogunate"; // Japanese
|
||||
if ([18, 17].includes(base) && form === "Empire") return "Caliphate"; // Arabic, Berber
|
||||
if (base === 18 && (form === "Grand Duchy" || form === "Duchy")) return "Emirate"; // Arabic
|
||||
|
|
@ -930,14 +942,14 @@ window.BurgsAndStates = (function () {
|
|||
"Marches"
|
||||
];
|
||||
|
||||
const getFullName = function (s) {
|
||||
if (!s.formName) return s.name;
|
||||
if (!s.name && s.formName) return "The " + s.formName;
|
||||
const adjName = adjForms.includes(s.formName) && !/-| /.test(s.name);
|
||||
return adjName ? `${getAdjective(s.name)} ${s.formName}` : `${s.formName} of ${s.name}`;
|
||||
const getFullName = state => {
|
||||
if (!state.formName) return state.name;
|
||||
if (!state.name && state.formName) return "The " + state.formName;
|
||||
const adjName = adjForms.includes(state.formName) && !/-| /.test(state.name);
|
||||
return adjName ? `${getAdjective(state.name)} ${state.formName}` : `${state.formName} of ${state.name}`;
|
||||
};
|
||||
|
||||
const generateProvinces = function (regenerate = false, regenerateInLockedStates = false) {
|
||||
const generateProvinces = (regenerate = false, regenerateInLockedStates = false) => {
|
||||
TIME && console.time("generateProvinces");
|
||||
const localSeed = regenerate ? generateSeed() : seed;
|
||||
Math.random = aleaPRNG(localSeed);
|
||||
|
|
@ -1125,14 +1137,14 @@ window.BurgsAndStates = (function () {
|
|||
const isleGroup = !singleIsle && !provCells.find(i => pack.features[cells.f[i]].group !== "isle");
|
||||
const colony = !singleIsle && !isleGroup && P(0.5) && !isPassable(s.center, center);
|
||||
|
||||
const name = (function () {
|
||||
const name = (() => {
|
||||
const colonyName = colony && P(0.8) && getColonyName();
|
||||
if (colonyName) return colonyName;
|
||||
if (burgCell && P(0.5)) return burgs[burg].name;
|
||||
return Names.getState(Names.getCultureShort(c), c);
|
||||
})();
|
||||
|
||||
const formName = (function () {
|
||||
const formName = (() => {
|
||||
if (singleIsle) return "Island";
|
||||
if (isleGroup) return "Islands";
|
||||
if (colony) return "Colony";
|
||||
|
|
|
|||
|
|
@ -71,28 +71,31 @@ window.Cultures = (function () {
|
|||
return;
|
||||
}
|
||||
|
||||
const cell = (c.center = placeCenter(c.sort ? c.sort : i => cells.s[i]));
|
||||
centers.add(cells.p[cell]);
|
||||
const sortingFn = c.sort ? c.sort : i => cells.s[i];
|
||||
const center = placeCenter(sortingFn);
|
||||
|
||||
centers.add(cells.p[center]);
|
||||
c.center = center;
|
||||
c.i = newId;
|
||||
delete c.odd;
|
||||
delete c.sort;
|
||||
c.color = colors[i];
|
||||
c.type = defineCultureType(cell);
|
||||
c.type = defineCultureType(center);
|
||||
c.expansionism = defineCultureExpansionism(c.type);
|
||||
c.origins = [0];
|
||||
c.code = abbreviate(c.name, codes);
|
||||
codes.push(c.code);
|
||||
cultureIds[cell] = newId;
|
||||
cultureIds[center] = newId;
|
||||
if (emblemShape === "random") c.shield = getRandomShield();
|
||||
});
|
||||
|
||||
cells.culture = cultureIds;
|
||||
|
||||
function placeCenter(v) {
|
||||
function placeCenter(sortingFn) {
|
||||
let spacing = (graphWidth + graphHeight) / 2 / count;
|
||||
const MAX_ATTEMPTS = 100;
|
||||
|
||||
const sorted = [...populated].sort((a, b) => v(b) - v(a));
|
||||
const sorted = [...populated].sort((a, b) => sortingFn(b) - sortingFn(a));
|
||||
const max = Math.floor(sorted.length / 2);
|
||||
|
||||
let cellId = 0;
|
||||
|
|
@ -187,12 +190,13 @@ window.Cultures = (function () {
|
|||
name = Names.getCulture(culture, 5, 8, "");
|
||||
base = pack.cultures[culture].base;
|
||||
}
|
||||
|
||||
const code = abbreviate(
|
||||
name,
|
||||
pack.cultures.map(c => c.code)
|
||||
);
|
||||
const i = pack.cultures.length;
|
||||
const color = d3.color(d3.scaleSequential(d3.interpolateRainbow)(Math.random())).hex();
|
||||
const color = getRandomColor();
|
||||
|
||||
// define emblem shape
|
||||
let shield = culture.shield;
|
||||
|
|
@ -211,7 +215,7 @@ window.Cultures = (function () {
|
|||
area: 0,
|
||||
rural: 0,
|
||||
urban: 0,
|
||||
origins: [0],
|
||||
origins: [pack.cells.culture[center]],
|
||||
code,
|
||||
shield
|
||||
});
|
||||
|
|
|
|||
|
|
@ -243,10 +243,12 @@ export function resolveVersionConflicts(version) {
|
|||
rivers.selectAll("path").each(function () {
|
||||
const i = +this.id.slice(5);
|
||||
const length = this.getTotalLength() / 2;
|
||||
const s = this.getPointAtLength(length),
|
||||
e = this.getPointAtLength(0);
|
||||
const source = findCell(s.x, s.y),
|
||||
mouth = findCell(e.x, e.y);
|
||||
if (!length) return;
|
||||
|
||||
const s = this.getPointAtLength(length);
|
||||
const e = this.getPointAtLength(0);
|
||||
const source = findCell(s.x, s.y);
|
||||
const mouth = findCell(e.x, e.y);
|
||||
const name = Rivers.getName(mouth);
|
||||
const type = length < 25 ? rw({Creek: 9, River: 3, Brook: 3, Stream: 1}) : "River";
|
||||
pack.rivers.push({i, parent: 0, length, source, mouth, basin: i, name, type});
|
||||
|
|
@ -736,4 +738,189 @@ export function resolveVersionConflicts(version) {
|
|||
.style("display", "none");
|
||||
vignette.append("rect").attr("x", 0).attr("y", 0).attr("width", "100%").attr("height", "100%");
|
||||
}
|
||||
|
||||
if (version < 1.96) {
|
||||
// v1.96 added ocean rendering for heightmap
|
||||
terrs.selectAll("*").remove();
|
||||
|
||||
const opacity = terrs.attr("opacity");
|
||||
const filter = terrs.attr("filter");
|
||||
const scheme = terrs.attr("scheme") || "bright";
|
||||
const terracing = terrs.attr("terracing");
|
||||
const skip = terrs.attr("skip");
|
||||
const relax = terrs.attr("relax");
|
||||
|
||||
const curveTypes = {0: "curveBasisClosed", 1: "curveLinear", 2: "curveStep"};
|
||||
const curve = curveTypes[terrs.attr("curve")] || "curveBasisClosed";
|
||||
|
||||
terrs
|
||||
.attr("opacity", null)
|
||||
.attr("filter", null)
|
||||
.attr("mask", null)
|
||||
.attr("scheme", null)
|
||||
.attr("terracing", null)
|
||||
.attr("skip", null)
|
||||
.attr("relax", null)
|
||||
.attr("curve", null);
|
||||
|
||||
terrs
|
||||
.append("g")
|
||||
.attr("id", "oceanHeights")
|
||||
.attr("data-render", 0)
|
||||
.attr("opacity", opacity)
|
||||
.attr("filter", filter)
|
||||
.attr("scheme", scheme)
|
||||
.attr("terracing", 0)
|
||||
.attr("skip", 0)
|
||||
.attr("relax", 1)
|
||||
.attr("curve", curve);
|
||||
|
||||
terrs
|
||||
.append("g")
|
||||
.attr("id", "landHeights")
|
||||
.attr("opacity", opacity)
|
||||
.attr("scheme", scheme)
|
||||
.attr("filter", filter)
|
||||
.attr("terracing", terracing)
|
||||
.attr("skip", skip)
|
||||
.attr("relax", relax)
|
||||
.attr("curve", curve)
|
||||
.attr("mask", "url(#land)");
|
||||
|
||||
if (layerIsOn("toggleHeight")) drawHeightmap();
|
||||
|
||||
// v1.96.00 moved scaleBar options from units editor to style
|
||||
d3.select("#scaleBar").remove();
|
||||
|
||||
scaleBar = svg
|
||||
.insert("g", "#viewbox + *")
|
||||
.attr("id", "scaleBar")
|
||||
.attr("opacity", 1)
|
||||
.attr("fill", "#353540")
|
||||
.attr("data-bar-size", 2)
|
||||
.attr("font-size", 10)
|
||||
.attr("data-x", 99)
|
||||
.attr("data-y", 99)
|
||||
.attr("data-label", "");
|
||||
|
||||
scaleBar
|
||||
.append("rect")
|
||||
.attr("id", "scaleBarBack")
|
||||
.attr("opacity", 0.2)
|
||||
.attr("fill", "#ffffff")
|
||||
.attr("stroke", "#000000")
|
||||
.attr("stroke-width", 1)
|
||||
.attr("filter", "url(#blur5)")
|
||||
.attr("data-top", 20)
|
||||
.attr("data-right", 15)
|
||||
.attr("data-bottom", 15)
|
||||
.attr("data-left", 10);
|
||||
|
||||
drawScaleBar(scaleBar, scale);
|
||||
fitScaleBar(scaleBar, svgWidth, svgHeight);
|
||||
|
||||
if (!layerIsOn("toggleScaleBar")) scaleBar.style("display", "none");
|
||||
|
||||
// v1.96.00 changed coloring approach for regiments
|
||||
armies.selectAll(":scope > g").each(function () {
|
||||
const fill = this.getAttribute("fill");
|
||||
if (!fill) return;
|
||||
const darkerColor = d3.color(fill).darker().hex();
|
||||
this.setAttribute("color", darkerColor);
|
||||
this.querySelectorAll("g > rect:nth-child(2)").forEach(rect => {
|
||||
rect.setAttribute("fill", "currentColor");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (version < 1.97) {
|
||||
// v1.97.00 changed MFCG link to an arbitrary preview URL
|
||||
options.villageMaxPopulation = 2000;
|
||||
options.showBurgPreview = options.showMFCGMap;
|
||||
delete options.showMFCGMap;
|
||||
|
||||
pack.burgs.forEach(burg => {
|
||||
if (!burg.i || burg.removed) return;
|
||||
|
||||
if (burg.MFCG) {
|
||||
burg.link = getBurgLink(burg);
|
||||
delete burg.MFCG;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (version < 1.98) {
|
||||
// v1.98.00 changed compass layer and rose element id
|
||||
const rose = compass.select("use");
|
||||
rose.attr("xlink:href", "#defs-compass-rose");
|
||||
|
||||
if (!compass.selectAll("*").size()) {
|
||||
compass.style("display", "none");
|
||||
compass.append("use").attr("xlink:href", "#defs-compass-rose");
|
||||
shiftCompass();
|
||||
}
|
||||
}
|
||||
|
||||
if (version < 1.99) {
|
||||
// v1.99.00 changed routes generation algorithm and data format
|
||||
routes.attr("display", null).attr("style", null);
|
||||
|
||||
delete cells.road;
|
||||
delete cells.crossroad;
|
||||
|
||||
pack.routes = [];
|
||||
const POINT_DISTANCE = grid.spacing * 0.75;
|
||||
|
||||
for (const g of document.querySelectorAll("#viewbox > #routes > g")) {
|
||||
const group = g.id;
|
||||
if (!group) continue;
|
||||
|
||||
for (const node of g.querySelectorAll("path")) {
|
||||
const totalLength = node.getTotalLength();
|
||||
if (!totalLength) {
|
||||
ERROR && console.error("Route path has zero length", node);
|
||||
continue;
|
||||
}
|
||||
|
||||
const increment = totalLength / Math.ceil(totalLength / POINT_DISTANCE);
|
||||
const points = [];
|
||||
|
||||
for (let i = 0; i <= totalLength + 0.1; i += increment) {
|
||||
const point = node.getPointAtLength(i);
|
||||
const x = rn(point.x, 2);
|
||||
const y = rn(point.y, 2);
|
||||
const cellId = findCell(x, y);
|
||||
points.push([x, y, cellId]);
|
||||
}
|
||||
|
||||
if (points.length < 2) {
|
||||
ERROR && console.error("Route path has less than 2 points", node);
|
||||
continue;
|
||||
}
|
||||
|
||||
const secondCellId = points[1][2];
|
||||
const feature = pack.cells.f[secondCellId];
|
||||
|
||||
pack.routes.push({i: pack.routes.length, group, feature, points});
|
||||
}
|
||||
}
|
||||
routes.selectAll("path").remove();
|
||||
if (layerIsOn("toggleRoutes")) drawRoutes();
|
||||
|
||||
const links = (pack.cells.routes = {});
|
||||
for (const route of pack.routes) {
|
||||
for (let i = 0; i < route.points.length - 1; i++) {
|
||||
const cellId = route.points[i][2];
|
||||
const nextCellId = route.points[i + 1][2];
|
||||
|
||||
if (cellId !== nextCellId) {
|
||||
if (!links[cellId]) links[cellId] = {};
|
||||
links[cellId][nextCellId] = route.i;
|
||||
|
||||
if (!links[nextCellId]) links[nextCellId] = {};
|
||||
links[nextCellId][cellId] = route.i;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -822,6 +822,7 @@ function addCulture() {
|
|||
|
||||
if (pack.cells.h[center] < 20)
|
||||
return tip("You cannot place culture center into the water. Please click on a land cell", false, "error");
|
||||
|
||||
const occupied = pack.cultures.some(c => !c.removed && c.center === center);
|
||||
if (occupied) return tip("This cell is already a culture center. Please select a different cell", false, "error");
|
||||
|
||||
|
|
@ -857,8 +858,19 @@ function closeCulturesEditor() {
|
|||
}
|
||||
|
||||
async function uploadCulturesData() {
|
||||
const csv = await Formats.csvParser(this.files[0]);
|
||||
const file = this.files[0];
|
||||
this.value = "";
|
||||
const csv = await file.text();
|
||||
const data = d3.csvParse(csv, d => ({
|
||||
i: +d.Id,
|
||||
name: d.Name,
|
||||
color: d.Color,
|
||||
expansionism: +d.Expansionism,
|
||||
type: d.Type,
|
||||
population: +d.Population,
|
||||
emblemsShape: d["Emblems Shape"],
|
||||
origins: d.Origins
|
||||
}));
|
||||
|
||||
const {cultures, cells} = pack;
|
||||
const shapes = Object.keys(COA.shields.types)
|
||||
|
|
@ -870,20 +882,26 @@ async function uploadCulturesData() {
|
|||
if (item.i) item.removed = true;
|
||||
});
|
||||
|
||||
for (const c of csv.iterator((a, b) => +a[0] > +b[0])) {
|
||||
for (const culture of data) {
|
||||
let current;
|
||||
if (+c.id < cultures.length) {
|
||||
current = cultures[c.id];
|
||||
if (culture.i < cultures.length) {
|
||||
current = cultures[culture.i];
|
||||
|
||||
const ratio = current.urban / (current.rural + current.urban);
|
||||
applyPopulationChange(current.rural, current.urban, c.population * (1 - ratio), c.population * ratio, +c.id);
|
||||
applyPopulationChange(
|
||||
current.rural,
|
||||
current.urban,
|
||||
culture.population * (1 - ratio),
|
||||
culture.population * ratio,
|
||||
culture.i
|
||||
);
|
||||
} else {
|
||||
current = {i: cultures.length, center: ra(populated), area: 0, cells: 0, origin: 0, rural: 0, urban: 0};
|
||||
cultures.push(current);
|
||||
}
|
||||
|
||||
current.removed = false;
|
||||
current.name = c.name;
|
||||
current.name = culture.name;
|
||||
|
||||
if (current.i) {
|
||||
current.code = abbreviate(
|
||||
|
|
@ -891,10 +909,10 @@ async function uploadCulturesData() {
|
|||
cultures.map(c => c.code)
|
||||
);
|
||||
|
||||
current.color = c.color;
|
||||
current.expansionism = +c.expansionism;
|
||||
current.color = culture.color;
|
||||
current.expansionism = +culture.expansionism;
|
||||
|
||||
if (cultureTypes.includes(c.type)) current.type = c.type;
|
||||
if (cultureTypes.includes(culture.type)) current.type = culture.type;
|
||||
else current.type = "Generic";
|
||||
}
|
||||
|
||||
|
|
@ -913,13 +931,11 @@ async function uploadCulturesData() {
|
|||
current.origins = originIds.filter(id => id !== null);
|
||||
if (!current.origins.length) current.origins = [0];
|
||||
}
|
||||
c.origins = current.i ? restoreOrigins(c.origins) : [null];
|
||||
|
||||
const shieldShape = c["emblems shape"].toLowerCase();
|
||||
if (shapes.includes(shieldShape)) current.shield = shieldShape;
|
||||
else current.shield = "heater";
|
||||
culture.origins = current.i ? restoreOrigins(culture.origins || "") : [null];
|
||||
current.shield = shapes.includes(culture.emblemsShape) ? culture.emblemsShape : "heater";
|
||||
|
||||
const nameBaseIndex = nameBases.findIndex(n => n.name == c.namesbase);
|
||||
const nameBaseIndex = nameBases.findIndex(n => n.name == culture.namesbase);
|
||||
current.base = nameBaseIndex === -1 ? 0 : nameBaseIndex;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -434,13 +434,13 @@ function editStateName(state) {
|
|||
modules.editStateName = true;
|
||||
|
||||
// add listeners
|
||||
byId("stateNameEditorShortCulture").on("click", regenerateShortNameCuture);
|
||||
byId("stateNameEditorShortCulture").on("click", regenerateShortNameCulture);
|
||||
byId("stateNameEditorShortRandom").on("click", regenerateShortNameRandom);
|
||||
byId("stateNameEditorAddForm").on("click", addCustomForm);
|
||||
byId("stateNameEditorCustomForm").on("change", addCustomForm);
|
||||
byId("stateNameEditorFullRegenerate").on("click", regenerateFullName);
|
||||
|
||||
function regenerateShortNameCuture() {
|
||||
function regenerateShortNameCulture() {
|
||||
const state = +stateNameEditor.dataset.state;
|
||||
const culture = pack.states[state].culture;
|
||||
const name = Names.getState(Names.getCultureShort(culture), culture);
|
||||
|
|
@ -624,28 +624,36 @@ function stateRemovePrompt(state) {
|
|||
});
|
||||
}
|
||||
|
||||
function stateRemove(state) {
|
||||
statesBody.select("#state" + state).remove();
|
||||
statesBody.select("#state-gap" + state).remove();
|
||||
statesHalo.select("#state-border" + state).remove();
|
||||
labels.select("#stateLabel" + state).remove();
|
||||
defs.select("#textPath_stateLabel" + state).remove();
|
||||
function stateRemove(stateId) {
|
||||
statesBody.select("#state" + stateId).remove();
|
||||
statesBody.select("#state-gap" + stateId).remove();
|
||||
statesHalo.select("#state-border" + stateId).remove();
|
||||
labels.select("#stateLabel" + stateId).remove();
|
||||
defs.select("#textPath_stateLabel" + stateId).remove();
|
||||
|
||||
unfog("focusState" + state);
|
||||
pack.burgs.forEach(b => {
|
||||
if (b.state === state) b.state = 0;
|
||||
unfog("focusState" + stateId);
|
||||
|
||||
pack.burgs.forEach(burg => {
|
||||
if (burg.state === stateId) {
|
||||
burg.state = 0;
|
||||
if (burg.capital) {
|
||||
burg.capital = 0;
|
||||
moveBurgToGroup(burg.i, "towns");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
pack.cells.state.forEach((s, i) => {
|
||||
if (s === state) pack.cells.state[i] = 0;
|
||||
if (s === stateId) pack.cells.state[i] = 0;
|
||||
});
|
||||
|
||||
// remove emblem
|
||||
const coaId = "stateCOA" + state;
|
||||
const coaId = "stateCOA" + stateId;
|
||||
byId(coaId).remove();
|
||||
emblems.select(`#stateEmblems > use[data-i='${state}']`).remove();
|
||||
emblems.select(`#stateEmblems > use[data-i='${stateId}']`).remove();
|
||||
|
||||
// remove provinces
|
||||
pack.states[state].provinces.forEach(p => {
|
||||
pack.states[stateId].provinces.forEach(p => {
|
||||
pack.provinces[p] = {i: p, removed: true};
|
||||
pack.cells.province.forEach((pr, i) => {
|
||||
if (pr === p) pack.cells.province[i] = 0;
|
||||
|
|
@ -660,19 +668,14 @@ function stateRemove(state) {
|
|||
});
|
||||
|
||||
// remove military
|
||||
pack.states[state].military.forEach(m => {
|
||||
const id = `regiment${state}-${m.i}`;
|
||||
pack.states[stateId].military.forEach(m => {
|
||||
const id = `regiment${stateId}-${m.i}`;
|
||||
const index = notes.findIndex(n => n.id === id);
|
||||
if (index != -1) notes.splice(index, 1);
|
||||
});
|
||||
armies.select("g#army" + state).remove();
|
||||
armies.select("g#army" + stateId).remove();
|
||||
|
||||
const capital = pack.states[state].capital;
|
||||
pack.burgs[capital].capital = 0;
|
||||
pack.burgs[capital].state = 0;
|
||||
moveBurgToGroup(capital, "towns");
|
||||
|
||||
pack.states[state] = {i: state, removed: true};
|
||||
pack.states[stateId] = {i: stateId, removed: true};
|
||||
|
||||
debug.selectAll(".highlight").remove();
|
||||
if (!layerIsOn("toggleStates")) toggleStates();
|
||||
|
|
@ -963,7 +966,7 @@ function dragStateBrush() {
|
|||
const p = d3.mouse(this);
|
||||
moveCircle(p[0], p[1], r);
|
||||
|
||||
const found = r > 5 ? findAll(p[0], p[1], r) : [findCell(p[0], p[1], r)];
|
||||
const found = r > 5 ? findAll(p[0], p[1], r) : [findCell(p[0], p[1])];
|
||||
const selection = found.filter(isLand);
|
||||
if (selection) changeStateForSelection(selection);
|
||||
});
|
||||
|
|
@ -1394,6 +1397,7 @@ function openStateMergeDialog() {
|
|||
|
||||
function mergeStates(statesToMerge, rulingStateId) {
|
||||
const rulingState = pack.states[rulingStateId];
|
||||
const rulingStateArmy = byId("army" + rulingStateId);
|
||||
|
||||
// remove states to be merged
|
||||
statesToMerge.forEach(stateId => {
|
||||
|
|
@ -1410,27 +1414,25 @@ function openStateMergeDialog() {
|
|||
emblems.select(`#stateEmblems > use[data-i='${stateId}']`).remove();
|
||||
|
||||
// add merged state regiments to the ruling state
|
||||
state.military.forEach(m => {
|
||||
const oldId = `regiment${stateId}-${m.i}`;
|
||||
|
||||
const newRegiment = {...m, i: rulingState.military.length};
|
||||
rulingState.military.push(newRegiment);
|
||||
|
||||
const newId = `regiment${rulingStateId}-${newRegiment.i}`;
|
||||
state.military.forEach(regiment => {
|
||||
const oldId = `regiment${stateId}-${regiment.i}`;
|
||||
const newIndex = rulingState.military.length;
|
||||
rulingState.military.push({...regiment, i: newIndex});
|
||||
const newId = `regiment${rulingStateId}-${newIndex}`;
|
||||
|
||||
const note = notes.find(n => n.id === oldId);
|
||||
if (note) note.id = newId;
|
||||
|
||||
const rulingStateArmy = armies.select("g#army" + rulingStateId);
|
||||
armies
|
||||
.select("g#army" + stateId)
|
||||
.selectAll("g")
|
||||
.each(function () {
|
||||
this.setAttribute("id", newId);
|
||||
rulingStateArmy.node().appendChild(this);
|
||||
});
|
||||
armies.select("g#army" + stateId).remove();
|
||||
const element = byId(oldId);
|
||||
if (element) {
|
||||
element.id = newId;
|
||||
element.dataset.state = rulingStateId;
|
||||
element.dataset.id = newIndex;
|
||||
rulingStateArmy.appendChild(element);
|
||||
}
|
||||
});
|
||||
|
||||
armies.select("g#army" + stateId).remove();
|
||||
});
|
||||
|
||||
// reassing burgs
|
||||
|
|
|
|||
|
|
@ -52,7 +52,8 @@ function getMinimalDataJson() {
|
|||
provinces: pack.provinces,
|
||||
religions: pack.religions,
|
||||
rivers: pack.rivers,
|
||||
markers: pack.markers
|
||||
markers: pack.markers,
|
||||
routes: pack.routes
|
||||
};
|
||||
return JSON.stringify({info, settings, mapCoordinates, pack: packData, biomesData, notes, nameBases});
|
||||
}
|
||||
|
|
@ -75,6 +76,8 @@ function getMapInfo() {
|
|||
description: "Azgaar's Fantasy Map Generator output: azgaar.github.io/Fantasy-map-generator",
|
||||
exportedAt: new Date().toISOString(),
|
||||
mapName: mapName.value,
|
||||
width: graphWidth,
|
||||
height: graphHeight,
|
||||
seed,
|
||||
mapId
|
||||
};
|
||||
|
|
@ -83,21 +86,16 @@ function getMapInfo() {
|
|||
function getSettings() {
|
||||
return {
|
||||
distanceUnit: distanceUnitInput.value,
|
||||
distanceScale: distanceScaleInput.value,
|
||||
distanceScale,
|
||||
areaUnit: areaUnit.value,
|
||||
heightUnit: heightUnit.value,
|
||||
heightExponent: heightExponentInput.value,
|
||||
temperatureScale: temperatureScale.value,
|
||||
barSize: barSizeInput.value,
|
||||
barLabel: barLabel.value,
|
||||
barBackOpacity: barBackOpacity.value,
|
||||
barBackColor: barBackColor.value,
|
||||
barPosX: barPosX.value,
|
||||
barPosY: barPosY.value,
|
||||
populationRate: populationRate,
|
||||
urbanization: urbanization,
|
||||
mapSize: mapSizeOutput.value,
|
||||
latitudeO: latitudeOutput.value,
|
||||
latitude: latitudeOutput.value,
|
||||
longitude: longitudeOutput.value,
|
||||
prec: precOutput.value,
|
||||
options: options,
|
||||
mapName: mapName.value,
|
||||
|
|
@ -109,7 +107,7 @@ function getSettings() {
|
|||
}
|
||||
|
||||
function getPackCellsData() {
|
||||
const dataArrays = {
|
||||
const data = {
|
||||
v: pack.cells.v,
|
||||
c: pack.cells.c,
|
||||
p: pack.cells.p,
|
||||
|
|
@ -128,8 +126,7 @@ function getPackCellsData() {
|
|||
pop: Array.from(pack.cells.pop),
|
||||
culture: Array.from(pack.cells.culture),
|
||||
burg: Array.from(pack.cells.burg),
|
||||
road: Array.from(pack.cells.road),
|
||||
crossroad: Array.from(pack.cells.crossroad),
|
||||
routes: pack.cells.routes,
|
||||
state: Array.from(pack.cells.state),
|
||||
religion: Array.from(pack.cells.religion),
|
||||
province: Array.from(pack.cells.province)
|
||||
|
|
@ -138,29 +135,28 @@ function getPackCellsData() {
|
|||
return {
|
||||
cells: Array.from(pack.cells.i).map(cellId => ({
|
||||
i: cellId,
|
||||
v: dataArrays.v[cellId],
|
||||
c: dataArrays.c[cellId],
|
||||
p: dataArrays.p[cellId],
|
||||
g: dataArrays.g[cellId],
|
||||
h: dataArrays.h[cellId],
|
||||
area: dataArrays.area[cellId],
|
||||
f: dataArrays.f[cellId],
|
||||
t: dataArrays.t[cellId],
|
||||
haven: dataArrays.haven[cellId],
|
||||
harbor: dataArrays.harbor[cellId],
|
||||
fl: dataArrays.fl[cellId],
|
||||
r: dataArrays.r[cellId],
|
||||
conf: dataArrays.conf[cellId],
|
||||
biome: dataArrays.biome[cellId],
|
||||
s: dataArrays.s[cellId],
|
||||
pop: dataArrays.pop[cellId],
|
||||
culture: dataArrays.culture[cellId],
|
||||
burg: dataArrays.burg[cellId],
|
||||
road: dataArrays.road[cellId],
|
||||
crossroad: dataArrays.crossroad[cellId],
|
||||
state: dataArrays.state[cellId],
|
||||
religion: dataArrays.religion[cellId],
|
||||
province: dataArrays.province[cellId]
|
||||
v: data.v[cellId],
|
||||
c: data.c[cellId],
|
||||
p: data.p[cellId],
|
||||
g: data.g[cellId],
|
||||
h: data.h[cellId],
|
||||
area: data.area[cellId],
|
||||
f: data.f[cellId],
|
||||
t: data.t[cellId],
|
||||
haven: data.haven[cellId],
|
||||
harbor: data.harbor[cellId],
|
||||
fl: data.fl[cellId],
|
||||
r: data.r[cellId],
|
||||
conf: data.conf[cellId],
|
||||
biome: data.biome[cellId],
|
||||
s: data.s[cellId],
|
||||
pop: data.pop[cellId],
|
||||
culture: data.culture[cellId],
|
||||
burg: data.burg[cellId],
|
||||
routes: data.routes[cellId],
|
||||
state: data.state[cellId],
|
||||
religion: data.religion[cellId],
|
||||
province: data.province[cellId]
|
||||
})),
|
||||
vertices: Array.from(pack.vertices.p).map((_, vertexId) => ({
|
||||
i: vertexId,
|
||||
|
|
@ -175,7 +171,8 @@ function getPackCellsData() {
|
|||
provinces: pack.provinces,
|
||||
religions: pack.religions,
|
||||
rivers: pack.rivers,
|
||||
markers: pack.markers
|
||||
markers: pack.markers,
|
||||
routes: pack.routes
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -314,6 +314,6 @@ function confirmHeightmapEdit() {
|
|||
function getHeightmapPreview(heights) {
|
||||
const scheme = getColorScheme(byId("heightmapSelectionColorScheme").value);
|
||||
const renderOcean = byId("heightmapSelectionRenderOcean").checked;
|
||||
const dataUrl = drawHeights({heights, width: grid.cellsX, height: grid.cellsY, scheme, renderOcean});
|
||||
const dataUrl = drawHeights({heights, width: graph.cellsX, height: graph.cellsY, scheme, renderOcean});
|
||||
return dataUrl;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,3 @@
|
|||
import {rollups} from "../../../utils/functionUtils.js";
|
||||
|
||||
const entitiesMap = {
|
||||
states: {
|
||||
label: "State",
|
||||
|
|
|
|||
|
|
@ -546,4 +546,38 @@ Noah Morris
|
|||
Phil Karecki
|
||||
Matthew Jarocki
|
||||
Lucius Licinius Lucullus
|
||||
Andrew Haney`;
|
||||
Andrew Haney
|
||||
Noah Morris
|
||||
Phil Karecki
|
||||
Matthew Jarocki
|
||||
Lucius Licinius Lucullus
|
||||
Andrew Haney
|
||||
Jesse Luke
|
||||
Lord_Luce
|
||||
Neko no Maigo
|
||||
Hossyboy
|
||||
Yasui Masatake
|
||||
Jesse Roy
|
||||
Remain
|
||||
Douglas Rector
|
||||
J Clark
|
||||
Raine Logan
|
||||
Matty Ice
|
||||
DieMuetze
|
||||
Dan Popoli
|
||||
Marwyn
|
||||
Kederalia
|
||||
Whyse Wytch
|
||||
Elliyevee
|
||||
James Miller
|
||||
Pirate Fish
|
||||
David Leitner
|
||||
Vyritecht
|
||||
emre
|
||||
Don't mail me
|
||||
Isaac Wooten
|
||||
MisterPete
|
||||
Johanna Martin
|
||||
Marmalade_MacGuffin
|
||||
James Benware
|
||||
FortunesFaded`;
|
||||
|
|
|
|||
|
|
@ -69,6 +69,12 @@ const fonts = [
|
|||
unicodeRange:
|
||||
"U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215"
|
||||
},
|
||||
{
|
||||
family: "Eagle Lake",
|
||||
src: "url(https://fonts.gstatic.com/s/eaglelake/v24/ptRMTiqbbuNJDOiKj9wG1On4KCFtpe4.woff2)",
|
||||
unicodeRange:
|
||||
"U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215"
|
||||
},
|
||||
{
|
||||
family: "Faster One",
|
||||
src: "url(https://fonts.gstatic.com/s/fasterone/v17/H4ciBXCHmdfClFb-vWhf-LyYhw.woff2)",
|
||||
|
|
@ -129,6 +135,12 @@ const fonts = [
|
|||
unicodeRange:
|
||||
"U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD"
|
||||
},
|
||||
{
|
||||
family: "Lugrasimo",
|
||||
src: "url(https://fonts.gstatic.com/s/lugrasimo/v4/qkBXXvoF_s_eT9c7Y7au455KsgbLMA.woff2)",
|
||||
unicodeRange:
|
||||
"U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215"
|
||||
},
|
||||
{
|
||||
family: "Kaushan Script",
|
||||
src: "url(https://fonts.gstatic.com/s/kaushanscript/v6/qx1LSqts-NtiKcLw4N03IEd0sm1ffa_JvZxsF_BEwQk.woff2)",
|
||||
|
|
|
|||
|
|
@ -60,7 +60,7 @@ window.Cloud = (function () {
|
|||
|
||||
async save(fileName, contents) {
|
||||
const resp = await this.call("filesUpload", {path: "/" + fileName, contents});
|
||||
DEBUG && console.log("Dropbox response:", resp);
|
||||
DEBUG && console.info("Dropbox response:", resp);
|
||||
return true;
|
||||
},
|
||||
|
||||
|
|
@ -104,7 +104,7 @@ window.Cloud = (function () {
|
|||
|
||||
// Callback function for auth window
|
||||
async setDropBoxToken(token) {
|
||||
DEBUG && console.log("Access token:", token);
|
||||
DEBUG && console.info("Access token:", token);
|
||||
setToken(this.name, token);
|
||||
await this.connect(token);
|
||||
this.authWindow.close();
|
||||
|
|
@ -131,7 +131,7 @@ window.Cloud = (function () {
|
|||
allow_download: true
|
||||
};
|
||||
const resp = await this.call("sharingCreateSharedLinkWithSettings", {path, settings});
|
||||
DEBUG && console.log("Dropbox link object:", resp.result);
|
||||
DEBUG && console.info("Dropbox link object:", resp.result);
|
||||
return resp.result.url;
|
||||
}
|
||||
};
|
||||
|
|
|
|||
|
|
@ -71,70 +71,100 @@ async function exportToJpeg() {
|
|||
}
|
||||
|
||||
async function exportToPngTiles() {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
// download schema
|
||||
const urlSchema = await getMapURL("tiles", {debug: true, fullMap: true});
|
||||
await import("../../libs/jszip.min.js");
|
||||
const zip = new window.JSZip();
|
||||
const status = byId("tileStatus");
|
||||
status.innerHTML = "Preparing files...";
|
||||
|
||||
const canvas = document.createElement("canvas");
|
||||
const ctx = canvas.getContext("2d");
|
||||
canvas.width = graphWidth;
|
||||
canvas.height = graphHeight;
|
||||
const urlSchema = await getMapURL("tiles", {debug: true, fullMap: true});
|
||||
await import("../../libs/jszip.min.js");
|
||||
const zip = new window.JSZip();
|
||||
|
||||
const imgSchema = new Image();
|
||||
imgSchema.src = urlSchema;
|
||||
imgSchema.onload = function () {
|
||||
ctx.drawImage(imgSchema, 0, 0, canvas.width, canvas.height);
|
||||
canvas.toBlob(blob => zip.file(`fmg_tile_schema.png`, blob));
|
||||
};
|
||||
const canvas = document.createElement("canvas");
|
||||
const ctx = canvas.getContext("2d");
|
||||
canvas.width = graphWidth;
|
||||
canvas.height = graphHeight;
|
||||
|
||||
// download tiles
|
||||
const url = await getMapURL("tiles", {fullMap: true});
|
||||
const tilesX = +document.getElementById("tileColsInput").value;
|
||||
const tilesY = +document.getElementById("tileRowsInput").value;
|
||||
const scale = +document.getElementById("tileScaleInput").value;
|
||||
const imgSchema = new Image();
|
||||
imgSchema.src = urlSchema;
|
||||
await loadImage(imgSchema);
|
||||
|
||||
const tileW = (graphWidth / tilesX) | 0;
|
||||
const tileH = (graphHeight / tilesY) | 0;
|
||||
const tolesTotal = tilesX * tilesY;
|
||||
status.innerHTML = "Rendering schema...";
|
||||
ctx.drawImage(imgSchema, 0, 0, canvas.width, canvas.height);
|
||||
const blob = await canvasToBlob(canvas, "image/png");
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
zip.file("schema.png", blob);
|
||||
|
||||
const width = graphWidth * scale;
|
||||
const height = width * (tileH / tileW);
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
// download tiles
|
||||
const url = await getMapURL("tiles", {fullMap: true});
|
||||
const tilesX = +byId("tileColsOutput").value || 2;
|
||||
const tilesY = +byId("tileRowsOutput").value || 2;
|
||||
const scale = +byId("tileScaleOutput").value || 1;
|
||||
const tolesTotal = tilesX * tilesY;
|
||||
|
||||
let loaded = 0;
|
||||
const img = new Image();
|
||||
img.src = url;
|
||||
img.onload = function () {
|
||||
for (let y = 0, i = 0; y + tileH <= graphHeight; y += tileH) {
|
||||
for (let x = 0; x + tileW <= graphWidth; x += tileW, i++) {
|
||||
ctx.drawImage(img, x, y, tileW, tileH, 0, 0, width, height);
|
||||
const name = `fmg_tile_${i}.png`;
|
||||
canvas.toBlob(blob => {
|
||||
zip.file(name, blob);
|
||||
loaded += 1;
|
||||
if (loaded === tolesTotal) return downloadZip();
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
const tileW = (graphWidth / tilesX) | 0;
|
||||
const tileH = (graphHeight / tilesY) | 0;
|
||||
|
||||
function downloadZip() {
|
||||
const name = `${getFileName()}.zip`;
|
||||
zip.generateAsync({type: "blob"}).then(blob => {
|
||||
const link = document.createElement("a");
|
||||
link.href = URL.createObjectURL(blob);
|
||||
link.download = name;
|
||||
link.click();
|
||||
link.remove();
|
||||
const width = graphWidth * scale;
|
||||
const height = width * (tileH / tileW);
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
|
||||
setTimeout(() => URL.revokeObjectURL(link.href), 5000);
|
||||
resolve(true);
|
||||
});
|
||||
const img = new Image();
|
||||
img.src = url;
|
||||
await loadImage(img);
|
||||
|
||||
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
function getRowLabel(row) {
|
||||
const first = row >= alphabet.length ? alphabet[Math.floor(row / alphabet.length) - 1] : "";
|
||||
const last = alphabet[row % alphabet.length];
|
||||
return first + last;
|
||||
}
|
||||
|
||||
for (let y = 0, row = 0, id = 1; y + tileH <= graphHeight; y += tileH, row++) {
|
||||
const rowName = getRowLabel(row);
|
||||
|
||||
for (let x = 0, cell = 1; x + tileW <= graphWidth; x += tileW, cell++, id++) {
|
||||
status.innerHTML = `Rendering tile ${rowName}${cell} (${id} of ${tolesTotal})...`;
|
||||
ctx.drawImage(img, x, y, tileW, tileH, 0, 0, width, height);
|
||||
const blob = await canvasToBlob(canvas, "image/png");
|
||||
ctx.clearRect(0, 0, canvas.width, canvas.height);
|
||||
zip.file(`${rowName}${cell}.png`, blob);
|
||||
}
|
||||
}
|
||||
|
||||
status.innerHTML = "Zipping files...";
|
||||
zip.generateAsync({type: "blob"}).then(blob => {
|
||||
status.innerHTML = "Downloading the archive...";
|
||||
const link = document.createElement("a");
|
||||
link.href = URL.createObjectURL(blob);
|
||||
link.download = getFileName() + ".zip";
|
||||
link.click();
|
||||
link.remove();
|
||||
|
||||
status.innerHTML = 'Done. Check .zip file in "Downloads" (crtl + J)';
|
||||
setTimeout(() => URL.revokeObjectURL(link.href), 5000);
|
||||
});
|
||||
|
||||
// promisified img.onload
|
||||
function loadImage(img) {
|
||||
return new Promise((resolve, reject) => {
|
||||
img.onload = () => resolve();
|
||||
img.onerror = err => reject(err);
|
||||
});
|
||||
}
|
||||
|
||||
// promisified canvas.toBlob
|
||||
function canvasToBlob(canvas, mimeType, qualityArgument = 1) {
|
||||
return new Promise((resolve, reject) => {
|
||||
canvas.toBlob(
|
||||
blob => {
|
||||
if (blob) resolve(blob);
|
||||
else reject(new Error("Canvas toBlob() error"));
|
||||
},
|
||||
mimeType,
|
||||
qualityArgument
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// parse map svg to object url
|
||||
|
|
@ -148,14 +178,14 @@ async function getMapURL(type, options) {
|
|||
fullMap = false
|
||||
} = options || {};
|
||||
|
||||
const cloneEl = document.getElementById("map").cloneNode(true); // clone svg
|
||||
const cloneEl = byId("map").cloneNode(true); // clone svg
|
||||
cloneEl.id = "fantasyMap";
|
||||
document.body.appendChild(cloneEl);
|
||||
const clone = d3.select(cloneEl);
|
||||
if (!debug) clone.select("#debug")?.remove();
|
||||
|
||||
const cloneDefs = cloneEl.getElementsByTagName("defs")[0];
|
||||
const svgDefs = document.getElementById("defElements");
|
||||
const svgDefs = byId("defElements");
|
||||
|
||||
const isFirefox = navigator.userAgent.toLowerCase().indexOf("firefox") > -1;
|
||||
if (isFirefox && type === "mesh") clone.select("#oceanPattern")?.remove();
|
||||
|
|
@ -218,7 +248,7 @@ async function getMapURL(type, options) {
|
|||
.forEach(el => {
|
||||
const href = el.getAttribute("href") || el.getAttribute("xlink:href");
|
||||
if (!href) return;
|
||||
const emblem = document.getElementById(href.slice(1));
|
||||
const emblem = byId(href.slice(1));
|
||||
if (emblem) cloneDefs.append(emblem.cloneNode(true));
|
||||
});
|
||||
} else {
|
||||
|
|
@ -271,7 +301,7 @@ async function getMapURL(type, options) {
|
|||
|
||||
// add wind rose
|
||||
if (cloneEl.getElementById("compass")) {
|
||||
const rose = svgDefs.getElementById("rose");
|
||||
const rose = svgDefs.getElementById("defs-compass-rose");
|
||||
if (rose) cloneDefs.appendChild(rose.cloneNode(true));
|
||||
}
|
||||
|
||||
|
|
@ -364,7 +394,7 @@ function removeUnusedElements(clone) {
|
|||
|
||||
function updateMeshCells(clone) {
|
||||
const data = renderOcean.checked ? grid.cells.i : grid.cells.i.filter(i => grid.cells.h[i] >= 20);
|
||||
const scheme = getColorScheme(terrs.attr("scheme"));
|
||||
const scheme = getColorScheme(terrs.select("#landHeights").attr("scheme"));
|
||||
clone.select("#heights").attr("filter", "url(#blur1)");
|
||||
clone
|
||||
.select("#heights")
|
||||
|
|
@ -441,17 +471,23 @@ function saveGeoJSON_Cells() {
|
|||
}
|
||||
|
||||
function saveGeoJSON_Routes() {
|
||||
const json = {type: "FeatureCollection", features: []};
|
||||
|
||||
routes.selectAll("g > path").each(function () {
|
||||
const coordinates = getRoutePoints(this);
|
||||
const id = this.id;
|
||||
const type = this.parentElement.id;
|
||||
|
||||
const feature = {type: "Feature", geometry: {type: "LineString", coordinates}, properties: {id, type}};
|
||||
json.features.push(feature);
|
||||
const {cells, burgs} = pack;
|
||||
let points = cells.p.map(([x, y], cellId) => {
|
||||
const burgId = cells.burg[cellId];
|
||||
if (burgId) return [burgs[burgId].x, burgs[burgId].y];
|
||||
return [x, y];
|
||||
});
|
||||
|
||||
const features = pack.routes.map(route => {
|
||||
const coordinates = route.points || getRoutePoints(route, points);
|
||||
return {
|
||||
type: "Feature",
|
||||
geometry: {type: "LineString", coordinates},
|
||||
properties: {id: route.id, group: route.group}
|
||||
};
|
||||
});
|
||||
const json = {type: "FeatureCollection", features};
|
||||
|
||||
const fileName = getFileName("Routes") + ".geojson";
|
||||
downloadFile(JSON.stringify(json), fileName, "application/json");
|
||||
}
|
||||
|
|
@ -495,17 +531,6 @@ function getCellCoordinates(vertices) {
|
|||
return [coordinates.concat([coordinates[0]])];
|
||||
}
|
||||
|
||||
function getRoutePoints(node) {
|
||||
let points = [];
|
||||
const l = node.getTotalLength();
|
||||
const increment = l / Math.ceil(l / 2);
|
||||
for (let i = 0; i <= l; i += increment) {
|
||||
const p = node.getPointAtLength(i);
|
||||
points.push(getCoordinates(p.x, p.y, 4));
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
function getRiverPoints(node) {
|
||||
let points = [];
|
||||
const l = node.getTotalLength() / 2; // half-length
|
||||
|
|
|
|||
|
|
@ -1,24 +0,0 @@
|
|||
"use strict";
|
||||
|
||||
window.Formats = (function () {
|
||||
async function csvParser(file, separator = ",") {
|
||||
const txt = await file.text();
|
||||
const rows = txt.split("\n");
|
||||
const headers = rows
|
||||
.shift()
|
||||
.split(separator)
|
||||
.map(x => x.toLowerCase());
|
||||
const data = rows.filter(a => a.trim() !== "").map(r => r.split(separator));
|
||||
|
||||
return {
|
||||
headers,
|
||||
data,
|
||||
iterator: function* (sortf) {
|
||||
const dataset = sortf ? this.data.sort(sortf) : this.data;
|
||||
for (const d of dataset) yield Object.fromEntries(d.map((a, i) => [this.headers[i], a]));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
return {csvParser};
|
||||
})();
|
||||
|
|
@ -12,7 +12,7 @@ async function quickLoad() {
|
|||
async function loadFromDropbox() {
|
||||
const mapPath = byId("loadFromDropboxSelect")?.value;
|
||||
|
||||
DEBUG && console.log("Loading map from Dropbox:", mapPath);
|
||||
DEBUG && console.info("Loading map from Dropbox:", mapPath);
|
||||
const blob = await Cloud.providers.dropbox.load(mapPath);
|
||||
uploadMap(blob);
|
||||
}
|
||||
|
|
@ -183,22 +183,22 @@ function showUploadMessage(type, mapData, mapVersion) {
|
|||
title = "Newer file";
|
||||
canBeLoaded = false;
|
||||
} else if (type === "outdated") {
|
||||
message = `The map version (${mapVersion}) does not match the Generator version (${version}).<br>That is fine, click OK to the get map <b style="color: #005000">auto-updated</b>.<br>In case of issues please keep using an ${archive} of the Generator`;
|
||||
title = "Outdated file";
|
||||
canBeLoaded = true;
|
||||
INFO && console.info(`Loading map. Auto-update from ${mapVersion} to ${version}`);
|
||||
parseLoadedData(mapData, mapVersion);
|
||||
return;
|
||||
}
|
||||
|
||||
alertMessage.innerHTML = message;
|
||||
const buttons = {
|
||||
OK: function () {
|
||||
$(this).dialog("close");
|
||||
if (canBeLoaded) parseLoadedData(mapData);
|
||||
if (canBeLoaded) parseLoadedData(mapData, mapVersion);
|
||||
}
|
||||
};
|
||||
$("#alert").dialog({title, buttons});
|
||||
}
|
||||
|
||||
async function parseLoadedData(data) {
|
||||
async function parseLoadedData(data, mapVersion) {
|
||||
try {
|
||||
// exit customization
|
||||
if (window.closeDialogs) closeDialogs();
|
||||
|
|
@ -218,6 +218,7 @@ async function parseLoadedData(data) {
|
|||
|
||||
INFO && console.group("Loaded Map " + seed);
|
||||
|
||||
// TODO: move all to options object
|
||||
void (function parseSettings() {
|
||||
const settings = data[1].split("|");
|
||||
if (settings[0]) applyOption(distanceUnitInput, settings[0]);
|
||||
|
|
@ -226,28 +227,22 @@ async function parseLoadedData(data) {
|
|||
if (settings[3]) applyOption(heightUnit, settings[3]);
|
||||
if (settings[4]) heightExponentInput.value = heightExponentOutput.value = settings[4];
|
||||
if (settings[5]) temperatureScale.value = settings[5];
|
||||
if (settings[6]) barSizeInput.value = barSizeOutput.value = settings[6];
|
||||
if (settings[7] !== undefined) barLabel.value = settings[7];
|
||||
if (settings[8] !== undefined) barBackOpacity.value = settings[8];
|
||||
if (settings[9]) barBackColor.value = settings[9];
|
||||
if (settings[10]) barPosX.value = settings[10];
|
||||
if (settings[11]) barPosY.value = settings[11];
|
||||
// setting 6-11 (scaleBar) are part of style now, kept as "" in newer versions for compatibility
|
||||
if (settings[12]) populationRate = populationRateInput.value = populationRateOutput.value = settings[12];
|
||||
if (settings[13]) urbanization = urbanizationInput.value = urbanizationOutput.value = settings[13];
|
||||
if (settings[14]) mapSizeInput.value = mapSizeOutput.value = minmax(settings[14], 1, 100);
|
||||
if (settings[15]) latitudeInput.value = latitudeOutput.value = minmax(settings[15], 0, 100);
|
||||
if (settings[18]) precInput.value = precOutput.value = settings[18];
|
||||
|
||||
if (settings[19]) options = JSON.parse(settings[19]);
|
||||
// setting 16 and 17 (temperature) are part of options now, kept as "" in newer versions for compatibility
|
||||
if (settings[16]) options.temperatureEquator = +settings[16];
|
||||
if (settings[17]) options.temperatureNorthPole = options.temperatureSouthPole = +settings[17];
|
||||
|
||||
if (settings[20]) mapName.value = settings[20];
|
||||
if (settings[21]) hideLabels.checked = +settings[21];
|
||||
if (settings[22]) stylePreset.value = settings[22];
|
||||
if (settings[23]) rescaleLabels.checked = +settings[23];
|
||||
if (settings[24]) urbanDensity = urbanDensityInput.value = urbanDensityOutput.value = +settings[24];
|
||||
if (settings[25]) longitudeInput.value = longitudeOutput.value = minmax(settings[25] || 50, 0, 100);
|
||||
})();
|
||||
|
||||
void (function applyOptionsToUI() {
|
||||
|
|
@ -353,6 +348,10 @@ async function parseLoadedData(data) {
|
|||
.attr("id", "texture")
|
||||
.attr("data-href", "./images/textures/plaster.jpg");
|
||||
}
|
||||
|
||||
if (!emblems.size()) {
|
||||
emblems = viewbox.insert("g", "#labels").attr("id", "emblems").style("display", "none");
|
||||
}
|
||||
})();
|
||||
|
||||
void (function parseGridData() {
|
||||
|
|
@ -380,6 +379,7 @@ async function parseLoadedData(data) {
|
|||
pack.provinces = data[30] ? JSON.parse(data[30]) : [0];
|
||||
pack.rivers = data[32] ? JSON.parse(data[32]) : [];
|
||||
pack.markers = data[35] ? JSON.parse(data[35]) : [];
|
||||
pack.routes = data[37] ? JSON.parse(data[37]) : [];
|
||||
|
||||
const cells = pack.cells;
|
||||
cells.biome = Uint8Array.from(data[16].split(","));
|
||||
|
|
@ -389,12 +389,13 @@ async function parseLoadedData(data) {
|
|||
cells.fl = Uint16Array.from(data[20].split(","));
|
||||
cells.pop = Float32Array.from(data[21].split(","));
|
||||
cells.r = Uint16Array.from(data[22].split(","));
|
||||
cells.road = Uint16Array.from(data[23].split(","));
|
||||
// data[23] for deprecated cells.road
|
||||
cells.s = Uint16Array.from(data[24].split(","));
|
||||
cells.state = Uint16Array.from(data[25].split(","));
|
||||
cells.religion = data[26] ? Uint16Array.from(data[26].split(",")) : new Uint16Array(cells.i.length);
|
||||
cells.province = data[27] ? Uint16Array.from(data[27].split(",")) : new Uint16Array(cells.i.length);
|
||||
cells.crossroad = data[28] ? Uint16Array.from(data[28].split(",")) : new Uint16Array(cells.i.length);
|
||||
// data[28] for deprecated cells.crossroad
|
||||
cells.routes = data[36] ? JSON.parse(data[36]) : {};
|
||||
|
||||
if (data[31]) {
|
||||
const namesDL = data[31].split("/");
|
||||
|
|
@ -462,16 +463,16 @@ async function parseLoadedData(data) {
|
|||
{
|
||||
// dynamically import and run auto-update script
|
||||
const versionNumber = parseFloat(params[0]);
|
||||
const {resolveVersionConflicts} = await import("../dynamic/auto-update.js?v=1.95.00");
|
||||
const {resolveVersionConflicts} = await import("../dynamic/auto-update.js?v=1.99.01");
|
||||
resolveVersionConflicts(versionNumber);
|
||||
}
|
||||
|
||||
{
|
||||
// add custom heightmap color scheme if any
|
||||
const scheme = terrs.attr("scheme");
|
||||
if (!(scheme in heightmapColorSchemes)) {
|
||||
addCustomColorScheme(scheme);
|
||||
}
|
||||
// add custom heightmap color scheme if any
|
||||
if (heightmapColorSchemes) {
|
||||
const oceanScheme = byId("oceanHeights")?.getAttribute("scheme");
|
||||
if (oceanScheme && !(oceanScheme in heightmapColorSchemes)) addCustomColorScheme(oceanScheme);
|
||||
const landScheme = byId("#landHeights")?.getAttribute("scheme");
|
||||
if (landScheme && !(landScheme in heightmapColorSchemes)) addCustomColorScheme(landScheme);
|
||||
}
|
||||
|
||||
{
|
||||
|
|
@ -484,7 +485,7 @@ async function parseLoadedData(data) {
|
|||
const cells = pack.cells;
|
||||
|
||||
if (pack.cells.i.length !== pack.cells.state.length) {
|
||||
const message = "Data Integrity Check. Striping issue detected. To fix edit the heightmap in erase mode";
|
||||
const message = "Data integrity check. Striping issue detected. To fix edit the heightmap in ERASE mode";
|
||||
ERROR && console.error(message);
|
||||
}
|
||||
|
||||
|
|
@ -492,7 +493,7 @@ async function parseLoadedData(data) {
|
|||
invalidStates.forEach(s => {
|
||||
const invalidCells = cells.i.filter(i => cells.state[i] === s);
|
||||
invalidCells.forEach(i => (cells.state[i] = 0));
|
||||
ERROR && console.error("Data Integrity Check. Invalid state", s, "is assigned to cells", invalidCells);
|
||||
ERROR && console.error("Data integrity check. Invalid state", s, "is assigned to cells", invalidCells);
|
||||
});
|
||||
|
||||
const invalidProvinces = [...new Set(cells.province)].filter(
|
||||
|
|
@ -501,14 +502,14 @@ async function parseLoadedData(data) {
|
|||
invalidProvinces.forEach(p => {
|
||||
const invalidCells = cells.i.filter(i => cells.province[i] === p);
|
||||
invalidCells.forEach(i => (cells.province[i] = 0));
|
||||
ERROR && console.error("Data Integrity Check. Invalid province", p, "is assigned to cells", invalidCells);
|
||||
ERROR && console.error("Data integrity check. Invalid province", p, "is assigned to cells", invalidCells);
|
||||
});
|
||||
|
||||
const invalidCultures = [...new Set(cells.culture)].filter(c => !pack.cultures[c] || pack.cultures[c].removed);
|
||||
invalidCultures.forEach(c => {
|
||||
const invalidCells = cells.i.filter(i => cells.culture[i] === c);
|
||||
invalidCells.forEach(i => (cells.province[i] = 0));
|
||||
ERROR && console.error("Data Integrity Check. Invalid culture", c, "is assigned to cells", invalidCells);
|
||||
ERROR && console.error("Data integrity check. Invalid culture", c, "is assigned to cells", invalidCells);
|
||||
});
|
||||
|
||||
const invalidReligions = [...new Set(cells.religion)].filter(
|
||||
|
|
@ -517,14 +518,14 @@ async function parseLoadedData(data) {
|
|||
invalidReligions.forEach(r => {
|
||||
const invalidCells = cells.i.filter(i => cells.religion[i] === r);
|
||||
invalidCells.forEach(i => (cells.religion[i] = 0));
|
||||
ERROR && console.error("Data Integrity Check. Invalid religion", r, "is assigned to cells", invalidCells);
|
||||
ERROR && console.error("Data integrity check. Invalid religion", r, "is assigned to cells", invalidCells);
|
||||
});
|
||||
|
||||
const invalidFeatures = [...new Set(cells.f)].filter(f => f && !pack.features[f]);
|
||||
invalidFeatures.forEach(f => {
|
||||
const invalidCells = cells.i.filter(i => cells.f[i] === f);
|
||||
// No fix as for now
|
||||
ERROR && console.error("Data Integrity Check. Invalid feature", f, "is assigned to cells", invalidCells);
|
||||
ERROR && console.error("Data integrity check. Invalid feature", f, "is assigned to cells", invalidCells);
|
||||
});
|
||||
|
||||
const invalidBurgs = [...new Set(cells.burg)].filter(
|
||||
|
|
@ -533,7 +534,7 @@ async function parseLoadedData(data) {
|
|||
invalidBurgs.forEach(burgId => {
|
||||
const invalidCells = cells.i.filter(i => cells.burg[i] === burgId);
|
||||
invalidCells.forEach(i => (cells.burg[i] = 0));
|
||||
ERROR && console.error("Data Integrity Check. Invalid burg", burgId, "is assigned to cells", invalidCells);
|
||||
ERROR && console.error("Data integrity check. Invalid burg", burgId, "is assigned to cells", invalidCells);
|
||||
});
|
||||
|
||||
const invalidRivers = [...new Set(cells.r)].filter(r => r && !pack.rivers.find(river => river.i === r));
|
||||
|
|
@ -541,60 +542,112 @@ async function parseLoadedData(data) {
|
|||
const invalidCells = cells.i.filter(i => cells.r[i] === r);
|
||||
invalidCells.forEach(i => (cells.r[i] = 0));
|
||||
rivers.select("river" + r).remove();
|
||||
ERROR && console.error("Data Integrity Check. Invalid river", r, "is assigned to cells", invalidCells);
|
||||
ERROR && console.error("Data integrity check. Invalid river", r, "is assigned to cells", invalidCells);
|
||||
});
|
||||
|
||||
pack.burgs.forEach(burg => {
|
||||
if ((!burg.i || burg.removed) && burg.lock) {
|
||||
if (typeof burg.capital === "boolean") burg.capital = Number(burg.capital);
|
||||
|
||||
if (!burg.i && burg.lock) {
|
||||
ERROR && console.error(`Data integrity check. Burg 0 is marked as locked, removing the status`);
|
||||
delete burg.lock;
|
||||
return;
|
||||
}
|
||||
|
||||
if (burg.removed && burg.lock) {
|
||||
ERROR &&
|
||||
console.error(
|
||||
`Data Integrity Check. Burg ${burg.i || "0"} is removed or invalid but still locked. Unlocking the burg`
|
||||
);
|
||||
console.error(`Data integrity check. Removed burg ${burg.i} is marked as locked. Unlocking the burg`);
|
||||
delete burg.lock;
|
||||
return;
|
||||
}
|
||||
|
||||
if (!burg.i || burg.removed) return;
|
||||
|
||||
if (burg.cell === undefined || burg.x === undefined || burg.y === undefined) {
|
||||
ERROR &&
|
||||
console.error(
|
||||
`Data Integrity Check. Burg ${burg.i} is missing cell info or coordinates. Removing the burg`
|
||||
`Data integrity check. Burg ${burg.i} is missing cell info or coordinates. Removing the burg`
|
||||
);
|
||||
burg.removed = true;
|
||||
}
|
||||
|
||||
if (burg.port < 0) {
|
||||
ERROR && console.error("Data Integrity Check. Burg", burg.i, "has invalid port value", burg.port);
|
||||
ERROR && console.error("Data integrity check. Burg", burg.i, "has invalid port value", burg.port);
|
||||
burg.port = 0;
|
||||
}
|
||||
|
||||
if (burg.cell >= cells.i.length) {
|
||||
ERROR && console.error("Data Integrity Check. Burg", burg.i, "is linked to invalid cell", burg.cell);
|
||||
ERROR && console.error("Data integrity check. Burg", burg.i, "is linked to invalid cell", burg.cell);
|
||||
burg.cell = findCell(burg.x, burg.y);
|
||||
cells.i.filter(i => cells.burg[i] === burg.i).forEach(i => (cells.burg[i] = 0));
|
||||
cells.burg[burg.cell] = burg.i;
|
||||
}
|
||||
|
||||
if (burg.state && !pack.states[burg.state]) {
|
||||
ERROR && console.error("Data Integrity Check. Burg", burg.i, "is linked to invalid state", burg.state);
|
||||
ERROR && console.error("Data integrity check. Burg", burg.i, "is linked to invalid state", burg.state);
|
||||
burg.state = 0;
|
||||
}
|
||||
|
||||
if (burg.state && pack.states[burg.state].removed) {
|
||||
ERROR && console.error("Data Integrity Check. Burg", burg.i, "is linked to removed state", burg.state);
|
||||
ERROR && console.error("Data integrity check. Burg", burg.i, "is linked to removed state", burg.state);
|
||||
burg.state = 0;
|
||||
}
|
||||
|
||||
if (burg.state === undefined) {
|
||||
ERROR && console.error("Data Integrity Check. Burg", burg.i, "has no state data");
|
||||
ERROR && console.error("Data integrity check. Burg", burg.i, "has no state data");
|
||||
burg.state = 0;
|
||||
}
|
||||
});
|
||||
|
||||
pack.states.forEach(state => {
|
||||
if (state.removed) return;
|
||||
|
||||
const stateBurgs = pack.burgs.filter(b => b.state === state.i && !b.removed);
|
||||
const capitalBurgs = stateBurgs.filter(b => b.capital);
|
||||
|
||||
if (!state.i && capitalBurgs.length) {
|
||||
ERROR &&
|
||||
console.error(
|
||||
`Data integrity check. Neutral burgs (${capitalBurgs
|
||||
.map(b => b.i)
|
||||
.join(", ")}) marked as capitals. Moving them to towns`
|
||||
);
|
||||
|
||||
capitalBurgs.forEach(burg => {
|
||||
burg.capital = 0;
|
||||
moveBurgToGroup(burg.i, "towns");
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (capitalBurgs.length > 1) {
|
||||
const message = `Data integrity check. State ${state.i} has multiple capitals (${capitalBurgs
|
||||
.map(b => b.i)
|
||||
.join(", ")}) assigned. Keeping the first as capital and moving others to towns`;
|
||||
ERROR && console.error(message);
|
||||
|
||||
capitalBurgs.forEach((burg, i) => {
|
||||
if (!i) return;
|
||||
burg.capital = 0;
|
||||
moveBurgToGroup(burg.i, "towns");
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.i && stateBurgs.length && !capitalBurgs.length) {
|
||||
ERROR &&
|
||||
console.error(`Data integrity check. State ${state.i} has no capital. Assigning the first burg as capital`);
|
||||
stateBurgs[0].capital = 1;
|
||||
moveBurgToGroup(stateBurgs[0].i, "cities");
|
||||
}
|
||||
});
|
||||
|
||||
pack.provinces.forEach(p => {
|
||||
if (!p.i || p.removed) return;
|
||||
if (pack.states[p.state] && !pack.states[p.state].removed) return;
|
||||
ERROR && console.error("Data Integrity Check. Province", p.i, "is linked to removed state", p.state);
|
||||
ERROR && console.error("Data integrity check. Province", p.i, "is linked to removed state", p.state);
|
||||
p.removed = true; // remove incorrect province
|
||||
});
|
||||
|
||||
|
|
@ -604,7 +657,7 @@ async function parseLoadedData(data) {
|
|||
|
||||
pack.markers.forEach(marker => {
|
||||
if (markerIds[marker.i]) {
|
||||
ERROR && console.error("Data Integrity Check. Marker", marker.i, "has non-unique id. Changing to", nextId);
|
||||
ERROR && console.error("Data integrity check. Marker", marker.i, "has non-unique id. Changing to", nextId);
|
||||
|
||||
const domElements = document.querySelectorAll("#marker" + marker.i);
|
||||
if (domElements[1]) domElements[1].id = "marker" + nextId; // rename 2nd dom element
|
||||
|
|
@ -645,7 +698,7 @@ async function parseLoadedData(data) {
|
|||
ERROR && console.error(error);
|
||||
clearMainTip();
|
||||
|
||||
alertMessage.innerHTML = /* html */ `An error is occured on map loading. Select a different file to load, <br />generate a new random map or cancel the loading
|
||||
alertMessage.innerHTML = /* html */ `An error is occured on map loading. Select a different file to load, <br>generate a new random map or cancel the loading.<br>Map version: ${mapVersion}. Generator version: ${version}.
|
||||
<p id="errorBox">${parseError(error)}</p>`;
|
||||
|
||||
$("#alert").dialog({
|
||||
|
|
|
|||
|
|
@ -44,17 +44,17 @@ function prepareMapData() {
|
|||
const params = [version, license, dateString, seed, graphWidth, graphHeight, mapId].join("|");
|
||||
const settings = [
|
||||
distanceUnitInput.value,
|
||||
distanceScaleInput.value,
|
||||
distanceScale,
|
||||
areaUnit.value,
|
||||
heightUnit.value,
|
||||
heightExponentInput.value,
|
||||
temperatureScale.value,
|
||||
barSizeInput.value,
|
||||
barLabel.value,
|
||||
barBackOpacity.value,
|
||||
barBackColor.value,
|
||||
barPosX.value,
|
||||
barPosY.value,
|
||||
"", // previously used for barSize.value
|
||||
"", // previously used for barLabel.value
|
||||
"", // previously used for barBackColor.value
|
||||
"", // previously used for barBackColor.value
|
||||
"", // previously used for barPosX.value
|
||||
"", // previously used for barPosY.value
|
||||
populationRate,
|
||||
urbanization,
|
||||
mapSizeOutput.value,
|
||||
|
|
@ -67,7 +67,8 @@ function prepareMapData() {
|
|||
+hideLabels.checked,
|
||||
stylePreset.value,
|
||||
+rescaleLabels.checked,
|
||||
urbanDensity
|
||||
urbanDensity,
|
||||
longitudeOutput.value
|
||||
].join("|");
|
||||
const coords = JSON.stringify(mapCoordinates);
|
||||
const biomes = [biomesData.color, biomesData.habitability, biomesData.name].join("|");
|
||||
|
|
@ -97,6 +98,8 @@ function prepareMapData() {
|
|||
const provinces = JSON.stringify(pack.provinces);
|
||||
const rivers = JSON.stringify(pack.rivers);
|
||||
const markers = JSON.stringify(pack.markers);
|
||||
const cellRoutes = JSON.stringify(pack.cells.routes);
|
||||
const routes = JSON.stringify(pack.routes);
|
||||
|
||||
// store name array only if not the same as default
|
||||
const defaultNB = Names.getNameBases();
|
||||
|
|
@ -135,19 +138,21 @@ function prepareMapData() {
|
|||
pack.cells.fl,
|
||||
pop,
|
||||
pack.cells.r,
|
||||
pack.cells.road,
|
||||
[], // deprecated pack.cells.road
|
||||
pack.cells.s,
|
||||
pack.cells.state,
|
||||
pack.cells.religion,
|
||||
pack.cells.province,
|
||||
pack.cells.crossroad,
|
||||
[], // deprecated pack.cells.crossroad
|
||||
religions,
|
||||
provinces,
|
||||
namesData,
|
||||
rivers,
|
||||
rulersString,
|
||||
fonts,
|
||||
markers
|
||||
markers,
|
||||
cellRoutes,
|
||||
routes
|
||||
].join("\r\n");
|
||||
return mapData;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,7 +12,10 @@ window.Lakes = (function () {
|
|||
f.flux = f.shoreline.reduce((acc, c) => acc + grid.cells.prec[cells.g[c]], 0);
|
||||
|
||||
// temperature and evaporation to detect closed lakes
|
||||
f.temp = f.cells < 6 ? grid.cells.temp[cells.g[f.firstCell]] : rn(d3.mean(f.shoreline.map(c => grid.cells.temp[cells.g[c]])), 1);
|
||||
f.temp =
|
||||
f.cells < 6
|
||||
? grid.cells.temp[cells.g[f.firstCell]]
|
||||
: rn(d3.mean(f.shoreline.map(c => grid.cells.temp[cells.g[c]])), 1);
|
||||
const height = (f.height - 18) ** heightExponentInput.value; // height in meters
|
||||
const evaporation = ((700 * (f.temp + 0.006 * height)) / 50 + 75) / (80 - f.temp); // based on Penman formula, [1-11]
|
||||
f.evaporation = rn(evaporation * f.cells);
|
||||
|
|
@ -31,6 +34,7 @@ window.Lakes = (function () {
|
|||
// get array of land cells aroound lake
|
||||
const getShoreline = function (lake) {
|
||||
const uniqueCells = new Set();
|
||||
if (!lake.vertices) lake.vertices = [];
|
||||
lake.vertices.forEach(v => pack.vertices.c[v].forEach(c => pack.cells.h[c] >= 20 && uniqueCells.add(c)));
|
||||
lake.shoreline = [...uniqueCells];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ window.Markers = (function () {
|
|||
{type: "water-sources", icon: "💧", min: 1, each: 1000, multiplier: 1, list: listWaterSources, add: addWaterSource},
|
||||
{type: "mines", icon: "⛏️", dx: 48, px: 13, min: 1, each: 15, multiplier: 1, list: listMines, add: addMine},
|
||||
{type: "bridges", icon: "🌉", px: 14, min: 1, each: 5, multiplier: 1, list: listBridges, add: addBridge},
|
||||
{type: "inns", icon: "🍻", px: 14, min: 1, each: 100, multiplier: 1, list: listInns, add: addInn},
|
||||
{type: "inns", icon: "🍻", px: 14, min: 1, each: 10, multiplier: 1, list: listInns, add: addInn},
|
||||
{type: "lighthouses", icon: "🚨", px: 14, min: 1, each: 2, multiplier: 1, list: listLighthouses, add: addLighthouse},
|
||||
{type: "waterfalls", icon: "⟱", dy: 54, px: 16, min: 1, each: 5, multiplier: 1, list: listWaterfalls, add: addWaterfall},
|
||||
{type: "battlefields", icon: "⚔️", dy: 52, min: 50, each: 700, multiplier: 1, list: listBattlefields, add: addBattlefield},
|
||||
|
|
@ -279,7 +279,8 @@ window.Markers = (function () {
|
|||
}
|
||||
|
||||
function listInns({cells}) {
|
||||
return cells.i.filter(i => !occupied[i] && cells.h[i] >= 20 && cells.road[i] > 4 && cells.pop[i] > 10);
|
||||
const crossRoads = cells.i.filter(i => !occupied[i] && cells.pop[i] > 5 && Routes.isCrossroad(i));
|
||||
return crossRoads;
|
||||
}
|
||||
|
||||
function addInn(id, cell) {
|
||||
|
|
@ -542,7 +543,7 @@ window.Markers = (function () {
|
|||
|
||||
function listLighthouses({cells}) {
|
||||
return cells.i.filter(
|
||||
i => !occupied[i] && cells.harbor[i] > 6 && cells.c[i].some(c => cells.h[c] < 20 && cells.road[c])
|
||||
i => !occupied[i] && cells.harbor[i] > 6 && cells.c[i].some(c => cells.h[c] < 20 && Routes.isConnected(c))
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -642,7 +643,7 @@ window.Markers = (function () {
|
|||
|
||||
function listSeaMonsters({cells, features}) {
|
||||
return cells.i.filter(
|
||||
i => !occupied[i] && cells.h[i] < 20 && cells.road[i] && features[cells.f[i]].type === "ocean"
|
||||
i => !occupied[i] && cells.h[i] < 20 && Routes.isConnected(i) && features[cells.f[i]].type === "ocean"
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -792,7 +793,7 @@ window.Markers = (function () {
|
|||
cells.religion[i] &&
|
||||
cells.biome[i] === 1 &&
|
||||
cells.pop[i] > 1 &&
|
||||
cells.road[i]
|
||||
Routes.isConnected(i)
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -807,7 +808,7 @@ window.Markers = (function () {
|
|||
}
|
||||
|
||||
function listBrigands({cells}) {
|
||||
return cells.i.filter(i => !occupied[i] && cells.culture[i] && cells.road[i] > 4);
|
||||
return cells.i.filter(i => !occupied[i] && cells.culture[i] && Routes.hasRoad(i));
|
||||
}
|
||||
|
||||
function addBrigands(id, cell) {
|
||||
|
|
@ -867,7 +868,7 @@ window.Markers = (function () {
|
|||
|
||||
// Pirates spawn on sea routes
|
||||
function listPirates({cells}) {
|
||||
return cells.i.filter(i => !occupied[i] && cells.h[i] < 20 && cells.road[i]);
|
||||
return cells.i.filter(i => !occupied[i] && cells.h[i] < 20 && Routes.isConnected(i));
|
||||
}
|
||||
|
||||
function addPirates(id, cell) {
|
||||
|
|
@ -961,7 +962,7 @@ window.Markers = (function () {
|
|||
}
|
||||
|
||||
function listCircuses({cells}) {
|
||||
return cells.i.filter(i => !occupied[i] && cells.culture[i] && cells.h[i] >= 20 && pack.cells.road[i]);
|
||||
return cells.i.filter(i => !occupied[i] && cells.culture[i] && cells.h[i] >= 20 && Routes.isConnected(i));
|
||||
}
|
||||
|
||||
function addCircuse(id, cell) {
|
||||
|
|
@ -1254,16 +1255,16 @@ window.Markers = (function () {
|
|||
|
||||
const name = `${toponym} ${type}`;
|
||||
const legend = ra([
|
||||
"A foreboding necropolis shrouded in perpetual darkness, where eerie whispers echo through the winding corridors and spectral guardians stand watch over the tombs of long-forgotten souls",
|
||||
"A towering necropolis adorned with macabre sculptures and guarded by formidable undead sentinels. Its ancient halls house the remains of fallen heroes, entombed alongside their cherished relics",
|
||||
"This ethereal necropolis seems suspended between the realms of the living and the dead. Wisps of mist dance around the tombstones, while haunting melodies linger in the air, commemorating the departed",
|
||||
"Rising from the desolate landscape, this sinister necropolis is a testament to necromantic power. Its skeletal spires cast ominous shadows, concealing forbidden knowledge and arcane secrets",
|
||||
"An eerie necropolis where nature intertwines with death. Overgrown tombstones are entwined by thorny vines, and mournful spirits wander among the fading petals of once-vibrant flowers",
|
||||
"A labyrinthine necropolis where each step echoes with haunting murmurs. The walls are adorned with ancient runes, and restless spirits guide or hinder those who dare to delve into its depths",
|
||||
"This cursed necropolis is veiled in perpetual twilight, perpetuating a sense of impending doom. Dark enchantments shroud the tombs, and the moans of anguished souls resound through its crumbling halls",
|
||||
"A sprawling necropolis built within a labyrinthine network of catacombs. Its halls are lined with countless alcoves, each housing the remains of the departed, while the distant sound of rattling bones fills the air",
|
||||
"A desolate necropolis where an eerie stillness reigns. Time seems frozen amidst the decaying mausoleums, and the silence is broken only by the whispers of the wind and the rustle of tattered banners",
|
||||
"A foreboding necropolis perched atop a jagged cliff, overlooking a desolate wasteland. Its towering walls harbor restless spirits, and the imposing gates bear the marks of countless battles and ancient curses"
|
||||
"A foreboding necropolis shrouded in perpetual darkness, where eerie whispers echo through the winding corridors and spectral guardians stand watch over the tombs of long-forgotten souls.",
|
||||
"A towering necropolis adorned with macabre sculptures and guarded by formidable undead sentinels. Its ancient halls house the remains of fallen heroes, entombed alongside their cherished relics.",
|
||||
"This ethereal necropolis seems suspended between the realms of the living and the dead. Wisps of mist dance around the tombstones, while haunting melodies linger in the air, commemorating the departed.",
|
||||
"Rising from the desolate landscape, this sinister necropolis is a testament to necromantic power. Its skeletal spires cast ominous shadows, concealing forbidden knowledge and arcane secrets.",
|
||||
"An eerie necropolis where nature intertwines with death. Overgrown tombstones are entwined by thorny vines, and mournful spirits wander among the fading petals of once-vibrant flowers.",
|
||||
"A labyrinthine necropolis where each step echoes with haunting murmurs. The walls are adorned with ancient runes, and restless spirits guide or hinder those who dare to delve into its depths.",
|
||||
"This cursed necropolis is veiled in perpetual twilight, perpetuating a sense of impending doom. Dark enchantments shroud the tombs, and the moans of anguished souls resound through its crumbling halls.",
|
||||
"A sprawling necropolis built within a labyrinthine network of catacombs. Its halls are lined with countless alcoves, each housing the remains of the departed, while the distant sound of rattling bones fills the air.",
|
||||
"A desolate necropolis where an eerie stillness reigns. Time seems frozen amidst the decaying mausoleums, and the silence is broken only by the whispers of the wind and the rustle of tattered banners.",
|
||||
"A foreboding necropolis perched atop a jagged cliff, overlooking a desolate wasteland. Its towering walls harbor restless spirits, and the imposing gates bear the marks of countless battles and ancient curses."
|
||||
]);
|
||||
|
||||
notes.push({id, name, legend});
|
||||
|
|
|
|||
|
|
@ -10,7 +10,18 @@ window.Military = (function () {
|
|||
|
||||
const expn = d3.sum(valid.map(s => s.expansionism)); // total expansion
|
||||
const area = d3.sum(valid.map(s => s.area)); // total area
|
||||
const rate = {x: 0, Ally: -0.2, Friendly: -0.1, Neutral: 0, Suspicion: 0.1, Enemy: 1, Unknown: 0, Rival: 0.5, Vassal: 0.5, Suzerain: -0.5};
|
||||
const rate = {
|
||||
x: 0,
|
||||
Ally: -0.2,
|
||||
Friendly: -0.1,
|
||||
Neutral: 0,
|
||||
Suspicion: 0.1,
|
||||
Enemy: 1,
|
||||
Unknown: 0,
|
||||
Rival: 0.5,
|
||||
Vassal: 0.5,
|
||||
Suzerain: -0.5
|
||||
};
|
||||
|
||||
const stateModifier = {
|
||||
melee: {Nomadic: 0.5, Highland: 1.2, Lake: 1, Naval: 0.7, Hunting: 1.2, River: 1.1},
|
||||
|
|
@ -24,14 +35,59 @@ window.Military = (function () {
|
|||
};
|
||||
|
||||
const cellTypeModifier = {
|
||||
nomadic: {melee: 0.2, ranged: 0.5, mounted: 3, machinery: 0.4, naval: 0.3, armored: 1.6, aviation: 1, magical: 0.5},
|
||||
wetland: {melee: 0.8, ranged: 2, mounted: 0.3, machinery: 1.2, naval: 1.0, armored: 0.2, aviation: 0.5, magical: 0.5},
|
||||
highland: {melee: 1.2, ranged: 1.6, mounted: 0.3, machinery: 3, naval: 1.0, armored: 0.8, aviation: 0.3, magical: 2}
|
||||
nomadic: {
|
||||
melee: 0.2,
|
||||
ranged: 0.5,
|
||||
mounted: 3,
|
||||
machinery: 0.4,
|
||||
naval: 0.3,
|
||||
armored: 1.6,
|
||||
aviation: 1,
|
||||
magical: 0.5
|
||||
},
|
||||
wetland: {
|
||||
melee: 0.8,
|
||||
ranged: 2,
|
||||
mounted: 0.3,
|
||||
machinery: 1.2,
|
||||
naval: 1.0,
|
||||
armored: 0.2,
|
||||
aviation: 0.5,
|
||||
magical: 0.5
|
||||
},
|
||||
highland: {
|
||||
melee: 1.2,
|
||||
ranged: 1.6,
|
||||
mounted: 0.3,
|
||||
machinery: 3,
|
||||
naval: 1.0,
|
||||
armored: 0.8,
|
||||
aviation: 0.3,
|
||||
magical: 2
|
||||
}
|
||||
};
|
||||
|
||||
const burgTypeModifier = {
|
||||
nomadic: {melee: 0.3, ranged: 0.8, mounted: 3, machinery: 0.4, naval: 1.0, armored: 1.6, aviation: 1, magical: 0.5},
|
||||
wetland: {melee: 1, ranged: 1.6, mounted: 0.2, machinery: 1.2, naval: 1.0, armored: 0.2, aviation: 0.5, magical: 0.5},
|
||||
nomadic: {
|
||||
melee: 0.3,
|
||||
ranged: 0.8,
|
||||
mounted: 3,
|
||||
machinery: 0.4,
|
||||
naval: 1.0,
|
||||
armored: 1.6,
|
||||
aviation: 1,
|
||||
magical: 0.5
|
||||
},
|
||||
wetland: {
|
||||
melee: 1,
|
||||
ranged: 1.6,
|
||||
mounted: 0.2,
|
||||
machinery: 1.2,
|
||||
naval: 1.0,
|
||||
armored: 0.2,
|
||||
aviation: 0.5,
|
||||
magical: 0.5
|
||||
},
|
||||
highland: {melee: 1.2, ranged: 2, mounted: 0.3, machinery: 3, naval: 1.0, armored: 0.8, aviation: 0.3, magical: 2}
|
||||
};
|
||||
|
||||
|
|
@ -40,8 +96,16 @@ window.Military = (function () {
|
|||
const d = s.diplomacy;
|
||||
|
||||
const expansionRate = minmax(s.expansionism / expn / (s.area / area), 0.25, 4); // how much state expansionism is realized
|
||||
const diplomacyRate = d.some(d => d === "Enemy") ? 1 : d.some(d => d === "Rival") ? 0.8 : d.some(d => d === "Suspicion") ? 0.5 : 0.1; // peacefulness
|
||||
const neighborsRateRaw = s.neighbors.map(n => (n ? pack.states[n].diplomacy[s.i] : "Suspicion")).reduce((s, r) => (s += rate[r]), 0.5);
|
||||
const diplomacyRate = d.some(d => d === "Enemy")
|
||||
? 1
|
||||
: d.some(d => d === "Rival")
|
||||
? 0.8
|
||||
: d.some(d => d === "Suspicion")
|
||||
? 0.5
|
||||
: 0.1; // peacefulness
|
||||
const neighborsRateRaw = s.neighbors
|
||||
.map(n => (n ? pack.states[n].diplomacy[s.i] : "Suspicion"))
|
||||
.reduce((s, r) => (s += rate[r]), 0.5);
|
||||
const neighborsRate = minmax(neighborsRateRaw, 0.3, 3); // neighbors rate
|
||||
s.alert = minmax(rn(expansionRate * diplomacyRate * neighborsRate, 2), 0.1, 5); // alert rate (area modifier)
|
||||
s.temp.platoons = [];
|
||||
|
|
@ -86,8 +150,10 @@ window.Military = (function () {
|
|||
|
||||
let modifier = cells.pop[i] / 100; // basic rural army in percentages
|
||||
if (culture !== stateObj.culture) modifier = stateObj.form === "Union" ? modifier / 1.2 : modifier / 2; // non-dominant culture
|
||||
if (religion !== cells.religion[stateObj.center]) modifier = stateObj.form === "Theocracy" ? modifier / 2.2 : modifier / 1.4; // non-dominant religion
|
||||
if (cells.f[i] !== cells.f[stateObj.center]) modifier = stateObj.type === "Naval" ? modifier / 1.2 : modifier / 1.8; // different landmass
|
||||
if (religion !== cells.religion[stateObj.center])
|
||||
modifier = stateObj.form === "Theocracy" ? modifier / 2.2 : modifier / 1.4; // non-dominant religion
|
||||
if (cells.f[i] !== cells.f[stateObj.center])
|
||||
modifier = stateObj.type === "Naval" ? modifier / 1.2 : modifier / 1.8; // different landmass
|
||||
const type = getType(i);
|
||||
|
||||
for (const unit of options.military) {
|
||||
|
|
@ -111,7 +177,17 @@ window.Military = (function () {
|
|||
n = 1;
|
||||
}
|
||||
|
||||
stateObj.temp.platoons.push({cell: i, a: total, t: total, x, y, u: unit.name, n, s: unit.separate, type: unit.type});
|
||||
stateObj.temp.platoons.push({
|
||||
cell: i,
|
||||
a: total,
|
||||
t: total,
|
||||
x,
|
||||
y,
|
||||
u: unit.name,
|
||||
n,
|
||||
s: unit.separate,
|
||||
type: unit.type
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -153,7 +229,17 @@ window.Military = (function () {
|
|||
n = 1;
|
||||
}
|
||||
|
||||
stateObj.temp.platoons.push({cell: b.cell, a: total, t: total, x, y, u: unit.name, n, s: unit.separate, type: unit.type});
|
||||
stateObj.temp.platoons.push({
|
||||
cell: b.cell,
|
||||
a: total,
|
||||
t: total,
|
||||
x,
|
||||
y,
|
||||
u: unit.name,
|
||||
n,
|
||||
s: unit.separate,
|
||||
type: unit.type
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -261,7 +347,8 @@ window.Military = (function () {
|
|||
const army = armies
|
||||
.append("g")
|
||||
.attr("id", "army" + s)
|
||||
.attr("fill", baseColor);
|
||||
.attr("fill", baseColor)
|
||||
.attr("color", darkerColor);
|
||||
|
||||
const g = army
|
||||
.selectAll("g")
|
||||
|
|
@ -271,7 +358,9 @@ window.Military = (function () {
|
|||
.attr("id", d => "regiment" + s + "-" + d.i)
|
||||
.attr("data-name", d => d.name)
|
||||
.attr("data-state", s)
|
||||
.attr("data-id", d => d.i);
|
||||
.attr("data-id", d => d.i)
|
||||
.attr("transform", d => (d.angle ? `rotate(${d.angle})` : null))
|
||||
.attr("transform-origin", d => `${d.x}px ${d.y}px`);
|
||||
g.append("rect")
|
||||
.attr("x", d => x(d))
|
||||
.attr("y", d => y(d))
|
||||
|
|
@ -282,7 +371,7 @@ window.Military = (function () {
|
|||
.attr("y", d => d.y)
|
||||
.text(d => getTotal(d));
|
||||
g.append("rect")
|
||||
.attr("fill", darkerColor)
|
||||
.attr("fill", "currentColor")
|
||||
.attr("x", d => x(d) - h)
|
||||
.attr("y", d => y(d))
|
||||
.attr("width", h)
|
||||
|
|
@ -294,33 +383,36 @@ window.Military = (function () {
|
|||
.text(d => d.icon);
|
||||
};
|
||||
|
||||
const drawRegiment = function (reg, s) {
|
||||
const drawRegiment = function (reg, stateId) {
|
||||
const size = +armies.attr("box-size");
|
||||
const w = reg.n ? size * 4 : size * 6;
|
||||
const h = size * 2;
|
||||
const x1 = rn(reg.x - w / 2, 2);
|
||||
const y1 = rn(reg.y - size, 2);
|
||||
|
||||
let army = armies.select("g#army" + s);
|
||||
let army = armies.select("g#army" + stateId);
|
||||
if (!army.size()) {
|
||||
const baseColor = pack.states[s].color[0] === "#" ? pack.states[s].color : "#999";
|
||||
const baseColor = pack.states[stateId].color[0] === "#" ? pack.states[stateId].color : "#999";
|
||||
const darkerColor = d3.color(baseColor).darker().hex();
|
||||
army = armies
|
||||
.append("g")
|
||||
.attr("id", "army" + s)
|
||||
.attr("fill", baseColor);
|
||||
.attr("id", "army" + stateId)
|
||||
.attr("fill", baseColor)
|
||||
.attr("color", darkerColor);
|
||||
}
|
||||
const darkerColor = d3.color(army.attr("fill")).darker().hex();
|
||||
|
||||
const g = army
|
||||
.append("g")
|
||||
.attr("id", "regiment" + s + "-" + reg.i)
|
||||
.attr("id", "regiment" + stateId + "-" + reg.i)
|
||||
.attr("data-name", reg.name)
|
||||
.attr("data-state", s)
|
||||
.attr("data-id", reg.i);
|
||||
.attr("data-state", stateId)
|
||||
.attr("data-id", reg.i)
|
||||
.attr("transform", `rotate(${reg.angle || 0})`)
|
||||
.attr("transform-origin", `${reg.x}px ${reg.y}px`);
|
||||
g.append("rect").attr("x", x1).attr("y", y1).attr("width", w).attr("height", h);
|
||||
g.append("text").attr("x", reg.x).attr("y", reg.y).text(getTotal(reg));
|
||||
g.append("rect")
|
||||
.attr("fill", darkerColor)
|
||||
.attr("fill", "currentColor")
|
||||
.attr("x", x1 - h)
|
||||
.attr("y", y1)
|
||||
.attr("width", h)
|
||||
|
|
@ -379,7 +471,13 @@ window.Military = (function () {
|
|||
// get default regiment emblem
|
||||
const getEmblem = function (r) {
|
||||
if (!r.n && !Object.values(r.u).length) return "🔰"; // "Newbie" regiment without troops
|
||||
if (!r.n && pack.states[r.state].form === "Monarchy" && pack.cells.burg[r.cell] && pack.burgs[pack.cells.burg[r.cell]].capital) return "👑"; // "Royal" regiment based in capital
|
||||
if (
|
||||
!r.n &&
|
||||
pack.states[r.state].form === "Monarchy" &&
|
||||
pack.cells.burg[r.cell] &&
|
||||
pack.burgs[pack.cells.burg[r.cell]].capital
|
||||
)
|
||||
return "👑"; // "Royal" regiment based in capital
|
||||
const mainUnit = Object.entries(r.u).sort((a, b) => b[1] - a[1])[0][0]; // unit with more troops in regiment
|
||||
const unit = options.military.find(u => u.name === mainUnit);
|
||||
return unit.icon;
|
||||
|
|
@ -400,7 +498,9 @@ window.Military = (function () {
|
|||
.map(t => `— ${t}: ${r.u[t]}`)
|
||||
.join("\r\n")
|
||||
: null;
|
||||
const troops = composition ? `\r\n\r\nRegiment composition in ${options.year} ${options.eraShort}:\r\n${composition}.` : "";
|
||||
const troops = composition
|
||||
? `\r\n\r\nRegiment composition in ${options.year} ${options.eraShort}:\r\n${composition}.`
|
||||
: "";
|
||||
|
||||
const campaign = s.campaigns ? ra(s.campaigns) : null;
|
||||
const year = campaign ? rand(campaign.start, campaign.end) : gauss(options.year - 100, 150, 1, options.year - 6);
|
||||
|
|
@ -409,5 +509,16 @@ window.Military = (function () {
|
|||
notes.push({id: `regiment${s.i}-${r.i}`, name: `${r.icon} ${r.name}`, legend});
|
||||
};
|
||||
|
||||
return {generate, redraw, getDefaultOptions, getName, generateNote, drawRegiments, drawRegiment, moveRegiment, getTotal, getEmblem};
|
||||
return {
|
||||
generate,
|
||||
redraw,
|
||||
getDefaultOptions,
|
||||
getName,
|
||||
generateNote,
|
||||
drawRegiments,
|
||||
drawRegiment,
|
||||
moveRegiment,
|
||||
getTotal,
|
||||
getEmblem
|
||||
};
|
||||
})();
|
||||
|
|
|
|||
|
|
@ -286,11 +286,11 @@ window.Names = (function () {
|
|||
{name: "Basque", i: 20, min: 4, max: 11, d: "r", m: .1, b: "Agurain,Aia,Aiara,Albiztur,Alkiza,Altzaga,Amorebieta,Amurrio,Andoain,Anoeta,Antzuola,Arakaldo,Arantzazu,Arbatzegi,Areatza,Arratzua,Arrieta,Artea,Artziniega,Asteasu,Astigarraga,Ataun,Atxondo,Aulesti,Azkoitia,Azpeitia,Bakio,Baliarrain,Barakaldo,Barrika,Barrundia,Basauri,Beasain,Bedia,Beizama,Belauntza,Berastegi,Bergara,Bermeo,Bernedo,Berriatua,Berriz,Bidania,Bilar,Bilbao,Busturia,Deba,Derio,Donostia,Dulantzi,Durango,Ea,Eibar,Elantxobe,Elduain,Elgeta,Elgoibar,Elorrio,Erandio,Ergoitia,Ermua,Errenteria,Errezil,Eskoriatza,Eskuernaga,Etxebarri,Etxebarria,Ezkio,Forua,Gabiria,Gaintza,Galdakao,Gamiz,Garai,Gasteiz,Gatzaga,Gaubea,Gautegiz,Gaztelu,Gernika,Gerrikaitz,Getaria,Getxo,Gizaburuaga,Goiatz,Gorliz,Gorriaga,Harana,Hernani,Hondarribia,Ibarra,Ibarrangelu,Idiazabal,Iekora,Igorre,Ikaztegieta,Irun,Irura,Iruraiz,Itsaso,Itsasondo,Iurreta,Izurtza,Jatabe,Kanpezu,Karrantza,Kortezubi,Kripan,Kuartango,Lanestosa,Lantziego,Larrabetzu,Lasarte,Laukiz,Lazkao,Leaburu,Legazpi,Legorreta,Legutio,Leintz,Leioa,Lekeitio,Lemoa,Lemoiz,Leza,Lezama,Lezo,Lizartza,Maeztu,Mallabia,Manaria,Markina,Maruri,Menaka,Mendaro,Mendata,Mendexa,Morga,Mundaka,Mungia,Munitibar,Murueta,Muskiz,Mutiloa,Mutriku,Nabarniz,Oiartzun,Oion,Okondo,Olaberria,Onati,Ondarroa,Ordizia,Orendain,Orexa,Oria,Orio,Ormaiztegi,Orozko,Ortuella,Otegi,Otxandio,Pasaia,Plentzia,Santurtzi,Sestao,Sondika,Soraluze,Sukarrieta,Tolosa,Trapagaran,Turtzioz,Ubarrundia,Ubide,Ugao,Urdua,Urduliz,Urizaharra,Urkabustaiz,Urnieta,Urretxu,Usurbil,Xemein,Zabaleta,Zaia,Zaldibar,Zambrana,Zamudio,Zaratamo,Zarautz,Zeberio,Zegama,Zerain,Zestoa,Zierbena,Zigoitia,Ziortza,Zuia,Zumaia,Zumarraga"},
|
||||
{name: "Nigerian", i: 21, min: 4, max: 10, d: "", m: .3, b: "Abadogo,Abafon,Adealesu,Adeto,Adyongo,Afaga,Afamju,Agigbigi,Agogoke,Ahute,Aiyelaboro,Ajebe,Ajola,Akarekwu,Akunuba,Alawode,Alkaijji,Amangam,Amgbaye,Amtasa,Amunigun,Animahun,Anyoko,Arapagi,Asande,Awgbagba,Awhum,Awodu,Babateduwa,Bandakwai,Bangdi,Bilikani,Birnindodo,Braidu,Bulakawa,Buriburi,Cainnan,Chakum,Chondugh,Dagwarga,Darpi,Dokatofa,Dozere,Ebelibri,Efem,Ekoku,Ekpe,Ewhoeviri,Galea,Gamen,Ganjin,Gantetudu,Gargar,Garinbode,Gbure,Gerti,Gidan,Gitabaremu,Giyagiri,Giyawa,Gmawa,Golakochi,Golumba,Gunji,Gwambula,Gwodoti,Hayinlere,Hayinmaialewa,Hirishi,Hombo,Ibefum,Iberekodo,Icharge,Idofin,Idofinoka,Igbogo,Ijoko,Ijuwa,Ikawga,Ikhin,Ikpakidout,Ikpeoniong,Imuogo,Ipawo,Ipinlerere,Isicha,Itakpa,Jangi,Jare,Jataudakum,Jaurogomki,Jepel,Kafinmalama,Katab,Katanga,Katinda,Katirije,Kaurakimba,Keffinshanu,Kellumiri,Kiagbodor,Kirbutu,Kita,Kogogo,Kopje,Korokorosei,Kotoku,Kuata,Kujum,Kukau,Kunboon,Kuonubogbene,Kurawe,Kushinahu,Kwaramakeri,Ladimeji,Lafiaro,Lahaga,Laindebajanle,Laindegoro,Lakati,Litenswa,Maba,Madarzai,Maianita,Malikansaa,Mata,Megoyo,Meku,Miama,Modi,Mshi,Msugh,Muduvu,Murnachehu,Namnai,Ndamanma,Ndiwulunbe,Ndonutim,Ngbande,Nguengu,Ntoekpe,Nyajo,Nyior,Odajie,Ogbaga,Ogultu,Ogunbunmi,Ojopode,Okehin,Olugunna,Omotunde,Onipede,Onma,Orhere,Orya,Otukwang,Otunade,Rampa,Rimi,Rugan,Rumbukawa,Sabiu,Sangabama,Sarabe,Seboregetore,Shafar,Shagwa,Shata,Shengu,Sokoron,Sunnayu,Tafoki,Takula,Talontan,Tarhemba,Tayu,Ter,Timtim,Timyam,Tindirke,Tokunbo,Torlwam,Tseakaadza,Tseanongo,Tsebeeve,Tsepaegh,Tuba,Tumbo,Tungalombo,Tunganyakwe,Uhkirhi,Umoru,Umuabai,Umuajuju,Unchida,Ungua,Unguwar,Unongo,Usha,Utongbo,Vembera,Wuro,Yanbashi,Yanmedi,Yoku,Zarunkwari,Zilumo,Zulika"},
|
||||
{name: "Celtic", i: 22, min: 4, max: 12, d: "nld", m: 0, b: "Aberaman,Aberangell,Aberarth,Aberavon,Aberbanc,Aberbargoed,Aberbeeg,Abercanaid,Abercarn,Abercastle,Abercegir,Abercraf,Abercregan,Abercych,Abercynon,Aberdare,Aberdaron,Aberdaugleddau,Aberdeen,Aberdulais,Aberdyfi,Aberedw,Abereiddy,Abererch,Abereron,Aberfan,Aberffraw,Aberffrwd,Abergavenny,Abergele,Aberglasslyn,Abergorlech,Abergwaun,Abergwesyn,Abergwili,Abergwynfi,Abergwyngregyn,Abergynolwyn,Aberhafesp,Aberhonddu,Aberkenfig,Aberllefenni,Abermain,Abermaw,Abermorddu,Abermule,Abernant,Aberpennar,Aberporth,Aberriw,Abersoch,Abersychan,Abertawe,Aberteifi,Aberthin,Abertillery,Abertridwr,Aberystwyth,Achininver,Afonhafren,Alisaha,Anfosadh,Antinbhearmor,Ardenna,Attacon,Banwen,Beira,Bhrura,Bleddfa,Boioduro,Bona,Boskyny,Boslowenpolbrogh,Boudobriga,Bravon,Brigant,Briganta,Briva,Brosnach,Caersws,Cambodunum,Cambra,Caracta,Catumagos,Centobriga,Ceredigion,Chalain,Chearbhallain,Chlasaigh,Chormaic,Cuileannach,Dinn,Diwa,Dubingen,Duibhidighe,Duro,Ebora,Ebruac,Eburodunum,Eccles,Egloskuri,Eighe,Eireann,Elerghi,Ferkunos,Fhlaithnin,Gallbhuaile,Genua,Ghrainnse,Gwyles,Heartsease,Hebron,Hordh,Inbhear,Inbhir,Inbhirair,Innerleithen,Innerleven,Innerwick,Inver,Inveraldie,Inverallan,Inveralmond,Inveramsay,Inveran,Inveraray,Inverarnan,Inverbervie,Inverclyde,Inverell,Inveresk,Inverfarigaig,Invergarry,Invergordon,Invergowrie,Inverhaddon,Inverkeilor,Inverkeithing,Inverkeithney,Inverkip,Inverleigh,Inverleith,Inverloch,Inverlochlarig,Inverlochy,Invermay,Invermoriston,Inverness,Inveroran,Invershin,Inversnaid,Invertrossachs,Inverugie,Inveruglas,Inverurie,Iubhrach,Karardhek,Kilninver,Kirkcaldy,Kirkintilloch,Krake,Lanngorrow,Latense,Leming,Lindomagos,Llanaber,Llandidiwg,Llandyrnog,Llanfarthyn,Llangadwaldr,Llansanwyr,Lochinver,Lugduno,Magoduro,Mheara,Monmouthshire,Nanshiryarth,Narann,Novioduno,Nowijonago,Octoduron,Penning,Pheofharain,Ponsmeur,Raithin,Ricomago,Rossinver,Salodurum,Seguia,Sentica,Theorsa,Tobargeal,Trealaw,Trefesgob,Trewedhenek,Trewythelan,Tuaisceart,Uige,Vitodurum,Windobona"},
|
||||
{name: "Mesopotamian", i: 23, min: 4, max: 9, d: "srpl", m: .1, b: "Adab,Adamndun,Adma,Admatum,Agrab,Akkad,Akshak,Amnanum,Andarig,Anshan,Apiru,Apum,Arantu,Arbid,Arpachiyah,Arpad,Arrapha,Ashlakka,Assur,Awan,Babilim,Bad-Tibira,Balawat,Barsip,Birtu,Bit-Bunakki,Borsippa,Chuera,Dashrah,Der,Dilbat,Diniktum,Doura,Dur-Kurigalzu,Dur-Sharrukin,Dur-Untash,Dûr-gurgurri,Ebla,Ekallatum,Ekalte,Emar,Erbil,Eresh,Eridu,Eshnunn,Eshnunna,Gargamish,Gasur,Gawra,Gibil,Girsu,Gizza,Habirun,Habur,Hadatu,Hakkulan,Halab,Halabit,Hamazi,Hamoukar,Haradum,Harbidum,Harran,Harranu,Hassuna,Hatarikka,Hatra,Hissar,Hiyawa,Hormirzad,Ida-Maras,Idamaraz,Idu,Imerishu,Imgur-Enlil,Irisagrig,Irnina,Irridu,Isin,Issinnitum,Iturungal,Izubitum,Jarmo,Jemdet,Kabnak,Kadesh,Kahat,Kalhu,Kar-Shulmanu-Asharedu,Kar-Tukulti-Ninurta,Kar-Šulmānu-ašarēdu,Karana,Karatepe,Kartukulti,Kazallu,Kesh,Kidsha,Kinza,Kish,Kisiga,Kisurra,Kuara,Kurda,Kurruhanni,Kutha,Lagaba,Lagash,Larak,Larsa,Leilan,Malgium,Marad,Mardaman,Mari,Marlik,Mashkan,Mashkan-shapir,Matutem,Me-Turan,Meliddu,Mumbaqat,Nabada,Nagar,Nanagugal,Nerebtum,Nigin,Nimrud,Nina,Nineveh,Ninua,Nippur,Niru,Niya,Nuhashe,Nuhasse,Nuzi,Puzrish-Dagan,Qalatjarmo,Qatara,Qatna,Qattunan,Qidshu,Rapiqum,Rawda,Sagaz,Shaduppum,Shaggaratum,Shalbatu,Shanidar,Sharrukin,Shawwan,Shehna,Shekhna,Shemshara,Shibaniba,Shubat-Enlil,Shurkutir,Shuruppak,Shusharra,Shushin,Sikan,Sippar,Sippar-Amnanum,Sippar-sha-Annunitum,Subatum,Susuka,Tadmor,Tarbisu,Telul,Terqa,Tirazish,Tisbon,Tuba,Tushhan,Tuttul,Tutub,Ubaid,Umma,Ur,Urah,Urbilum,Urkesh,Ursa'um,Uruk,Urum,Uzarlulu,Warka,Washukanni,Zabalam,Zarri-Amnan"},
|
||||
{name: "Mesopotamian", i: 23, min: 4, max: 9, d: "srpl", m: .1, b: "Adab,Adamndun,Adma,Admatum,Agrab,Akkad,Akshak,Amnanum,Andarig,Anshan,Apiru,Apum,Arantu,Arbid,Arpachiyah,Arpad,Arrapha,Ashlakka,Assur,Awan,Babilim,Bad-Tibira,Balawat,Barsip,Birtu,Bit-Bunakki,Borsippa,Chuera,Dashrah,Der,Dilbat,Diniktum,Doura,Dur-Kurigalzu,Dur-Sharrukin,Dur-Untash,Dûr-gurgurri,Ebla,Ekallatum,Ekalte,Emar,Erbil,Eresh,Eridu,Eshnunn,Eshnunna,Gargamish,Gasur,Gawra,Gibil,Girsu,Gizza,Habirun,Habur,Hadatu,Hakkulan,Halab,Halabit,Hamazi,Hamoukar,Haradum,Harbidum,Harran,Harranu,Hassuna,Hatarikka,Hatra,Hissar,Hiyawa,Hormirzad,Ida-Maras,Idamaraz,Idu,Imerishu,Imgur-Enlil,Irisagrig,Irnina,Irridu,Isin,Issinnitum,Iturungal,Izubitum,Jarmo,Jemdet,Kabnak,Kadesh,Kahat,Kalhu,Kar-Shulmanu-Asharedu,Kar-Tukulti-Ninurta,Kar-shulmanu-asharedu,Karana,Karatepe,Kartukulti,Kazallu,Kesh,Kidsha,Kinza,Kish,Kisiga,Kisurra,Kuara,Kurda,Kurruhanni,Kutha,Lagaba,Lagash,Larak,Larsa,Leilan,Malgium,Marad,Mardaman,Mari,Marlik,Mashkan,Mashkan-shapir,Matutem,Me-Turan,Meliddu,Mumbaqat,Nabada,Nagar,Nanagugal,Nerebtum,Nigin,Nimrud,Nina,Nineveh,Ninua,Nippur,Niru,Niya,Nuhashe,Nuhasse,Nuzi,Puzrish-Dagan,Qalatjarmo,Qatara,Qatna,Qattunan,Qidshu,Rapiqum,Rawda,Sagaz,Shaduppum,Shaggaratum,Shalbatu,Shanidar,Sharrukin,Shawwan,Shehna,Shekhna,Shemshara,Shibaniba,Shubat-Enlil,Shurkutir,Shuruppak,Shusharra,Shushin,Sikan,Sippar,Sippar-Amnanum,Sippar-sha-Annunitum,Subatum,Susuka,Tadmor,Tarbisu,Telul,Terqa,Tirazish,Tisbon,Tuba,Tushhan,Tuttul,Tutub,Ubaid,Umma,Ur,Urah,Urbilum,Urkesh,Ursa'um,Uruk,Urum,Uzarlulu,Warka,Washukanni,Zabalam,Zarri-Amnan"},
|
||||
{name: "Iranian", i: 24, min: 5, max: 11, d: "", m: .1, b: "Abali,Abrisham,Absard,Abuzeydabad,Afus,Alavicheh,Alikosh,Amol,Anarak,Anbar,Andisheh,Anshan,Aran,Ardabil,Arderica,Ardestan,Arjomand,Asgaran,Asgharabad,Ashian,Awan,Babajan,Badrud,Bafran,Baghestan,Baghshad,Bahadoran,Baharan Shahr,Baharestan,Bakun,Bam,Baqershahr,Barzok,Bastam,Behistun,Bitistar,Bumahen,Bushehr,Chadegan,Chahardangeh,Chamgardan,Chermahin,Choghabonut,Chugan,Damaneh,Damavand,Darabgard,Daran,Dastgerd,Dehaq,Dehaqan,Dezful,Dizicheh,Dorcheh,Dowlatabad,Duruntash,Ecbatana,Eslamshahr,Estakhr,Ezhiyeh,Falavarjan,Farrokhi,Fasham,Ferdowsieh,Fereydunshahr,Ferunabad,Firuzkuh,Fuladshahr,Ganjdareh,Ganzak,Gaz,Geoy,Godin,Goldasht,Golestan,Golpayegan,Golshahr,Golshan,Gorgab,Guged,Habibabad,Hafshejan,Hajjifiruz,Hana,Harand,Hasanabad,Hasanlu,Hashtgerd,Hecatompylos,Hormirzad,Imanshahr,Isfahan,Jandaq,Javadabad,Jiroft,Jowsheqan ,Jowzdan,Kabnak,Kahrizak,Kahriz Sang,Kangavar,Karaj,Karkevand,Kashan,Kelishad,Kermanshah,Khaledabad,Khansar,Khorramabad,Khur,Khvorzuq,Kilan,Komeh,Komeshcheh,Konar,Kuhpayeh,Kul,Kushk,Lavasan,Laybid,Liyan,Lyan,Mahabad,Mahallat,Majlesi,Malard,Manzariyeh,Marlik,Meshkat,Meymeh,Miandasht,Mish,Mobarakeh,Nahavand,Nain,Najafabad,Naqshe,Narezzash,Nasimshahr,Nasirshahr,Nasrabad,Natanz,Neyasar,Nikabad,Nimvar,Nushabad,Pakdasht,Parand,Pardis,Parsa,Pasargadai,Patigrabana,Pir Bakran,Pishva,Qahderijan,Qahjaverestan,Qamsar,Qarchak,Qods,Rabat,Ray-shahr,Rezvanshahr,Rhages,Robat Karim,Rozveh,Rudehen,Sabashahr,Safadasht,Sagzi,Salehieh,Sandal,Sarvestan,Sedeh,Sefidshahr,Semirom,Semnan,Shadpurabad,Shah,Shahdad,Shahedshahr,Shahin,Shahpour,Shahr,Shahreza,Shahriar,Sharifabad,Shemshak,Shiraz,Shushan,Shushtar,Sialk,Sin,Sukhteh,Tabas,Tabriz,Takhte,Talkhuncheh,Talli,Tarq,Temukan,Tepe,Tiran,Tudeshk,Tureng,Urmia,Vahidieh,Vahrkana,Vanak,Varamin,Varnamkhast,Varzaneh,Vazvan,Yahya,Yarim,Yasuj,Zarrin Shahr,Zavareh,Zayandeh,Zazeran,Ziar,Zibashahr,Zranka"},
|
||||
{name: "Hawaiian", i: 25, min: 5, max: 10, d: "auo", m: 1, b: "Aapueo,Ahoa,Ahuakaio,Ahupau,Alaakua,Alae,Alaeloa,Alamihi,Aleamai,Alena,Alio,Aupokopoko,Halakaa,Haleu,Haliimaile,Hamoa,Hanakaoo,Hanaulu,Hanawana,Hanehoi,Haou,Hikiaupea,Hokuula,Honohina,Honokahua,Honokeana,Honokohau,Honolulu,Honomaele,Hononana,Honopou,Hoolawa,Huelo,Kaalaea,Kaapahu,Kaeo,Kahalehili,Kahana,Kahuai,Kailua,Kainehe,Kakalahale,Kakanoni,Kalenanui,Kaleoaihe,Kalialinui,Kalihi,Kalimaohe,Kaloi,Kamani,Kamehame,Kanahena,Kaniaula,Kaonoulu,Kapaloa,Kapohue,Kapuaikini,Kapunakea,Kauau,Kaulalo,Kaulanamoa,Kauluohana,Kaumakani,Kaumanu,Kaunauhane,Kaupakulua,Kawaloa,Keaa,Keaaula,Keahua,Keahuapono,Kealahou,Keanae,Keauhou,Kelawea,Keokea,Keopuka,Kikoo,Kipapa,Koakupuna,Koali,Kolokolo,Kopili,Kou,Kualapa,Kuhiwa,Kuholilea,Kuhua,Kuia,Kuikui,Kukoae,Kukohia,Kukuiaeo,Kukuipuka,Kukuiula,Kulahuhu,Lapakea,Lapueo,Launiupoko,Lole,Maalo,Mahinahina,Mailepai,Makaakini,Makaalae,Makaehu,Makaiwa,Makaliua,Makapipi,Makapuu,Maluaka,Manawainui,Mehamenui,Moalii,Moanui,Mohopili,Mokae,Mokuia,Mokupapa,Mooiki,Mooloa,Moomuku,Muolea,Nakaaha,Nakalepo,Nakaohu,Nakapehu,Nakula,Napili,Niniau,Nuu,Oloewa,Olowalu,Omaopio,Onau,Onouli,Opaeula,Opana,Opikoula,Paakea,Paeahu,Paehala,Paeohi,Pahoa,Paia,Pakakia,Palauea,Palemo,Paniau,Papaaea,Papaanui,Papaauhau,Papaka,Papauluana,Pauku,Paunau,Pauwalu,Pauwela,Pohakanele,Polaiki,Polanui,Polapola,Poopoo,Poponui,Poupouwela,Puahoowali,Puakea,Puako,Pualaea,Puehuehu,Pueokauiki,Pukaauhuhu,Pukuilua,Pulehu,Puolua,Puou,Puuhaehae,Puuiki,Puuki,Puulani,Puunau,Puuomaile,Uaoa,Uhao,Ukumehame,Ulaino,Ulumalu,Wahikuli,Waianae,Waianu,Waiawa,Waiehu,Waieli,Waikapu,Wailamoa,Wailaulau,Wainee,Waiohole,Waiohonu,Waiohuli,Waiokama,Waiokila,Waiopai,Waiopua,Waipao,Waipionui,Waipouli"},
|
||||
{name: "Karnataka", i: 26, min: 5, max: 11, d: "tnl", m: 0, b: "Adityapatna,Adyar,Afzalpur,Aland,Alnavar,Alur,Ambikanagara,Anekal,Ankola,Annigeri,Arkalgud,Arsikere,Athni,Aurad,Badami,Bagalkot,Bagepalli,Bail,Bajpe,Bangalore,Bangarapet,Bankapura,Bannur,Bantval,Basavakalyan,Basavana,Belgaum,Beltangadi,Belur,Bhadravati,Bhalki,Bhatkal,Bhimarayanagudi,Bidar,Bijapur,Bilgi,Birur,Bommasandra,Byadgi,Challakere,Chamarajanagar,Channagiri,Channapatna,Channarayapatna,Chik,Chikmagalur,Chiknayakanhalli,Chikodi,Chincholi,Chintamani,Chitapur,Chitgoppa,Chitradurga,Dandeli,Dargajogihalli,Devadurga,Devanahalli,Dod,Donimalai,Gadag,Gajendragarh,Gangawati,Gauribidanur,Gokak,Gonikoppal,Gubbi,Gudibanda,Gulbarga,Guledgudda,Gundlupet,Gurmatkal,Haliyal,Hangal,Harapanahalli,Harihar,Hassan,Hatti,Haveri,Hebbagodi,Heggadadevankote,Hirekerur,Holalkere,Hole,Homnabad,Honavar,Honnali,Hoovina,Hosakote,Hosanagara,Hosdurga,Hospet,Hubli,Hukeri,Hungund,Hunsur,Ilkal,Indi,Jagalur,Jamkhandi,Jevargi,Jog,Kadigenahalli,Kadur,Kalghatgi,Kamalapuram,Kampli,Kanakapura,Karkal,Karwar,Khanapur,Kodiyal,Kolar,Kollegal,Konnur,Koppa,Koppal,Koratagere,Kotturu,Krishnarajanagara,Krishnarajasagara,Krishnarajpet,Kudchi,Kudligi,Kudremukh,Kumta,Kundapura,Kundgol,Kunigal,Kurgunta,Kushalnagar,Kushtagi,Lakshmeshwar,Lingsugur,Londa,Maddur,Madhugiri,Madikeri,Mahalingpur,Malavalli,Mallar,Malur,Mandya,Mangalore,Manvi,Molakalmuru,Mudalgi,Mudbidri,Muddebihal,Mudgal,Mudhol,Mudigere,Mulbagal,Mulgund,Mulki,Mulur,Mundargi,Mundgod,Munirabad,Mysore,Nagamangala,Nanjangud,Narasimharajapura,Naregal,Nargund,Navalgund,Nipani,Pandavapura,Pavagada,Piriyapatna,Pudu,Puttur,Rabkavi,Raichur,Ramanagaram,Ramdurg,Ranibennur,Raybag,Robertson,Ron,Sadalgi,Sagar,Sakleshpur,Saligram,Sandur,Sankeshwar,Saundatti,Savanur,Sedam,Shahabad,Shahpur,Shaktinagar,Shiggaon,Shikarpur,Shirhatti,Shorapur,Shrirangapattana,Siddapur,Sidlaghatta,Sindgi,Sindhnur,Sira,Siralkoppa,Sirsi,Siruguppa,Somvarpet,Sorab,Sringeri,Srinivaspur,Sulya,Talikota,Tarikere,Tekkalakote,Terdal,Thumbe,Tiptur,Tirthahalli,Tirumakudal,Tumkur,Turuvekere,Udupi,Vijayapura,Wadi,Yadgir,Yelandur,Yelbarga,Yellapur,Yenagudde"},
|
||||
{name: "Quechua", i: 27, min: 6, max: 12, d: "l", m: 0, b: "Alpahuaycco,Anchihuay,Anqea,Apurimac,Arequipa,Atahuallpa,Atawalpa,Atico,Ayacucho,Ayahuanco,Ayllu,Cajamarca,Canayre,Canchacancha,Carhuac,Carhuacatac,Cashan,Caullaraju,Caxamalca,Cayesh,Ccahuasno,Ccarhuacc,Ccopayoc,Chacchapunta,Chacraraju,Challhuamayo,Champara,Chanchan,Chekiacraju,Chillihua,Chinchey,Chontah,Chopicalqui,Chucuito,Chuito,Chullo,Chumpi,Chuncho,Chupahuacho,Chuquiapo,Chuquisaca,Churup,Cocapata,Cochabamba,Cojup,Collota,Conococha,Corihuayrachina,Cuchoquesera,Cusichaca,Haika,Hanpiq,Hatun,Haywarisqa,Huaca,Huachinga,Hualcan,Hualchancca,Huamanga,Huamashraju,Huancarhuas,Huandoy,Huantsan,Huanupampa,Huarmihuanusca,Huascaran,Huaylas,Huayllabamba,Huayrana,Huaytara,Huichajanca,Huinayhuayna,Huinche,Huinioch,Illiasca,Intipunku,Iquicha,Ishinca,Jahuacocha,Jirishanca,Juli,Jurau,Kakananpunta,Kamasqa,Karpay,Kausay,Khuya,Kuelap,Lanccochayocc,Llaca,Llactapata,Llanganuco,Llaqta,Lloqllasca,Llupachayoc,Luricocha,Machu,Mallku,Matarraju,Mechecc,Mikhuy,Milluacocha,Morochuco,Munay,Ocshapalca,Ollantaytambo,Oroccahua,Oronccoy,Oyolo,Pacamayo,Pacaycasa.Carapo,Paccharaju,Pachacamac,Pachakamaq,Pachakuteq,Pachakuti,Pachamama,Paititi,Pajaten,Palcaraju,Pallccas,Pampa,Panaka,Paqarina,Paqo,Parap,Paria,Patahuasi,Patallacta,Patibamba,Pisac,Pisco,Pongos,Pucacolpa,Pucahirca,Pucaranra,Pumatambo,Puscanturpa,Putaca,Puyupatamarca,Qawaq,Qayqa,Qochamoqo,Qollana,Qorihuayrachina,Qorimoqo,Qotupuquio,Quenuaracra,Queshque,Quillcayhuanca,Quillya,Quitaracsa,Quitaraju,Qusqu,Rajucolta,Rajutakanan,Rajutuna,Ranrahirca,Ranrapalca,Raria,Rasac,Rimarima,Riobamba,Runkuracay,Rurec,Sacsa,Sacsamarca,Saiwa,Sarapo,Sayacmarca,Sayripata,Sinakara,Sonccopa,Taripaypacha,Taulliraju,Tawantinsuyu,Taytanchis,Tiwanaku,Tocllaraju,Tsacra,Tuco,Tucubamba,Tullparaju,Tumbes,Uchuraccay,Uchuraqay,Ulta,Urihuana,Uruashraju,Vallunaraju,Vilcabamba,Wacho,Wankawillka,Wayra,Yachay,Yahuarraju,Yanamarey,Yanaqucha,Yanesha,Yerupaja"},
|
||||
{name: "Quechua", i: 27, min: 6, max: 12, d: "l", m: 0, b: "Alpahuaycco,Anchihuay,Anqea,Apurimac,Arequipa,Atahuallpa,Atawalpa,Atico,Ayacucho,Ayahuanco,Ayllu,Cajamarca,Canayre,Canchacancha,Carapo,Carhuac,Carhuacatac,Cashan,Caullaraju,Caxamalca,Cayesh,Ccahuasno,Ccarhuacc,Ccopayoc,Chacchapunta,Chacraraju,Challhuamayo,Champara,Chanchan,Chekiacraju,Chillihua,Chinchey,Chontah,Chopicalqui,Chucuito,Chuito,Chullo,Chumpi,Chuncho,Chupahuacho,Chuquiapo,Chuquisaca,Churup,Cocapata,Cochabamba,Cojup,Collota,Conococha,Corihuayrachina,Cuchoquesera,Cusichaca,Haika,Hanpiq,Hatun,Haywarisqa,Huaca,Huachinga,Hualcan,Hualchancca,Huamanga,Huamashraju,Huancarhuas,Huandoy,Huantsan,Huanupampa,Huarmihuanusca,Huascaran,Huaylas,Huayllabamba,Huayrana,Huaytara,Huichajanca,Huinayhuayna,Huinche,Huinioch,Illiasca,Intipunku,Iquicha,Ishinca,Jahuacocha,Jirishanca,Juli,Jurau,Kakananpunta,Kamasqa,Karpay,Kausay,Khuya,Kuelap,Lanccochayocc,Llaca,Llactapata,Llanganuco,Llaqta,Lloqllasca,Llupachayoc,Luricocha,Machu,Mallku,Matarraju,Mechecc,Mikhuy,Milluacocha,Morochuco,Munay,Ocshapalca,Ollantaytambo,Oroccahua,Oronccoy,Oyolo,Pacamayo,Pacaycasa,Paccharaju,Pachacamac,Pachakamaq,Pachakuteq,Pachakuti,Pachamama,Paititi,Pajaten,Palcaraju,Pallccas,Pampa,Panaka,Paqarina,Paqo,Parap,Paria,Patahuasi,Patallacta,Patibamba,Pisac,Pisco,Pongos,Pucacolpa,Pucahirca,Pucaranra,Pumatambo,Puscanturpa,Putaca,Puyupatamarca,Qawaq,Qayqa,Qochamoqo,Qollana,Qorihuayrachina,Qorimoqo,Qotupuquio,Quenuaracra,Queshque,Quillcayhuanca,Quillya,Quitaracsa,Quitaraju,Qusqu,Rajucolta,Rajutakanan,Rajutuna,Ranrahirca,Ranrapalca,Raria,Rasac,Rimarima,Riobamba,Runkuracay,Rurec,Sacsa,Sacsamarca,Saiwa,Sarapo,Sayacmarca,Sayripata,Sinakara,Sonccopa,Taripaypacha,Taulliraju,Tawantinsuyu,Taytanchis,Tiwanaku,Tocllaraju,Tsacra,Tuco,Tucubamba,Tullparaju,Tumbes,Uchuraccay,Uchuraqay,Ulta,Urihuana,Uruashraju,Vallunaraju,Vilcabamba,Wacho,Wankawillka,Wayra,Yachay,Yahuarraju,Yanamarey,Yanaqucha,Yanesha,Yerupaja"},
|
||||
{name: "Swahili", i: 28, min: 4, max: 9, d: "", m: 0, b: "Abim,Adjumani,Alebtong,Amolatar,Amuru,Apac,Arua,Arusha,Babati,Baragoi,Bombo,Budaka,Bugembe,Bugiri,Buikwe,Bukedea,Bukoba,Bukomansimbi,Bukungu,Buliisa,Bundibugyo,Bungoma,Busembatya,Bushenyi,Busia,Busolwe,Butaleja,Butambala,Butere,Buwenge,Buyende,Dadaab,Dodoma,Dokolo,Eldoret,Elegu,Emali,Embu,Entebbe,Garissa,Gede,Gulu,Handeni,Hima,Hoima,Hola,Ibanda,Iganga,Iringa,Isingiro,Isiolo,Jinja,Kaabong,Kabuyanda,Kabwohe,Kagadi,Kajiado,Kakinga,Kakiri,Kakuma,Kalangala,Kaliro,Kalongo,Kalungu,Kampala,Kamwenge,Kanungu,Kapchorwa,Kasese,Kasulu,Katakwi,Kayunga,Keroka,Kiambu,Kibaale,Kibaha,Kibingo,Kibwezi,Kigoma,Kihiihi,Kilifi,Kiruhura,Kiryandongo,Kisii,Kisoro,Kisumu,Kitale,Kitgum,Kitui,Koboko,Korogwe,Kotido,Kumi,Kyazanga,Kyegegwa,Kyenjojo,Kyotera,Lamu,Langata,Lindi,Lodwar,Lokichoggio,Londiani,Loyangalani,Lugazi,Lukaya,Luweero,Lwakhakha,Lwengo,Lyantonde,Machakos,Mafinga,Makambako,Makindu,Malaba,Malindi,Manafwa,Mandera,Marsabit,Masaka,Masindi,Masulita,Matugga,Mayuge,Mbale,Mbarara,Mbeya,Meru,Mitooma,Mityana,Mombasa,Morogoro,Moroto,Moyale,Moyo,Mpanda,Mpigi,Mpondwe,Mtwara,Mubende,Mukono,Muranga,Musoma,Mutomo,Mutukula,Mwanza,Nagongera,Nairobi,Naivasha,Nakapiripirit,Nakaseke,Nakasongola,Nakuru,Namanga,Namayingo,Namutumba,Nansana,Nanyuki,Narok,Naromoru,Nebbi,Ngora,Njeru,Njombe,Nkokonjeru,Ntungamo,Nyahururu,Nyeri,Oyam,Pader,Paidha,Pakwach,Pallisa,Rakai,Ruiru,Rukungiri,Rwimi,Sanga,Sembabule,Shimoni,Shinyanga,Singida,Sironko,Songea,Soroti,Ssabagabo,Sumbawanga,Tabora,Takaungu,Tanga,Thika,Tororo,Tunduma,Vihiga,Voi,Wajir,Wakiso,Watamu,Webuye,Wobulenzi,Wote,Wundanyi,Yumbe,Zanzibar"},
|
||||
{name: "Vietnamese", i: 29, min: 3, max: 12, d: "", m: 1, b: "An Giang,Anh Son,An Khe,An Nhon,Ayun Pa,Bac Giang,Bac Kan,Bac Lieu,Bac Ninh,Ba Don,Bao Loc,Ba Ria,Ba Ria-Vung Tau,Ba Thuoc,Ben Cat,Ben Tre,Bien Hoa,Bim Son,Binh Dinh,Binh Duong,Binh Long,Binh Minh,Binh Phuoc,Binh Thuan,Buon Ho,Buon Ma Thuot,Cai Lay,Ca Mau,Cam Khe,Cam Pha,Cam Ranh,Cam Thuy,Can Tho,Cao Bang,Cao Lanh,Cao Phong,Chau Doc,Chi Linh,Con Cuong,Cua Lo,Da Bac,Dak Lak,Da Lat,Da Nang,Di An,Dien Ban,Dien Bien,Dien Bien Phu,Dien Chau,Do Luong,Dong Ha,Dong Hoi,Dong Trieu,Duc Pho,Duyen Hai,Duy Tien,Gia Lai,Gia Nghia,Gia Rai,Go Cong,Ha Giang,Ha Hoa,Hai Duong,Hai Phong,Ha Long,Ha Nam,Ha Noi,Ha Tinh,Ha Trung,Hau Giang,Hoa Binh,Hoang Mai,Hoa Thanh,Ho Chi Minh,Hoi An,Hong Linh,Hong Ngu,Hue,Hung Nguyen,Hung Yen,Huong Thuy,Huong Tra,Khanh Hoa,Kien Tuong,Kim Boi,Kinh Mon,Kon Tum,Ky Anh,Ky Son,Lac Son,Lac Thuy,La Gi,Lai Chau,Lam Thao,Lang Chanh,Lang Son,Lao Cai,Long An,Long Khanh,Long My,Long Xuyen,Luong Son,Mai Chau,Mong Cai,Muong Lat,Muong Lay,My Hao,My Tho,Nam Dan,Nam Dinh,Nga Bay,Nga Nam,Nga Son,Nghe An,Nghia Dan,Nghia Lo,Nghi Loc,Nghi Son,Ngoc Lac,Nha Trang,Nhu Thanh,Nhu Xuan,Ninh Binh,Ninh Hoa,Nong Cong,Phan Rang Thap Cham,Phan Thiet,Pho Yen,Phu Ly,Phu My,Phu Ninh,Phuoc Long,Phu Tho,Phu Yen,Pleiku,Quang Binh,Quang Nam,Quang Ngai,Quang Ninh,Quang Tri,Quang Xuong,Quang Yen,Quan Hoa,Quan Son,Que Phong,Quy Chau,Quy Hop,Quynh Luu,Quy Nhon,Rach Gia,Sa Dec,Sai Gon,Sam Son,Sa Pa,Soc Trang,Song Cau,Song Cong,Son La,Son Tay,Tam Diep,Tam Ky,Tan An,Tan Chau,Tan Ky,Tan Lac,Tan Son,Tan Uyen,Tay Ninh,Thach Thanh,Thai Binh,Thai Hoa,Thai Nguyen,Thanh Chuong,Thanh Hoa,Thieu Hoa,Thuan An,Thua Thien-Hue,Thu Dau Mot,Thu Duc,Thuong Xuan,Tien Giang,Trang Bang,Tra Vinh,Trieu Son,Tu Son,Tuyen Quang,Tuy Hoa,Uong Bi,Viet Tri,Vinh,Vinh Chau,Vinh Loc,Vinh Long,Vinh Yen,Vi Thanh,Vung Tau,Yen Bai,Yen Dinh,Yen Thanh,Yen Thuy"},
|
||||
{name: "Cantonese", i: 30, min: 5, max: 11, d: "", m: 0, b: "Chaiwan,Chingchung,Chinghoi,Chingsen,Chingshing,Chiunam,Chiuon,Chiuyeung,Chiyuen,Choihung,Chuehoi,Chuiman,Chungfu,Chungsan,Chunguktsuen,Dakhing,Daopo,Daumun,Dingwu,Dinpak,Donggun,Dongyuen,Duenchau,Fachau,Fanling,Fatgong,Fatshan,Fotan,Fuktien,Fumun,Funggong,Funghoi,Fungshun,Fungtei,Gamtin,Gochau,Goming,Gonghoi,Gongshing,Goyiu,Hanghau,Hangmei,Hengon,Heungchau,Heunggong,Heungkiu,Hingning,Hohfuktong,Hoichue,Hoifung,Hoiping,Hokong,Hokshan,Hoyuen,Hunghom,Hungshuikiu,Jiuling,Kamsheung,Kamwan,Kaulongtong,Keilun,Kinon,Kinsang,Kityeung,Kongmun,Kukgong,Kwaifong,Kwaihing,Kwongchau,Kwongling,Kwongming,Kwuntong,Laichikok,Laiking,Laiwan,Lamtei,Lamtin,Leitung,Leungking,Limkong,Linping,Linshan,Loding,Lokcheong,Lokfu,Longchuen,Longgong,Longmun,Longping,Longwa,Longwu,Lowu,Luichau,Lukfung,Lukho,Lungmun,Macheung,Maliushui,Maonshan,Mauming,Maunam,Meifoo,Mingkum,Mogong,Mongkok,Muichau,Muigong,Muiyuen,Naiwai,Namcheong,Namhoi,Namhong,Namsha,Nganwai,Ngautaukok,Ngchuen,Ngwa,Onting,Pakwun,Paotoishan,Pingshan,Pingyuen,Poklo,Pongon,Poning,Potau,Puito,Punyue,Saiwanho,Saiyingpun,Samshing,Samshui,Samtsen,Samyuenlei,Sanfung,Sanhing,Sanhui,Sanwai,Seiwui,Shamshuipo,Shanmei,Shantau,Shauking,Shekmun,Shekpai,Sheungshui,Shingkui,Shiuhing,Shundak,Shunyi,Shupinwai,Simshing,Siuhei,Siuhong,Siukwan,Siulun,Suikai,Taihing,Taikoo,Taipo,Taishuihang,Taiwai,Taiwohau,Tinhau,Tinshuiwai,Tiukengleng,Toishan,Tongfong,Tonglowan,Tsakyoochung,Tsamgong,Tsangshing,Tseungkwano,Tsimshatsui,Tsinggong,Tsingshantsuen,Tsingwun,Tsingyi,Tsingyuen,Tsiuchau,Tsuenshekshan,Tsuenwan,Tuenmun,Tungchung,Waichap,Waichau,Waidong,Wailoi,Waishing,Waiyeung,Wanchai,Wanfau,Wanshing,Wingon,Wongpo,Wongtaisin,Woping,Wukaisha,Yano,Yaumatei,Yautong,Yenfa,Yeungchun,Yeungdong,Yeungsai,Yeungshan,Yimtin,Yingdak,Yiuping,Yongshing,Yongyuen,Yuenlong,Yuenshing,Yuetsau,Yuknam,Yunping"},
|
||||
|
|
|
|||
|
|
@ -692,7 +692,7 @@ window.Religions = (function () {
|
|||
|
||||
// growth algorithm to assign cells to religions
|
||||
function expandReligions(religions) {
|
||||
const cells = pack.cells;
|
||||
const {cells, routes} = pack;
|
||||
const religionIds = spreadFolkReligions(religions);
|
||||
|
||||
const queue = new PriorityQueue({comparator: (a, b) => a.p - b.p});
|
||||
|
|
@ -700,8 +700,6 @@ window.Religions = (function () {
|
|||
|
||||
const maxExpansionCost = (cells.i.length / 20) * neutralInput.value; // limit cost for organized religions growth
|
||||
|
||||
const biomePassageCost = cellId => biomesData.cost[cells.biome[cellId]];
|
||||
|
||||
religions
|
||||
.filter(r => r.i && !r.lock && r.type !== "Folk" && !r.removed)
|
||||
.forEach(r => {
|
||||
|
|
@ -712,11 +710,6 @@ window.Religions = (function () {
|
|||
|
||||
const religionsMap = new Map(religions.map(r => [r.i, r]));
|
||||
|
||||
const isMainRoad = cellId => cells.road[cellId] - cells.crossroad[cellId] > 4;
|
||||
const isTrail = cellId => cells.h[cellId] > 19 && cells.road[cellId] - cells.crossroad[cellId] === 1;
|
||||
const isSeaRoute = cellId => cells.h[cellId] < 20 && cells.road[cellId];
|
||||
const isWater = cellId => cells.h[cellId] < 20;
|
||||
|
||||
while (queue.length) {
|
||||
const {e: cellId, p, r, s: state} = queue.dequeue();
|
||||
const {culture, expansion, expansionism} = religionsMap.get(r);
|
||||
|
|
@ -728,7 +721,7 @@ window.Religions = (function () {
|
|||
|
||||
const cultureCost = culture !== cells.culture[nextCell] ? 10 : 0;
|
||||
const stateCost = state !== cells.state[nextCell] ? 10 : 0;
|
||||
const passageCost = getPassageCost(nextCell);
|
||||
const passageCost = getPassageCost(cellId, nextCell);
|
||||
|
||||
const cellCost = cultureCost + stateCost + passageCost;
|
||||
const totalCost = p + 10 + cellCost / expansionism;
|
||||
|
|
@ -745,11 +738,18 @@ window.Religions = (function () {
|
|||
|
||||
return religionIds;
|
||||
|
||||
function getPassageCost(cellId) {
|
||||
if (isWater(cellId)) return isSeaRoute ? 50 : 500;
|
||||
if (isMainRoad(cellId)) return 1;
|
||||
const biomeCost = biomePassageCost(cellId);
|
||||
return isTrail(cellId) ? biomeCost / 1.5 : biomeCost;
|
||||
function getPassageCost(cellId, nextCellId) {
|
||||
const route = Routes.getRoute(cellId, nextCellId);
|
||||
if (isWater(cellId)) return route ? 50 : 500;
|
||||
|
||||
const biomePassageCost = biomesData.cost[cells.biome[nextCellId]];
|
||||
|
||||
if (route) {
|
||||
if (route.group === "roads") return 1;
|
||||
return biomePassageCost / 3; // trails and other routes
|
||||
}
|
||||
|
||||
return biomePassageCost;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -4,6 +4,10 @@
|
|||
function drawStateLabels(list) {
|
||||
console.time("drawStateLabels");
|
||||
|
||||
// temporary make the labels visible
|
||||
const layerDisplay = labels.style("display");
|
||||
labels.style("display", null);
|
||||
|
||||
const {cells, states, features} = pack;
|
||||
const stateIds = cells.state;
|
||||
|
||||
|
|
@ -17,7 +21,11 @@ function drawStateLabels(list) {
|
|||
const MAX_ITERATIONS = 100;
|
||||
|
||||
const labelPaths = getLabelPaths();
|
||||
drawLabelPath();
|
||||
const letterLength = checkExampleLetterLength();
|
||||
drawLabelPath(letterLength);
|
||||
|
||||
// restore labels visibility
|
||||
labels.style("display", layerDisplay);
|
||||
|
||||
function getLabelPaths() {
|
||||
const labelPaths = [];
|
||||
|
|
@ -110,17 +118,22 @@ function drawStateLabels(list) {
|
|||
}
|
||||
}
|
||||
|
||||
function drawLabelPath() {
|
||||
function checkExampleLetterLength() {
|
||||
const textGroup = d3.select("g#labels > g#states");
|
||||
const testLabel = textGroup.append("text").attr("x", 0).attr("y", 0).text("Example");
|
||||
const letterLength = testLabel.node().getComputedTextLength() / 7; // approximate length of 1 letter
|
||||
testLabel.remove();
|
||||
|
||||
return letterLength;
|
||||
}
|
||||
|
||||
function drawLabelPath(letterLength) {
|
||||
const mode = options.stateLabelsMode || "auto";
|
||||
const lineGen = d3.line().curve(d3.curveBundle.beta(1));
|
||||
|
||||
const textGroup = d3.select("g#labels > g#states");
|
||||
const pathGroup = d3.select("defs > g#deftemp > g#textPaths");
|
||||
|
||||
const testLabel = textGroup.append("text").attr("x", 0).attr("y", 0).text("Example");
|
||||
const letterLength = testLabel.node().getComputedTextLength() / 7; // approximate length of 1 letter
|
||||
testLabel.remove();
|
||||
|
||||
for (const [stateId, pathPoints] of labelPaths) {
|
||||
const state = states[stateId];
|
||||
if (!state.i || state.removed) throw new Error("State must not be neutral or removed");
|
||||
|
|
|
|||
|
|
@ -1,269 +1,748 @@
|
|||
const ROUTES_SHARP_ANGLE = 135;
|
||||
const ROUTES_VERY_SHARP_ANGLE = 115;
|
||||
|
||||
window.Routes = (function () {
|
||||
const getRoads = function () {
|
||||
TIME && console.time("generateMainRoads");
|
||||
const cells = pack.cells;
|
||||
const burgs = pack.burgs.filter(b => b.i && !b.removed);
|
||||
const capitals = burgs.filter(b => b.capital).sort((a, b) => a.population - b.population);
|
||||
function generate(lockedRoutes = []) {
|
||||
const {capitalsByFeature, burgsByFeature, portsByFeature} = sortBurgsByFeature(pack.burgs);
|
||||
|
||||
if (capitals.length < 2) return []; // not enough capitals to build main roads
|
||||
const paths = []; // array to store path segments
|
||||
const connections = new Map();
|
||||
lockedRoutes.forEach(route => addConnections(route.points.map(p => p[2])));
|
||||
|
||||
for (const b of capitals) {
|
||||
const connect = capitals.filter(c => c.feature === b.feature && c !== b);
|
||||
for (const t of connect) {
|
||||
const [from, exit] = findLandPath(b.cell, t.cell, true);
|
||||
const segments = restorePath(b.cell, exit, "main", from);
|
||||
segments.forEach(s => paths.push(s));
|
||||
}
|
||||
}
|
||||
const mainRoads = generateMainRoads();
|
||||
const trails = generateTrails();
|
||||
const seaRoutes = generateSeaRoutes();
|
||||
|
||||
cells.i.forEach(i => (cells.s[i] += cells.road[i] / 2)); // add roads to suitability score
|
||||
TIME && console.timeEnd("generateMainRoads");
|
||||
return paths;
|
||||
};
|
||||
pack.routes = createRoutesData(lockedRoutes);
|
||||
pack.cells.routes = buildLinks(pack.routes);
|
||||
|
||||
const getTrails = function () {
|
||||
TIME && console.time("generateTrails");
|
||||
const cells = pack.cells;
|
||||
const burgs = pack.burgs.filter(b => b.i && !b.removed);
|
||||
function sortBurgsByFeature(burgs) {
|
||||
const burgsByFeature = {};
|
||||
const capitalsByFeature = {};
|
||||
const portsByFeature = {};
|
||||
|
||||
if (burgs.length < 2) return []; // not enough burgs to build trails
|
||||
const addBurg = (object, feature, burg) => {
|
||||
if (!object[feature]) object[feature] = [];
|
||||
object[feature].push(burg);
|
||||
};
|
||||
|
||||
let paths = []; // array to store path segments
|
||||
for (const f of pack.features.filter(f => f.land)) {
|
||||
const isle = burgs.filter(b => b.feature === f.i); // burgs on island
|
||||
if (isle.length < 2) continue;
|
||||
|
||||
isle.forEach(function (b, i) {
|
||||
let path = [];
|
||||
if (!i) {
|
||||
// build trail from the first burg on island
|
||||
// to the farthest one on the same island or the closest road
|
||||
const farthest = d3.scan(isle, (a, c) => (c.y - b.y) ** 2 + (c.x - b.x) ** 2 - ((a.y - b.y) ** 2 + (a.x - b.x) ** 2));
|
||||
const to = isle[farthest].cell;
|
||||
if (cells.road[to]) return;
|
||||
const [from, exit] = findLandPath(b.cell, to, true);
|
||||
path = restorePath(b.cell, exit, "small", from);
|
||||
} else {
|
||||
// build trail from all other burgs to the closest road on the same island
|
||||
if (cells.road[b.cell]) return;
|
||||
const [from, exit] = findLandPath(b.cell, null, true);
|
||||
if (exit === null) return;
|
||||
path = restorePath(b.cell, exit, "small", from);
|
||||
}
|
||||
if (path) paths = paths.concat(path);
|
||||
});
|
||||
}
|
||||
|
||||
TIME && console.timeEnd("generateTrails");
|
||||
return paths;
|
||||
};
|
||||
|
||||
const getSearoutes = function () {
|
||||
TIME && console.time("generateSearoutes");
|
||||
const {cells, burgs, features} = pack;
|
||||
const allPorts = burgs.filter(b => b.port > 0 && !b.removed);
|
||||
|
||||
if (!allPorts.length) return [];
|
||||
|
||||
const bodies = new Set(allPorts.map(b => b.port)); // water features with ports
|
||||
let paths = []; // array to store path segments
|
||||
const connected = []; // store cell id of connected burgs
|
||||
|
||||
bodies.forEach(f => {
|
||||
const ports = allPorts.filter(b => b.port === f); // all ports on the same feature
|
||||
if (!ports.length) return;
|
||||
|
||||
if (features[f]?.border) addOverseaRoute(f, ports[0]);
|
||||
|
||||
// get inner-map routes
|
||||
for (let s = 0; s < ports.length; s++) {
|
||||
const source = ports[s].cell;
|
||||
if (connected[source]) continue;
|
||||
|
||||
for (let t = s + 1; t < ports.length; t++) {
|
||||
const target = ports[t].cell;
|
||||
if (connected[target]) continue;
|
||||
|
||||
const [from, exit, passable] = findOceanPath(target, source, true);
|
||||
if (!passable) continue;
|
||||
|
||||
const path = restorePath(target, exit, "ocean", from);
|
||||
paths = paths.concat(path);
|
||||
|
||||
connected[source] = 1;
|
||||
connected[target] = 1;
|
||||
for (const burg of burgs) {
|
||||
if (burg.i && !burg.removed) {
|
||||
const {feature, capital, port} = burg;
|
||||
addBurg(burgsByFeature, feature, burg);
|
||||
if (capital) addBurg(capitalsByFeature, feature, burg);
|
||||
if (port) addBurg(portsByFeature, port, burg);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function addOverseaRoute(f, port) {
|
||||
const {x, y, cell: source} = port;
|
||||
const dist = p => Math.abs(p[0] - x) + Math.abs(p[1] - y);
|
||||
const [x1, y1] = [
|
||||
[0, y],
|
||||
[x, 0],
|
||||
[graphWidth, y],
|
||||
[x, graphHeight]
|
||||
].sort((a, b) => dist(a) - dist(b))[0];
|
||||
const target = findCell(x1, y1);
|
||||
return {burgsByFeature, capitalsByFeature, portsByFeature};
|
||||
}
|
||||
|
||||
if (cells.f[target] === f && cells.h[target] < 20) {
|
||||
const [from, exit, passable] = findOceanPath(target, source, true);
|
||||
function generateMainRoads() {
|
||||
TIME && console.time("generateMainRoads");
|
||||
const mainRoads = [];
|
||||
|
||||
if (passable) {
|
||||
const path = restorePath(target, exit, "ocean", from);
|
||||
paths = paths.concat(path);
|
||||
last(path).push([x1, y1]);
|
||||
for (const [key, featureCapitals] of Object.entries(capitalsByFeature)) {
|
||||
const points = featureCapitals.map(burg => [burg.x, burg.y]);
|
||||
const urquhartEdges = calculateUrquhartEdges(points);
|
||||
urquhartEdges.forEach(([fromId, toId]) => {
|
||||
const start = featureCapitals[fromId].cell;
|
||||
const exit = featureCapitals[toId].cell;
|
||||
|
||||
const segments = findPathSegments({isWater: false, connections, start, exit});
|
||||
for (const segment of segments) {
|
||||
addConnections(segment);
|
||||
mainRoads.push({feature: Number(key), cells: segment});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
TIME && console.timeEnd("generateMainRoads");
|
||||
return mainRoads;
|
||||
}
|
||||
|
||||
function generateTrails() {
|
||||
TIME && console.time("generateTrails");
|
||||
const trails = [];
|
||||
|
||||
for (const [key, featureBurgs] of Object.entries(burgsByFeature)) {
|
||||
const points = featureBurgs.map(burg => [burg.x, burg.y]);
|
||||
const urquhartEdges = calculateUrquhartEdges(points);
|
||||
urquhartEdges.forEach(([fromId, toId]) => {
|
||||
const start = featureBurgs[fromId].cell;
|
||||
const exit = featureBurgs[toId].cell;
|
||||
|
||||
const segments = findPathSegments({isWater: false, connections, start, exit});
|
||||
for (const segment of segments) {
|
||||
addConnections(segment);
|
||||
trails.push({feature: Number(key), cells: segment});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
TIME && console.timeEnd("generateTrails");
|
||||
return trails;
|
||||
}
|
||||
|
||||
function generateSeaRoutes() {
|
||||
TIME && console.time("generateSeaRoutes");
|
||||
const seaRoutes = [];
|
||||
|
||||
for (const [featureId, featurePorts] of Object.entries(portsByFeature)) {
|
||||
const points = featurePorts.map(burg => [burg.x, burg.y]);
|
||||
const urquhartEdges = calculateUrquhartEdges(points);
|
||||
|
||||
urquhartEdges.forEach(([fromId, toId]) => {
|
||||
const start = featurePorts[fromId].cell;
|
||||
const exit = featurePorts[toId].cell;
|
||||
const segments = findPathSegments({isWater: true, connections, start, exit});
|
||||
for (const segment of segments) {
|
||||
addConnections(segment);
|
||||
seaRoutes.push({feature: Number(featureId), cells: segment});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
TIME && console.timeEnd("generateSeaRoutes");
|
||||
return seaRoutes;
|
||||
}
|
||||
|
||||
function addConnections(segment) {
|
||||
for (let i = 0; i < segment.length; i++) {
|
||||
const cellId = segment[i];
|
||||
const nextCellId = segment[i + 1];
|
||||
if (nextCellId) {
|
||||
connections.set(`${cellId}-${nextCellId}`, true);
|
||||
connections.set(`${nextCellId}-${cellId}`, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TIME && console.timeEnd("generateSearoutes");
|
||||
return paths;
|
||||
};
|
||||
function findPathSegments({isWater, connections, start, exit}) {
|
||||
const from = findPath(isWater, start, exit, connections);
|
||||
if (!from) return [];
|
||||
|
||||
const draw = function (main, small, water) {
|
||||
TIME && console.time("drawRoutes");
|
||||
const {cells, burgs} = pack;
|
||||
const {burg, p} = cells;
|
||||
|
||||
const getBurgCoords = b => [burgs[b].x, burgs[b].y];
|
||||
const getPathPoints = cells => cells.map(i => (Array.isArray(i) ? i : burg[i] ? getBurgCoords(burg[i]) : p[i]));
|
||||
const getPath = segment => round(lineGen(getPathPoints(segment)), 1);
|
||||
const getPathsHTML = (paths, type) => paths.map((path, i) => `<path id="${type}${i}" d="${getPath(path)}" />`).join("");
|
||||
|
||||
lineGen.curve(d3.curveCatmullRom.alpha(0.1));
|
||||
roads.html(getPathsHTML(main, "road"));
|
||||
trails.html(getPathsHTML(small, "trail"));
|
||||
|
||||
lineGen.curve(d3.curveBundle.beta(1));
|
||||
searoutes.html(getPathsHTML(water, "searoute"));
|
||||
|
||||
TIME && console.timeEnd("drawRoutes");
|
||||
};
|
||||
|
||||
const regenerate = function () {
|
||||
routes.selectAll("path").remove();
|
||||
pack.cells.road = new Uint16Array(pack.cells.i.length);
|
||||
pack.cells.crossroad = new Uint16Array(pack.cells.i.length);
|
||||
const main = getRoads();
|
||||
const small = getTrails();
|
||||
const water = getSearoutes();
|
||||
draw(main, small, water);
|
||||
};
|
||||
|
||||
return {getRoads, getTrails, getSearoutes, draw, regenerate};
|
||||
|
||||
// Find a land path to a specific cell (exit), to a closest road (toRoad), or to all reachable cells (null, null)
|
||||
function findLandPath(start, exit = null, toRoad = null) {
|
||||
const cells = pack.cells;
|
||||
const queue = new PriorityQueue({comparator: (a, b) => a.p - b.p});
|
||||
const cost = [],
|
||||
from = [];
|
||||
queue.queue({e: start, p: 0});
|
||||
|
||||
while (queue.length) {
|
||||
const next = queue.dequeue(),
|
||||
n = next.e,
|
||||
p = next.p;
|
||||
if (toRoad && cells.road[n]) return [from, n];
|
||||
|
||||
for (const c of cells.c[n]) {
|
||||
if (cells.h[c] < 20) continue; // ignore water cells
|
||||
const stateChangeCost = cells.state && cells.state[c] !== cells.state[n] ? 400 : 0; // trails tend to lay within the same state
|
||||
const habitability = biomesData.habitability[cells.biome[c]];
|
||||
if (!habitability) continue; // avoid inhabitable cells (eg. lava, glacier)
|
||||
const habitedCost = habitability ? Math.max(100 - habitability, 0) : 400; // routes tend to lay within populated areas
|
||||
const heightChangeCost = Math.abs(cells.h[c] - cells.h[n]) * 10; // routes tend to avoid elevation changes
|
||||
const heightCost = cells.h[c] > 80 ? cells.h[c] : 0; // routes tend to avoid mountainous areas
|
||||
const cellCoast = 10 + stateChangeCost + habitedCost + heightChangeCost + heightCost;
|
||||
const totalCost = p + (cells.road[c] || cells.burg[c] ? cellCoast / 3 : cellCoast);
|
||||
|
||||
if (from[c] || totalCost >= cost[c]) continue;
|
||||
from[c] = n;
|
||||
if (c === exit) return [from, exit];
|
||||
cost[c] = totalCost;
|
||||
queue.queue({e: c, p: totalCost});
|
||||
}
|
||||
const pathCells = restorePath(start, exit, from);
|
||||
const segments = getRouteSegments(pathCells, connections);
|
||||
return segments;
|
||||
}
|
||||
|
||||
function createRoutesData(routes) {
|
||||
const pointsArray = preparePointsArray();
|
||||
|
||||
for (const {feature, cells, merged} of mergeRoutes(mainRoads)) {
|
||||
if (merged) continue;
|
||||
const points = getPoints("roads", cells, pointsArray);
|
||||
routes.push({i: routes.length, group: "roads", feature, points});
|
||||
}
|
||||
|
||||
for (const {feature, cells, merged} of mergeRoutes(trails)) {
|
||||
if (merged) continue;
|
||||
const points = getPoints("trails", cells, pointsArray);
|
||||
routes.push({i: routes.length, group: "trails", feature, points});
|
||||
}
|
||||
|
||||
for (const {feature, cells, merged} of mergeRoutes(seaRoutes)) {
|
||||
if (merged) continue;
|
||||
const points = getPoints("searoutes", cells, pointsArray);
|
||||
routes.push({i: routes.length, group: "searoutes", feature, points});
|
||||
}
|
||||
|
||||
return routes;
|
||||
}
|
||||
|
||||
// merge routes so that the last cell of one route is the first cell of the next route
|
||||
function mergeRoutes(routes) {
|
||||
let routesMerged = 0;
|
||||
|
||||
for (let i = 0; i < routes.length; i++) {
|
||||
const thisRoute = routes[i];
|
||||
if (thisRoute.merged) continue;
|
||||
|
||||
for (let j = i + 1; j < routes.length; j++) {
|
||||
const nextRoute = routes[j];
|
||||
if (nextRoute.merged) continue;
|
||||
|
||||
if (nextRoute.cells.at(0) === thisRoute.cells.at(-1)) {
|
||||
routesMerged++;
|
||||
thisRoute.cells = thisRoute.cells.concat(nextRoute.cells.slice(1));
|
||||
nextRoute.merged = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return routesMerged > 1 ? mergeRoutes(routes) : routes;
|
||||
}
|
||||
|
||||
function buildLinks(routes) {
|
||||
const links = {};
|
||||
|
||||
for (const {points, i: routeId} of routes) {
|
||||
const cells = points.map(p => p[2]);
|
||||
|
||||
for (let i = 0; i < cells.length - 1; i++) {
|
||||
const cellId = cells[i];
|
||||
const nextCellId = cells[i + 1];
|
||||
|
||||
if (cellId !== nextCellId) {
|
||||
if (!links[cellId]) links[cellId] = {};
|
||||
links[cellId][nextCellId] = routeId;
|
||||
|
||||
if (!links[nextCellId]) links[nextCellId] = {};
|
||||
links[nextCellId][cellId] = routeId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return links;
|
||||
}
|
||||
return [from, exit];
|
||||
}
|
||||
|
||||
function restorePath(start, end, type, from) {
|
||||
const cells = pack.cells;
|
||||
const path = []; // to store all segments;
|
||||
let segment = [],
|
||||
current = end,
|
||||
prev = end;
|
||||
const score = type === "main" ? 5 : 1; // to increase road score at cell
|
||||
function preparePointsArray() {
|
||||
const {cells, burgs} = pack;
|
||||
return cells.p.map(([x, y], cellId) => {
|
||||
const burgId = cells.burg[cellId];
|
||||
if (burgId) return [burgs[burgId].x, burgs[burgId].y];
|
||||
return [x, y];
|
||||
});
|
||||
}
|
||||
|
||||
if (type === "ocean" || !cells.road[prev]) segment.push(end);
|
||||
if (!cells.road[prev]) cells.road[prev] = score;
|
||||
function getPoints(group, cells, points) {
|
||||
const data = cells.map(cellId => [...points[cellId], cellId]);
|
||||
|
||||
for (let i = 0, limit = 1000; i < limit; i++) {
|
||||
if (!from[current]) break;
|
||||
current = from[current];
|
||||
// resolve sharp angles
|
||||
if (group !== "searoutes") {
|
||||
for (let i = 1; i < cells.length - 1; i++) {
|
||||
const cellId = cells[i];
|
||||
if (pack.cells.burg[cellId]) continue;
|
||||
|
||||
if (cells.road[current]) {
|
||||
if (segment.length) {
|
||||
segment.push(current);
|
||||
path.push(segment);
|
||||
if (segment[0] !== end) {
|
||||
cells.road[segment[0]] += score;
|
||||
cells.crossroad[segment[0]] += score;
|
||||
const [prevX, prevY] = data[i - 1];
|
||||
const [currX, currY] = data[i];
|
||||
const [nextX, nextY] = data[i + 1];
|
||||
|
||||
const dAx = prevX - currX;
|
||||
const dAy = prevY - currY;
|
||||
const dBx = nextX - currX;
|
||||
const dBy = nextY - currY;
|
||||
const angle = Math.abs((Math.atan2(dAx * dBy - dAy * dBx, dAx * dBx + dAy * dBy) * 180) / Math.PI);
|
||||
|
||||
if (angle < ROUTES_SHARP_ANGLE) {
|
||||
const middleX = (prevX + nextX) / 2;
|
||||
const middleY = (prevY + nextY) / 2;
|
||||
let newX, newY;
|
||||
|
||||
if (angle < ROUTES_VERY_SHARP_ANGLE) {
|
||||
newX = rn((currX + middleX * 2) / 3, 2);
|
||||
newY = rn((currY + middleY * 2) / 3, 2);
|
||||
} else {
|
||||
newX = rn((currX + middleX) / 2, 2);
|
||||
newY = rn((currY + middleY) / 2, 2);
|
||||
}
|
||||
if (current !== start) {
|
||||
cells.road[current] += score;
|
||||
cells.crossroad[current] += score;
|
||||
|
||||
if (findCell(newX, newY) === cellId) {
|
||||
data[i] = [newX, newY, cellId];
|
||||
points[cellId] = [data[i][0], data[i][1]]; // change cell coordinate for all routes
|
||||
}
|
||||
}
|
||||
segment = [];
|
||||
prev = current;
|
||||
} else {
|
||||
if (prev) segment.push(prev);
|
||||
prev = null;
|
||||
segment.push(current);
|
||||
}
|
||||
|
||||
cells.road[current] += score;
|
||||
if (current === start) break;
|
||||
}
|
||||
|
||||
if (segment.length > 1) path.push(segment);
|
||||
return data; // [[x, y, cell], [x, y, cell]];
|
||||
}
|
||||
|
||||
const MIN_PASSABLE_SEA_TEMP = -4;
|
||||
const TYPE_MODIFIERS = {
|
||||
"-1": 1, // coastline
|
||||
"-2": 1.8, // sea
|
||||
"-3": 4, // open sea
|
||||
"-4": 6, // ocean
|
||||
default: 8 // far ocean
|
||||
};
|
||||
|
||||
function findPath(isWater, start, exit, connections) {
|
||||
const {temp} = grid.cells;
|
||||
const {cells} = pack;
|
||||
|
||||
const from = [];
|
||||
const cost = [];
|
||||
const queue = new FlatQueue();
|
||||
queue.push(start, 0);
|
||||
|
||||
return isWater ? findWaterPath() : findLandPath();
|
||||
|
||||
function findLandPath() {
|
||||
while (queue.length) {
|
||||
const priority = queue.peekValue();
|
||||
const next = queue.pop();
|
||||
|
||||
for (const neibCellId of cells.c[next]) {
|
||||
if (neibCellId === exit) {
|
||||
from[neibCellId] = next;
|
||||
return from;
|
||||
}
|
||||
|
||||
if (cells.h[neibCellId] < 20) continue; // ignore water cells
|
||||
const habitability = biomesData.habitability[cells.biome[neibCellId]];
|
||||
if (!habitability) continue; // inhabitable cells are not passable (eg. lava, glacier)
|
||||
|
||||
const distanceCost = dist2(cells.p[next], cells.p[neibCellId]);
|
||||
const habitabilityModifier = 1 + Math.max(100 - habitability, 0) / 1000; // [1, 1.1];
|
||||
const heightModifier = 1 + Math.max(cells.h[neibCellId] - 25, 25) / 25; // [1, 3];
|
||||
const connectionModifier = connections.has(`${next}-${neibCellId}`) ? 1 : 2;
|
||||
const burgModifier = cells.burg[neibCellId] ? 1 : 3;
|
||||
|
||||
const cellsCost = distanceCost * habitabilityModifier * heightModifier * connectionModifier * burgModifier;
|
||||
const totalCost = priority + cellsCost;
|
||||
|
||||
if (totalCost >= cost[neibCellId]) continue;
|
||||
from[neibCellId] = next;
|
||||
cost[neibCellId] = totalCost;
|
||||
queue.push(neibCellId, totalCost);
|
||||
}
|
||||
}
|
||||
|
||||
return null; // path is not found
|
||||
}
|
||||
|
||||
function findWaterPath() {
|
||||
while (queue.length) {
|
||||
const priority = queue.peekValue();
|
||||
const next = queue.pop();
|
||||
|
||||
for (const neibCellId of cells.c[next]) {
|
||||
if (neibCellId === exit) {
|
||||
from[neibCellId] = next;
|
||||
return from;
|
||||
}
|
||||
|
||||
if (cells.h[neibCellId] >= 20) continue; // ignore land cells
|
||||
if (temp[cells.g[neibCellId]] < MIN_PASSABLE_SEA_TEMP) continue; // ignore too cold cells
|
||||
|
||||
const distanceCost = dist2(cells.p[next], cells.p[neibCellId]);
|
||||
const typeModifier = TYPE_MODIFIERS[cells.t[neibCellId]] || TYPE_MODIFIERS.default;
|
||||
const connectionModifier = connections.has(`${next}-${neibCellId}`) ? 1 : 2;
|
||||
|
||||
const cellsCost = distanceCost * typeModifier * connectionModifier;
|
||||
const totalCost = priority + cellsCost;
|
||||
|
||||
if (totalCost >= cost[neibCellId]) continue;
|
||||
from[neibCellId] = next;
|
||||
cost[neibCellId] = totalCost;
|
||||
queue.push(neibCellId, totalCost);
|
||||
}
|
||||
}
|
||||
|
||||
return null; // path is not found
|
||||
}
|
||||
}
|
||||
|
||||
function restorePath(start, end, from) {
|
||||
const cells = [];
|
||||
|
||||
let current = end;
|
||||
let prev = end;
|
||||
|
||||
while (current !== start) {
|
||||
cells.push(current);
|
||||
prev = from[current];
|
||||
current = prev;
|
||||
}
|
||||
|
||||
cells.push(current);
|
||||
|
||||
return cells;
|
||||
}
|
||||
|
||||
function getRouteSegments(pathCells, connections) {
|
||||
const segments = [];
|
||||
let segment = [];
|
||||
|
||||
for (let i = 0; i < pathCells.length; i++) {
|
||||
const cellId = pathCells[i];
|
||||
const nextCellId = pathCells[i + 1];
|
||||
const isConnected = connections.has(`${cellId}-${nextCellId}`) || connections.has(`${nextCellId}-${cellId}`);
|
||||
|
||||
if (isConnected) {
|
||||
if (segment.length) {
|
||||
// segment stepped into existing segment
|
||||
segment.push(pathCells[i]);
|
||||
segments.push(segment);
|
||||
segment = [];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
segment.push(pathCells[i]);
|
||||
}
|
||||
|
||||
if (segment.length > 1) segments.push(segment);
|
||||
|
||||
return segments;
|
||||
}
|
||||
|
||||
// Urquhart graph is obtained by removing the longest edge from each triangle in the Delaunay triangulation
|
||||
// this gives us an aproximation of a desired road network, i.e. connections between burgs
|
||||
// code from https://observablehq.com/@mbostock/urquhart-graph
|
||||
function calculateUrquhartEdges(points) {
|
||||
const score = (p0, p1) => dist2(points[p0], points[p1]);
|
||||
|
||||
const {halfedges, triangles} = Delaunator.from(points);
|
||||
const n = triangles.length;
|
||||
|
||||
const removed = new Uint8Array(n);
|
||||
const edges = [];
|
||||
|
||||
for (let e = 0; e < n; e += 3) {
|
||||
const p0 = triangles[e],
|
||||
p1 = triangles[e + 1],
|
||||
p2 = triangles[e + 2];
|
||||
|
||||
const p01 = score(p0, p1),
|
||||
p12 = score(p1, p2),
|
||||
p20 = score(p2, p0);
|
||||
|
||||
removed[
|
||||
p20 > p01 && p20 > p12
|
||||
? Math.max(e + 2, halfedges[e + 2])
|
||||
: p12 > p01 && p12 > p20
|
||||
? Math.max(e + 1, halfedges[e + 1])
|
||||
: Math.max(e, halfedges[e])
|
||||
] = 1;
|
||||
}
|
||||
|
||||
for (let e = 0; e < n; ++e) {
|
||||
if (e > halfedges[e] && !removed[e]) {
|
||||
const t0 = triangles[e];
|
||||
const t1 = triangles[e % 3 === 2 ? e - 2 : e + 1];
|
||||
edges.push([t0, t1]);
|
||||
}
|
||||
}
|
||||
|
||||
return edges;
|
||||
}
|
||||
|
||||
// connect cell with routes system by land
|
||||
function connect(cellId) {
|
||||
if (isConnected(cellId)) return;
|
||||
|
||||
const {cells, routes} = pack;
|
||||
|
||||
const path = findConnectionPath(cellId);
|
||||
if (!path) return;
|
||||
|
||||
const pathCells = restorePath(...path);
|
||||
const pointsArray = preparePointsArray();
|
||||
const points = getPoints("trails", pathCells, pointsArray);
|
||||
const feature = cells.f[cellId];
|
||||
|
||||
const routeId = getNextId();
|
||||
const newRoute = {i: routeId, group: "trails", feature, points};
|
||||
routes.push(newRoute);
|
||||
|
||||
for (let i = 0; i < pathCells.length; i++) {
|
||||
const cellId = pathCells[i];
|
||||
const nextCellId = pathCells[i + 1];
|
||||
if (nextCellId) addConnection(cellId, nextCellId, routeId);
|
||||
}
|
||||
|
||||
return newRoute;
|
||||
|
||||
function findConnectionPath(start) {
|
||||
const from = [];
|
||||
const cost = [];
|
||||
const queue = new FlatQueue();
|
||||
queue.push(start, 0);
|
||||
|
||||
while (queue.length) {
|
||||
const priority = queue.peekValue();
|
||||
const next = queue.pop();
|
||||
|
||||
for (const neibCellId of cells.c[next]) {
|
||||
if (isConnected(neibCellId)) {
|
||||
from[neibCellId] = next;
|
||||
return [start, neibCellId, from];
|
||||
}
|
||||
|
||||
if (cells.h[neibCellId] < 20) continue; // ignore water cells
|
||||
const habitability = biomesData.habitability[cells.biome[neibCellId]];
|
||||
if (!habitability) continue; // inhabitable cells are not passable (eg. lava, glacier)
|
||||
|
||||
const distanceCost = dist2(cells.p[next], cells.p[neibCellId]);
|
||||
const habitabilityModifier = 1 + Math.max(100 - habitability, 0) / 1000; // [1, 1.1];
|
||||
const heightModifier = 1 + Math.max(cells.h[neibCellId] - 25, 25) / 25; // [1, 3];
|
||||
|
||||
const cellsCost = distanceCost * habitabilityModifier * heightModifier;
|
||||
const totalCost = priority + cellsCost;
|
||||
|
||||
if (totalCost >= cost[neibCellId]) continue;
|
||||
from[neibCellId] = next;
|
||||
cost[neibCellId] = totalCost;
|
||||
queue.push(neibCellId, totalCost);
|
||||
}
|
||||
}
|
||||
|
||||
return null; // path is not found
|
||||
}
|
||||
|
||||
function addConnection(from, to, routeId) {
|
||||
const routes = pack.cells.routes;
|
||||
|
||||
if (!routes[from]) routes[from] = {};
|
||||
routes[from][to] = routeId;
|
||||
|
||||
if (!routes[to]) routes[to] = {};
|
||||
routes[to][from] = routeId;
|
||||
}
|
||||
}
|
||||
|
||||
// utility functions
|
||||
function isConnected(cellId) {
|
||||
const {routes} = pack.cells;
|
||||
return routes[cellId] && Object.keys(routes[cellId]).length > 0;
|
||||
}
|
||||
|
||||
function areConnected(from, to) {
|
||||
const routeId = pack.cells.routes[from]?.[to];
|
||||
return routeId !== undefined;
|
||||
}
|
||||
|
||||
function getRoute(from, to) {
|
||||
const routeId = pack.cells.routes[from]?.[to];
|
||||
return routeId === undefined ? null : pack.routes[routeId];
|
||||
}
|
||||
|
||||
function hasRoad(cellId) {
|
||||
const connections = pack.cells.routes[cellId];
|
||||
if (!connections) return false;
|
||||
return Object.values(connections).some(routeId => pack.routes[routeId].group === "roads");
|
||||
}
|
||||
|
||||
function isCrossroad(cellId) {
|
||||
const connections = pack.cells.routes[cellId];
|
||||
if (!connections) return false;
|
||||
return (
|
||||
Object.keys(connections).length > 3 ||
|
||||
Object.values(connections).filter(routeId => pack.routes[routeId]?.group === "roads").length > 2
|
||||
);
|
||||
}
|
||||
|
||||
// name generator data
|
||||
const models = {
|
||||
roads: {burg_suffix: 3, prefix_suffix: 6, the_descriptor_prefix_suffix: 2, the_descriptor_burg_suffix: 1},
|
||||
trails: {burg_suffix: 8, prefix_suffix: 1, the_descriptor_burg_suffix: 1},
|
||||
searoutes: {burg_suffix: 4, prefix_suffix: 2, the_descriptor_prefix_suffix: 1}
|
||||
};
|
||||
|
||||
const prefixes = [
|
||||
"King",
|
||||
"Queen",
|
||||
"Military",
|
||||
"Old",
|
||||
"New",
|
||||
"Ancient",
|
||||
"Royal",
|
||||
"Imperial",
|
||||
"Great",
|
||||
"Grand",
|
||||
"High",
|
||||
"Silver",
|
||||
"Dragon",
|
||||
"Shadow",
|
||||
"Star",
|
||||
"Mystic",
|
||||
"Whisper",
|
||||
"Eagle",
|
||||
"Golden",
|
||||
"Crystal",
|
||||
"Enchanted",
|
||||
"Frost",
|
||||
"Moon",
|
||||
"Sun",
|
||||
"Thunder",
|
||||
"Phoenix",
|
||||
"Sapphire",
|
||||
"Celestial",
|
||||
"Wandering",
|
||||
"Echo",
|
||||
"Twilight",
|
||||
"Crimson",
|
||||
"Serpent",
|
||||
"Iron",
|
||||
"Forest",
|
||||
"Flower",
|
||||
"Whispering",
|
||||
"Eternal",
|
||||
"Frozen",
|
||||
"Rain",
|
||||
"Luminous",
|
||||
"Stardust",
|
||||
"Arcane",
|
||||
"Glimmering",
|
||||
"Jade",
|
||||
"Ember",
|
||||
"Azure",
|
||||
"Gilded",
|
||||
"Divine",
|
||||
"Shadowed",
|
||||
"Cursed",
|
||||
"Moonlit",
|
||||
"Sable",
|
||||
"Everlasting",
|
||||
"Amber",
|
||||
"Nightshade",
|
||||
"Wraith",
|
||||
"Scarlet",
|
||||
"Platinum",
|
||||
"Whirlwind",
|
||||
"Obsidian",
|
||||
"Ethereal",
|
||||
"Ghost",
|
||||
"Spike",
|
||||
"Dusk",
|
||||
"Raven",
|
||||
"Spectral",
|
||||
"Burning",
|
||||
"Verdant",
|
||||
"Copper",
|
||||
"Velvet",
|
||||
"Falcon",
|
||||
"Enigma",
|
||||
"Glowing",
|
||||
"Silvered",
|
||||
"Molten",
|
||||
"Radiant",
|
||||
"Astral",
|
||||
"Wild",
|
||||
"Flame",
|
||||
"Amethyst",
|
||||
"Aurora",
|
||||
"Shadowy",
|
||||
"Solar",
|
||||
"Lunar",
|
||||
"Whisperwind",
|
||||
"Fading",
|
||||
"Titan",
|
||||
"Dawn",
|
||||
"Crystalline",
|
||||
"Jeweled",
|
||||
"Sylvan",
|
||||
"Twisted",
|
||||
"Ebon",
|
||||
"Thorn",
|
||||
"Cerulean",
|
||||
"Halcyon",
|
||||
"Infernal",
|
||||
"Storm",
|
||||
"Eldritch",
|
||||
"Sapphire",
|
||||
"Crimson",
|
||||
"Tranquil",
|
||||
"Paved"
|
||||
];
|
||||
|
||||
const descriptors = [
|
||||
"Great",
|
||||
"Shrouded",
|
||||
"Sacred",
|
||||
"Fabled",
|
||||
"Frosty",
|
||||
"Winding",
|
||||
"Echoing",
|
||||
"Serpentine",
|
||||
"Breezy",
|
||||
"Misty",
|
||||
"Rustic",
|
||||
"Silent",
|
||||
"Cobbled",
|
||||
"Cracked",
|
||||
"Shaky",
|
||||
"Obscure"
|
||||
];
|
||||
|
||||
const suffixes = {
|
||||
roads: {road: 7, route: 3, way: 2, highway: 1},
|
||||
trails: {trail: 4, path: 1, track: 1, pass: 1},
|
||||
searoutes: {"sea route": 5, lane: 2, passage: 1, seaway: 1}
|
||||
};
|
||||
|
||||
function generateName({group, points}) {
|
||||
if (points.length < 4) return "Unnamed route segment";
|
||||
|
||||
const model = rw(models[group]);
|
||||
const suffix = rw(suffixes[group]);
|
||||
|
||||
const burgName = getBurgName();
|
||||
if (model === "burg_suffix" && burgName) return `${burgName} ${suffix}`;
|
||||
if (model === "prefix_suffix") return `${ra(prefixes)} ${suffix}`;
|
||||
if (model === "the_descriptor_prefix_suffix") return `The ${ra(descriptors)} ${ra(prefixes)} ${suffix}`;
|
||||
if (model === "the_descriptor_burg_suffix" && burgName) return `The ${ra(descriptors)} ${burgName} ${suffix}`;
|
||||
return "Unnamed route";
|
||||
|
||||
function getBurgName() {
|
||||
const priority = [points.at(-1), points.at(0), points.slice(1, -1).reverse()];
|
||||
for (const [_x, _y, cellId] of priority) {
|
||||
const burgId = pack.cells.burg[cellId];
|
||||
if (burgId) return getAdjective(pack.burgs[burgId].name);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const ROUTE_CURVES = {
|
||||
roads: d3.curveCatmullRom.alpha(0.1),
|
||||
trails: d3.curveCatmullRom.alpha(0.1),
|
||||
searoutes: d3.curveCatmullRom.alpha(0.5),
|
||||
default: d3.curveCatmullRom.alpha(0.1)
|
||||
};
|
||||
|
||||
function getPath({group, points}) {
|
||||
const lineGen = d3.line();
|
||||
lineGen.curve(ROUTE_CURVES[group] || ROUTE_CURVES.default);
|
||||
const path = round(lineGen(points.map(p => [p[0], p[1]])), 1);
|
||||
return path;
|
||||
}
|
||||
|
||||
// find water paths
|
||||
function findOceanPath(start, exit = null, toRoute = null) {
|
||||
const cells = pack.cells,
|
||||
temp = grid.cells.temp;
|
||||
const queue = new PriorityQueue({comparator: (a, b) => a.p - b.p});
|
||||
const cost = [],
|
||||
from = [];
|
||||
queue.queue({e: start, p: 0});
|
||||
function getLength(routeId) {
|
||||
const path = routes.select("#route" + routeId).node();
|
||||
return path.getTotalLength();
|
||||
}
|
||||
|
||||
while (queue.length) {
|
||||
const next = queue.dequeue(),
|
||||
n = next.e,
|
||||
p = next.p;
|
||||
if (toRoute && n !== start && cells.road[n]) return [from, n, true];
|
||||
function getNextId() {
|
||||
return pack.routes.length ? Math.max(...pack.routes.map(r => r.i)) + 1 : 0;
|
||||
}
|
||||
|
||||
for (const c of cells.c[n]) {
|
||||
if (c === exit) {
|
||||
from[c] = n;
|
||||
return [from, exit, true];
|
||||
function remove(route) {
|
||||
const routes = pack.cells.routes;
|
||||
|
||||
for (const point of route.points) {
|
||||
const from = point[2];
|
||||
|
||||
for (const [to, routeId] of Object.entries(routes[from])) {
|
||||
if (routeId === route.i) {
|
||||
delete routes[from][to];
|
||||
delete routes[to][from];
|
||||
}
|
||||
if (cells.h[c] >= 20) continue; // ignore land cells
|
||||
if (temp[cells.g[c]] <= -5) continue; // ignore cells with term <= -5
|
||||
const dist2 = (cells.p[c][1] - cells.p[n][1]) ** 2 + (cells.p[c][0] - cells.p[n][0]) ** 2;
|
||||
const totalCost = p + (cells.road[c] ? 1 + dist2 / 2 : dist2 + (cells.t[c] ? 1 : 100));
|
||||
|
||||
if (from[c] || totalCost >= cost[c]) continue;
|
||||
(from[c] = n), (cost[c] = totalCost);
|
||||
queue.queue({e: c, p: totalCost});
|
||||
}
|
||||
}
|
||||
return [from, exit, false];
|
||||
|
||||
pack.routes = pack.routes.filter(r => r.i !== route.i);
|
||||
viewbox
|
||||
.select("#routes")
|
||||
.select("#route" + route.i)
|
||||
.remove();
|
||||
}
|
||||
|
||||
return {
|
||||
generate,
|
||||
connect,
|
||||
isConnected,
|
||||
areConnected,
|
||||
getRoute,
|
||||
hasRoad,
|
||||
isCrossroad,
|
||||
generateName,
|
||||
getPath,
|
||||
getLength,
|
||||
getNextId,
|
||||
remove
|
||||
};
|
||||
})();
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ window.Submap = (function () {
|
|||
|
||||
const projection = options.projection;
|
||||
const inverse = options.inverse;
|
||||
const stage = s => INFO && console.log("SUBMAP:", s);
|
||||
const stage = s => INFO && console.info("SUBMAP:", s);
|
||||
const timeStart = performance.now();
|
||||
invokeActiveZooming();
|
||||
|
||||
|
|
@ -36,7 +36,7 @@ window.Submap = (function () {
|
|||
seed = parentMap.seed;
|
||||
Math.random = aleaPRNG(seed);
|
||||
INFO && console.group("SubMap with seed: " + seed);
|
||||
DEBUG && console.log("Using Options:", options);
|
||||
DEBUG && console.info("Using Options:", options);
|
||||
|
||||
// create new grid
|
||||
applyGraphSize();
|
||||
|
|
@ -145,8 +145,6 @@ window.Submap = (function () {
|
|||
cells.state = new Uint16Array(pn);
|
||||
cells.burg = new Uint16Array(pn);
|
||||
cells.religion = new Uint16Array(pn);
|
||||
cells.road = new Uint16Array(pn);
|
||||
cells.crossroad = new Uint16Array(pn);
|
||||
cells.province = new Uint16Array(pn);
|
||||
|
||||
stage("Resampling culture, state and religion map.");
|
||||
|
|
@ -272,8 +270,8 @@ window.Submap = (function () {
|
|||
|
||||
BurgsAndStates.drawBurgs();
|
||||
|
||||
stage("Regenerating road network.");
|
||||
Routes.regenerate();
|
||||
stage("Regenerating routes network.");
|
||||
regenerateRoutes();
|
||||
|
||||
drawStates();
|
||||
drawBorders();
|
||||
|
|
@ -396,8 +394,8 @@ window.Submap = (function () {
|
|||
b.removed = true;
|
||||
return;
|
||||
}
|
||||
DEBUG && console.log(`Moving ${b.name} from ${cityCell} to ${newCell} near ${neighbor}.`);
|
||||
[b.x, b.y] = b.port ? getMiddlePoint(newCell, neighbor) : cells.p[newCell];
|
||||
DEBUG && console.info(`Moving ${b.name} from ${cityCell} to ${newCell} near ${neighbor}.`);
|
||||
[b.x, b.y] = b.port ? getCloseToEdgePoint(newCell, neighbor) : cells.p[newCell];
|
||||
if (b.port) b.port = cells.f[neighbor]; // copy feature number
|
||||
b.cell = newCell;
|
||||
if (b.port && !isWater(pack, neighbor)) console.error("betrayal! negihbor must be water!", b);
|
||||
|
|
@ -409,6 +407,23 @@ window.Submap = (function () {
|
|||
});
|
||||
}
|
||||
|
||||
function getCloseToEdgePoint(cell1, cell2) {
|
||||
const {cells, vertices} = pack;
|
||||
|
||||
const [x0, y0] = cells.p[cell1];
|
||||
|
||||
const commonVertices = cells.v[cell1].filter(vertex => vertices.c[vertex].some(cell => cell === cell2));
|
||||
const [x1, y1] = vertices.p[commonVertices[0]];
|
||||
const [x2, y2] = vertices.p[commonVertices[1]];
|
||||
const xEdge = (x1 + x2) / 2;
|
||||
const yEdge = (y1 + y2) / 2;
|
||||
|
||||
const x = rn(x0 + 0.95 * (xEdge - x0), 2);
|
||||
const y = rn(y0 + 0.95 * (yEdge - y0), 2);
|
||||
|
||||
return [x, y];
|
||||
}
|
||||
|
||||
// export
|
||||
return {resample, findNearest};
|
||||
})();
|
||||
|
|
|
|||
|
|
@ -37,12 +37,22 @@ class Battle {
|
|||
|
||||
// add listeners
|
||||
document.getElementById("battleType").addEventListener("click", ev => this.toggleChange(ev));
|
||||
document.getElementById("battleType").nextElementSibling.addEventListener("click", ev => Battle.prototype.context.changeType(ev));
|
||||
document.getElementById("battleNameShow").addEventListener("click", () => Battle.prototype.context.showNameSection());
|
||||
document.getElementById("battleNamePlace").addEventListener("change", ev => (Battle.prototype.context.place = ev.target.value));
|
||||
document
|
||||
.getElementById("battleType")
|
||||
.nextElementSibling.addEventListener("click", ev => Battle.prototype.context.changeType(ev));
|
||||
document
|
||||
.getElementById("battleNameShow")
|
||||
.addEventListener("click", () => Battle.prototype.context.showNameSection());
|
||||
document
|
||||
.getElementById("battleNamePlace")
|
||||
.addEventListener("change", ev => (Battle.prototype.context.place = ev.target.value));
|
||||
document.getElementById("battleNameFull").addEventListener("change", ev => Battle.prototype.context.changeName(ev));
|
||||
document.getElementById("battleNameCulture").addEventListener("click", () => Battle.prototype.context.generateName("culture"));
|
||||
document.getElementById("battleNameRandom").addEventListener("click", () => Battle.prototype.context.generateName("random"));
|
||||
document
|
||||
.getElementById("battleNameCulture")
|
||||
.addEventListener("click", () => Battle.prototype.context.generateName("culture"));
|
||||
document
|
||||
.getElementById("battleNameRandom")
|
||||
.addEventListener("click", () => Battle.prototype.context.generateName("random"));
|
||||
document.getElementById("battleNameHide").addEventListener("click", this.hideNameSection);
|
||||
document.getElementById("battleAddRegiment").addEventListener("click", this.addSide);
|
||||
document.getElementById("battleRoll").addEventListener("click", () => Battle.prototype.context.randomize());
|
||||
|
|
@ -52,11 +62,19 @@ class Battle {
|
|||
document.getElementById("battleWiki").addEventListener("click", () => wiki("Battle-Simulator"));
|
||||
|
||||
document.getElementById("battlePhase_attackers").addEventListener("click", ev => this.toggleChange(ev));
|
||||
document.getElementById("battlePhase_attackers").nextElementSibling.addEventListener("click", ev => Battle.prototype.context.changePhase(ev, "attackers"));
|
||||
document
|
||||
.getElementById("battlePhase_attackers")
|
||||
.nextElementSibling.addEventListener("click", ev => Battle.prototype.context.changePhase(ev, "attackers"));
|
||||
document.getElementById("battlePhase_defenders").addEventListener("click", ev => this.toggleChange(ev));
|
||||
document.getElementById("battlePhase_defenders").nextElementSibling.addEventListener("click", ev => Battle.prototype.context.changePhase(ev, "defenders"));
|
||||
document.getElementById("battleDie_attackers").addEventListener("click", () => Battle.prototype.context.rollDie("attackers"));
|
||||
document.getElementById("battleDie_defenders").addEventListener("click", () => Battle.prototype.context.rollDie("defenders"));
|
||||
document
|
||||
.getElementById("battlePhase_defenders")
|
||||
.nextElementSibling.addEventListener("click", ev => Battle.prototype.context.changePhase(ev, "defenders"));
|
||||
document
|
||||
.getElementById("battleDie_attackers")
|
||||
.addEventListener("click", () => Battle.prototype.context.rollDie("attackers"));
|
||||
document
|
||||
.getElementById("battleDie_defenders")
|
||||
.addEventListener("click", () => Battle.prototype.context.rollDie("defenders"));
|
||||
}
|
||||
|
||||
defineType() {
|
||||
|
|
@ -82,8 +100,12 @@ class Battle {
|
|||
document.getElementById("battleType").className = "icon-button-" + this.type;
|
||||
|
||||
const sideSpecific = document.getElementById("battlePhases_" + this.type + "_attackers");
|
||||
const attackers = sideSpecific ? sideSpecific.content : document.getElementById("battlePhases_" + this.type).content;
|
||||
const defenders = sideSpecific ? document.getElementById("battlePhases_" + this.type + "_defenders").content : attackers;
|
||||
const attackers = sideSpecific
|
||||
? sideSpecific.content
|
||||
: document.getElementById("battlePhases_" + this.type).content;
|
||||
const defenders = sideSpecific
|
||||
? document.getElementById("battlePhases_" + this.type + "_defenders").content
|
||||
: attackers;
|
||||
|
||||
document.getElementById("battlePhase_attackers").nextElementSibling.innerHTML = "";
|
||||
document.getElementById("battlePhase_defenders").nextElementSibling.innerHTML = "";
|
||||
|
|
@ -139,26 +161,37 @@ class Battle {
|
|||
regiment.survivors = Object.assign({}, regiment.u);
|
||||
|
||||
const state = pack.states[regiment.state];
|
||||
const distance = (Math.hypot(this.y - regiment.by, this.x - regiment.bx) * distanceScaleInput.value) | 0; // distance between regiment and its base
|
||||
const distance = (Math.hypot(this.y - regiment.by, this.x - regiment.bx) * distanceScale) | 0; // distance between regiment and its base
|
||||
const color = state.color[0] === "#" ? state.color : "#999";
|
||||
const icon = `<svg width="1.4em" height="1.4em" style="margin-bottom: -.6em; stroke: #333">
|
||||
<rect x="0" y="0" width="100%" height="100%" fill="${color}"></rect>
|
||||
<text x="0" y="1.04em" style="">${regiment.icon}</text></svg>`;
|
||||
const body = `<tbody id="battle${state.i}-${regiment.i}">`;
|
||||
|
||||
let initial = `<tr class="battleInitial"><td>${icon}</td><td class="regiment" data-tip="${regiment.name}">${regiment.name.slice(0, 24)}</td>`;
|
||||
let casualties = `<tr class="battleCasualties"><td></td><td data-tip="${state.fullName}">${state.fullName.slice(0, 26)}</td>`;
|
||||
let initial = `<tr class="battleInitial"><td>${icon}</td><td class="regiment" data-tip="${
|
||||
regiment.name
|
||||
}">${regiment.name.slice(0, 24)}</td>`;
|
||||
let casualties = `<tr class="battleCasualties"><td></td><td data-tip="${state.fullName}">${state.fullName.slice(
|
||||
0,
|
||||
26
|
||||
)}</td>`;
|
||||
let survivors = `<tr class="battleSurvivors"><td></td><td data-tip="Supply line length, affects morale">Distance to base: ${distance} ${distanceUnitInput.value}</td>`;
|
||||
|
||||
for (const u of options.military) {
|
||||
initial += `<td data-tip="Initial forces" style="width: 2.5em; text-align: center">${regiment.u[u.name] || 0}</td>`;
|
||||
initial += `<td data-tip="Initial forces" style="width: 2.5em; text-align: center">${
|
||||
regiment.u[u.name] || 0
|
||||
}</td>`;
|
||||
casualties += `<td data-tip="Casualties" style="width: 2.5em; text-align: center; color: red">0</td>`;
|
||||
survivors += `<td data-tip="Survivors" style="width: 2.5em; text-align: center; color: green">${regiment.u[u.name] || 0}</td>`;
|
||||
survivors += `<td data-tip="Survivors" style="width: 2.5em; text-align: center; color: green">${
|
||||
regiment.u[u.name] || 0
|
||||
}</td>`;
|
||||
}
|
||||
|
||||
initial += `<td data-tip="Initial forces" style="width: 2.5em; text-align: center">${regiment.a || 0}</td></tr>`;
|
||||
casualties += `<td data-tip="Casualties" style="width: 2.5em; text-align: center; color: red">0</td></tr>`;
|
||||
survivors += `<td data-tip="Survivors" style="width: 2.5em; text-align: center; color: green">${regiment.a || 0}</td></tr>`;
|
||||
survivors += `<td data-tip="Survivors" style="width: 2.5em; text-align: center; color: green">${
|
||||
regiment.a || 0
|
||||
}</td></tr>`;
|
||||
|
||||
const div = side === "attackers" ? battleAttackers : battleDefenders;
|
||||
div.innerHTML += body + initial + casualties + survivors + "</tbody>";
|
||||
|
|
@ -173,17 +206,23 @@ class Battle {
|
|||
.filter(s => s.military && !s.removed)
|
||||
.map(s => s.military)
|
||||
.flat();
|
||||
const distance = reg => rn(Math.hypot(context.y - reg.y, context.x - reg.x) * distanceScaleInput.value) + " " + distanceUnitInput.value;
|
||||
const isAdded = reg => context.defenders.regiments.some(r => r === reg) || context.attackers.regiments.some(r => r === reg);
|
||||
const distance = reg =>
|
||||
rn(Math.hypot(context.y - reg.y, context.x - reg.x) * distanceScale) + " " + distanceUnitInput.value;
|
||||
const isAdded = reg =>
|
||||
context.defenders.regiments.some(r => r === reg) || context.attackers.regiments.some(r => r === reg);
|
||||
|
||||
body.innerHTML = regiments
|
||||
.map(r => {
|
||||
const s = pack.states[r.state],
|
||||
added = isAdded(r),
|
||||
dist = added ? "0 " + distanceUnitInput.value : distance(r);
|
||||
return `<div ${added ? "class='inactive'" : ""} data-s=${s.i} data-i=${r.i} data-state=${s.name} data-regiment=${r.name}
|
||||
return `<div ${added ? "class='inactive'" : ""} data-s=${s.i} data-i=${r.i} data-state=${
|
||||
s.name
|
||||
} data-regiment=${r.name}
|
||||
data-total=${r.a} data-distance=${dist} data-tip="Click to select regiment">
|
||||
<svg width=".9em" height=".9em" style="margin-bottom:-1px; stroke: #333"><rect x="0" y="0" width="100%" height="100%" fill="${s.color}" ></svg>
|
||||
<svg width=".9em" height=".9em" style="margin-bottom:-1px; stroke: #333"><rect x="0" y="0" width="100%" height="100%" fill="${
|
||||
s.color
|
||||
}" ></svg>
|
||||
<div style="width:6em">${s.name.slice(0, 11)}</div>
|
||||
<div style="width:1.2em">${r.icon}</div>
|
||||
<div style="width:13em">${r.name.slice(0, 24)}</div>
|
||||
|
|
@ -267,7 +306,10 @@ class Battle {
|
|||
}
|
||||
|
||||
generateName(type) {
|
||||
const place = type === "culture" ? Names.getCulture(pack.cells.culture[this.cell], null, null, "") : Names.getBase(rand(nameBases.length - 1));
|
||||
const place =
|
||||
type === "culture"
|
||||
? Names.getCulture(pack.cells.culture[this.cell], null, null, "")
|
||||
: Names.getBase(rand(nameBases.length - 1));
|
||||
document.getElementById("battleNamePlace").value = this.place = place;
|
||||
document.getElementById("battleNameFull").value = this.name = this.defineName();
|
||||
$("#battleScreen").dialog({title: this.name});
|
||||
|
|
@ -286,35 +328,161 @@ class Battle {
|
|||
calculateStrength(side) {
|
||||
const scheme = {
|
||||
// field battle phases
|
||||
skirmish: {melee: 0.2, ranged: 2.4, mounted: 0.1, machinery: 3, naval: 1, armored: 0.2, aviation: 1.8, magical: 1.8}, // ranged excel
|
||||
skirmish: {
|
||||
melee: 0.2,
|
||||
ranged: 2.4,
|
||||
mounted: 0.1,
|
||||
machinery: 3,
|
||||
naval: 1,
|
||||
armored: 0.2,
|
||||
aviation: 1.8,
|
||||
magical: 1.8
|
||||
}, // ranged excel
|
||||
melee: {melee: 2, ranged: 1.2, mounted: 1.5, machinery: 0.5, naval: 0.2, armored: 2, aviation: 0.8, magical: 0.8}, // melee excel
|
||||
pursue: {melee: 1, ranged: 1, mounted: 4, machinery: 0.05, naval: 1, armored: 1, aviation: 1.5, magical: 0.6}, // mounted excel
|
||||
retreat: {melee: 0.1, ranged: 0.01, mounted: 0.5, machinery: 0.01, naval: 0.2, armored: 0.1, aviation: 0.8, magical: 0.05}, // reduced
|
||||
retreat: {
|
||||
melee: 0.1,
|
||||
ranged: 0.01,
|
||||
mounted: 0.5,
|
||||
machinery: 0.01,
|
||||
naval: 0.2,
|
||||
armored: 0.1,
|
||||
aviation: 0.8,
|
||||
magical: 0.05
|
||||
}, // reduced
|
||||
|
||||
// naval battle phases
|
||||
shelling: {melee: 0, ranged: 0.2, mounted: 0, machinery: 2, naval: 2, armored: 0, aviation: 0.1, magical: 0.5}, // naval and machinery excel
|
||||
boarding: {melee: 1, ranged: 0.5, mounted: 0.5, machinery: 0, naval: 0.5, armored: 0.4, aviation: 0, magical: 0.2}, // melee excel
|
||||
boarding: {
|
||||
melee: 1,
|
||||
ranged: 0.5,
|
||||
mounted: 0.5,
|
||||
machinery: 0,
|
||||
naval: 0.5,
|
||||
armored: 0.4,
|
||||
aviation: 0,
|
||||
magical: 0.2
|
||||
}, // melee excel
|
||||
chase: {melee: 0, ranged: 0.15, mounted: 0, machinery: 1, naval: 1, armored: 0, aviation: 0.15, magical: 0.5}, // reduced
|
||||
withdrawal: {melee: 0, ranged: 0.02, mounted: 0, machinery: 0.5, naval: 0.1, armored: 0, aviation: 0.1, magical: 0.3}, // reduced
|
||||
withdrawal: {
|
||||
melee: 0,
|
||||
ranged: 0.02,
|
||||
mounted: 0,
|
||||
machinery: 0.5,
|
||||
naval: 0.1,
|
||||
armored: 0,
|
||||
aviation: 0.1,
|
||||
magical: 0.3
|
||||
}, // reduced
|
||||
|
||||
// siege phases
|
||||
blockade: {melee: 0.25, ranged: 0.25, mounted: 0.2, machinery: 0.5, naval: 0.2, armored: 0.1, aviation: 0.25, magical: 0.25}, // no active actions
|
||||
sheltering: {melee: 0.3, ranged: 0.5, mounted: 0.2, machinery: 0.5, naval: 0.2, armored: 0.1, aviation: 0.25, magical: 0.25}, // no active actions
|
||||
blockade: {
|
||||
melee: 0.25,
|
||||
ranged: 0.25,
|
||||
mounted: 0.2,
|
||||
machinery: 0.5,
|
||||
naval: 0.2,
|
||||
armored: 0.1,
|
||||
aviation: 0.25,
|
||||
magical: 0.25
|
||||
}, // no active actions
|
||||
sheltering: {
|
||||
melee: 0.3,
|
||||
ranged: 0.5,
|
||||
mounted: 0.2,
|
||||
machinery: 0.5,
|
||||
naval: 0.2,
|
||||
armored: 0.1,
|
||||
aviation: 0.25,
|
||||
magical: 0.25
|
||||
}, // no active actions
|
||||
sortie: {melee: 2, ranged: 0.5, mounted: 1.2, machinery: 0.2, naval: 0.1, armored: 0.5, aviation: 1, magical: 1}, // melee excel
|
||||
bombardment: {melee: 0.2, ranged: 0.5, mounted: 0.2, machinery: 3, naval: 1, armored: 0.5, aviation: 1, magical: 1}, // machinery excel
|
||||
storming: {melee: 1, ranged: 0.6, mounted: 0.5, machinery: 1, naval: 0.1, armored: 0.1, aviation: 0.5, magical: 0.5}, // melee excel
|
||||
bombardment: {
|
||||
melee: 0.2,
|
||||
ranged: 0.5,
|
||||
mounted: 0.2,
|
||||
machinery: 3,
|
||||
naval: 1,
|
||||
armored: 0.5,
|
||||
aviation: 1,
|
||||
magical: 1
|
||||
}, // machinery excel
|
||||
storming: {
|
||||
melee: 1,
|
||||
ranged: 0.6,
|
||||
mounted: 0.5,
|
||||
machinery: 1,
|
||||
naval: 0.1,
|
||||
armored: 0.1,
|
||||
aviation: 0.5,
|
||||
magical: 0.5
|
||||
}, // melee excel
|
||||
defense: {melee: 2, ranged: 3, mounted: 1, machinery: 1, naval: 0.1, armored: 1, aviation: 0.5, magical: 1}, // ranged excel
|
||||
looting: {melee: 1.6, ranged: 1.6, mounted: 0.5, machinery: 0.2, naval: 0.02, armored: 0.2, aviation: 0.1, magical: 0.3}, // melee excel
|
||||
surrendering: {melee: 0.1, ranged: 0.1, mounted: 0.05, machinery: 0.01, naval: 0.01, armored: 0.02, aviation: 0.01, magical: 0.03}, // reduced
|
||||
looting: {
|
||||
melee: 1.6,
|
||||
ranged: 1.6,
|
||||
mounted: 0.5,
|
||||
machinery: 0.2,
|
||||
naval: 0.02,
|
||||
armored: 0.2,
|
||||
aviation: 0.1,
|
||||
magical: 0.3
|
||||
}, // melee excel
|
||||
surrendering: {
|
||||
melee: 0.1,
|
||||
ranged: 0.1,
|
||||
mounted: 0.05,
|
||||
machinery: 0.01,
|
||||
naval: 0.01,
|
||||
armored: 0.02,
|
||||
aviation: 0.01,
|
||||
magical: 0.03
|
||||
}, // reduced
|
||||
|
||||
// ambush phases
|
||||
surprise: {melee: 2, ranged: 2.4, mounted: 1, machinery: 1, naval: 1, armored: 1, aviation: 0.8, magical: 1.2}, // increased
|
||||
shock: {melee: 0.5, ranged: 0.5, mounted: 0.5, machinery: 0.4, naval: 0.3, armored: 0.1, aviation: 0.4, magical: 0.5}, // reduced
|
||||
shock: {
|
||||
melee: 0.5,
|
||||
ranged: 0.5,
|
||||
mounted: 0.5,
|
||||
machinery: 0.4,
|
||||
naval: 0.3,
|
||||
armored: 0.1,
|
||||
aviation: 0.4,
|
||||
magical: 0.5
|
||||
}, // reduced
|
||||
|
||||
// langing phases
|
||||
landing: {melee: 0.8, ranged: 0.6, mounted: 0.6, machinery: 0.5, naval: 0.5, armored: 0.5, aviation: 0.5, magical: 0.6}, // reduced
|
||||
flee: {melee: 0.1, ranged: 0.01, mounted: 0.5, machinery: 0.01, naval: 0.5, armored: 0.1, aviation: 0.2, magical: 0.05}, // reduced
|
||||
waiting: {melee: 0.05, ranged: 0.5, mounted: 0.05, machinery: 0.5, naval: 2, armored: 0.05, aviation: 0.5, magical: 0.5}, // reduced
|
||||
landing: {
|
||||
melee: 0.8,
|
||||
ranged: 0.6,
|
||||
mounted: 0.6,
|
||||
machinery: 0.5,
|
||||
naval: 0.5,
|
||||
armored: 0.5,
|
||||
aviation: 0.5,
|
||||
magical: 0.6
|
||||
}, // reduced
|
||||
flee: {
|
||||
melee: 0.1,
|
||||
ranged: 0.01,
|
||||
mounted: 0.5,
|
||||
machinery: 0.01,
|
||||
naval: 0.5,
|
||||
armored: 0.1,
|
||||
aviation: 0.2,
|
||||
magical: 0.05
|
||||
}, // reduced
|
||||
waiting: {
|
||||
melee: 0.05,
|
||||
ranged: 0.5,
|
||||
mounted: 0.05,
|
||||
machinery: 0.5,
|
||||
naval: 2,
|
||||
armored: 0.05,
|
||||
aviation: 0.5,
|
||||
magical: 0.5
|
||||
}, // reduced
|
||||
|
||||
// air battle phases
|
||||
maneuvering: {melee: 0, ranged: 0.1, mounted: 0, machinery: 0.2, naval: 0, armored: 0, aviation: 1, magical: 0.2}, // aviation
|
||||
|
|
@ -324,7 +492,8 @@ class Battle {
|
|||
const forces = this.getJoinedForces(this[side].regiments);
|
||||
const phase = this[side].phase;
|
||||
const adjuster = Math.max(populationRate / 10, 10); // population adjuster, by default 100
|
||||
this[side].power = d3.sum(options.military.map(u => (forces[u.name] || 0) * u.power * scheme[phase][u.type])) / adjuster;
|
||||
this[side].power =
|
||||
d3.sum(options.military.map(u => (forces[u.name] || 0) * u.power * scheme[phase][u.type])) / adjuster;
|
||||
const UIvalue = this[side].power ? Math.max(this[side].power | 0, 1) : 0;
|
||||
document.getElementById("battlePower_" + side).innerHTML = UIvalue;
|
||||
}
|
||||
|
|
@ -723,11 +892,13 @@ class Battle {
|
|||
|
||||
const status = battleStatus[+P(0.7)];
|
||||
const result = `The ${this.getTypeName(this.type)} ended in ${status}`;
|
||||
const legend = `${this.name} took place in ${options.year} ${options.eraShort}. It was fought between ${getSide(this.attackers.regiments, 1)} and ${getSide(
|
||||
this.defenders.regiments,
|
||||
0
|
||||
)}. ${result}.
|
||||
\r\nAttackers losses: ${getLosses(this.attackers.casualties)}%, defenders losses: ${getLosses(this.defenders.casualties)}%`;
|
||||
const legend = `${this.name} took place in ${options.year} ${options.eraShort}. It was fought between ${getSide(
|
||||
this.attackers.regiments,
|
||||
1
|
||||
)} and ${getSide(this.defenders.regiments, 0)}. ${result}.
|
||||
\r\nAttackers losses: ${getLosses(this.attackers.casualties)}%, defenders losses: ${getLosses(
|
||||
this.defenders.casualties
|
||||
)}%`;
|
||||
notes.push({id: `marker${i}`, name: this.name, legend});
|
||||
|
||||
tip(`${this.name} is over. ${result}`, true, "success", 4000);
|
||||
|
|
|
|||
|
|
@ -390,7 +390,7 @@ function editBiomes() {
|
|||
const p = d3.mouse(this);
|
||||
moveCircle(p[0], p[1], r);
|
||||
|
||||
const found = r > 5 ? findAll(p[0], p[1], r) : [findCell(p[0], p[1], r)];
|
||||
const found = r > 5 ? findAll(p[0], p[1], r) : [findCell(p[0], p[1])];
|
||||
const selection = found.filter(isLand);
|
||||
if (selection) changeBiomeForSelection(selection);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -21,38 +21,37 @@ function editBurg(id) {
|
|||
modules.editBurg = true;
|
||||
|
||||
// add listeners
|
||||
document.getElementById("burgGroupShow").addEventListener("click", showGroupSection);
|
||||
document.getElementById("burgGroupHide").addEventListener("click", hideGroupSection);
|
||||
document.getElementById("burgSelectGroup").addEventListener("change", changeGroup);
|
||||
document.getElementById("burgInputGroup").addEventListener("change", createNewGroup);
|
||||
document.getElementById("burgAddGroup").addEventListener("click", toggleNewGroupInput);
|
||||
document.getElementById("burgRemoveGroup").addEventListener("click", removeBurgsGroup);
|
||||
byId("burgGroupShow").addEventListener("click", showGroupSection);
|
||||
byId("burgGroupHide").addEventListener("click", hideGroupSection);
|
||||
byId("burgSelectGroup").addEventListener("change", changeGroup);
|
||||
byId("burgInputGroup").addEventListener("change", createNewGroup);
|
||||
byId("burgAddGroup").addEventListener("click", toggleNewGroupInput);
|
||||
byId("burgRemoveGroup").addEventListener("click", removeBurgsGroup);
|
||||
|
||||
document.getElementById("burgName").addEventListener("input", changeName);
|
||||
document.getElementById("burgNameReRandom").addEventListener("click", generateNameRandom);
|
||||
document.getElementById("burgType").addEventListener("input", changeType);
|
||||
document.getElementById("burgCulture").addEventListener("input", changeCulture);
|
||||
document.getElementById("burgNameReCulture").addEventListener("click", generateNameCulture);
|
||||
document.getElementById("burgPopulation").addEventListener("change", changePopulation);
|
||||
byId("burgName").addEventListener("input", changeName);
|
||||
byId("burgNameReRandom").addEventListener("click", generateNameRandom);
|
||||
byId("burgType").addEventListener("input", changeType);
|
||||
byId("burgCulture").addEventListener("input", changeCulture);
|
||||
byId("burgNameReCulture").addEventListener("click", generateNameCulture);
|
||||
byId("burgPopulation").addEventListener("change", changePopulation);
|
||||
burgBody.querySelectorAll(".burgFeature").forEach(el => el.addEventListener("click", toggleFeature));
|
||||
document.getElementById("mfcgBurgSeed").addEventListener("change", changeSeed);
|
||||
document.getElementById("regenerateMFCGBurgSeed").addEventListener("click", randomizeSeed);
|
||||
document.getElementById("addCustomMFCGBurgLink").addEventListener("click", addCustomMfcgLink);
|
||||
byId("burgLinkOpen").addEventListener("click", openBurgLink);
|
||||
byId("burgLinkEdit").addEventListener("click", changeBurgLink);
|
||||
|
||||
document.getElementById("burgStyleShow").addEventListener("click", showStyleSection);
|
||||
document.getElementById("burgStyleHide").addEventListener("click", hideStyleSection);
|
||||
document.getElementById("burgEditLabelStyle").addEventListener("click", editGroupLabelStyle);
|
||||
document.getElementById("burgEditIconStyle").addEventListener("click", editGroupIconStyle);
|
||||
document.getElementById("burgEditAnchorStyle").addEventListener("click", editGroupAnchorStyle);
|
||||
byId("burgStyleShow").addEventListener("click", showStyleSection);
|
||||
byId("burgStyleHide").addEventListener("click", hideStyleSection);
|
||||
byId("burgEditLabelStyle").addEventListener("click", editGroupLabelStyle);
|
||||
byId("burgEditIconStyle").addEventListener("click", editGroupIconStyle);
|
||||
byId("burgEditAnchorStyle").addEventListener("click", editGroupAnchorStyle);
|
||||
|
||||
document.getElementById("burgEmblem").addEventListener("click", openEmblemEdit);
|
||||
document.getElementById("burgToggleMFCGMap").addEventListener("click", toggleMFCGMap);
|
||||
document.getElementById("burgEditEmblem").addEventListener("click", openEmblemEdit);
|
||||
document.getElementById("burgRelocate").addEventListener("click", toggleRelocateBurg);
|
||||
document.getElementById("burglLegend").addEventListener("click", editBurgLegend);
|
||||
document.getElementById("burgLock").addEventListener("click", toggleBurgLockButton);
|
||||
document.getElementById("burgRemove").addEventListener("click", removeSelectedBurg);
|
||||
document.getElementById("burgTemperatureGraph").addEventListener("click", showTemperatureGraph);
|
||||
byId("burgEmblem").addEventListener("click", openEmblemEdit);
|
||||
byId("burgTogglePreview").addEventListener("click", toggleBurgPreview);
|
||||
byId("burgEditEmblem").addEventListener("click", openEmblemEdit);
|
||||
byId("burgRelocate").addEventListener("click", toggleRelocateBurg);
|
||||
byId("burglLegend").addEventListener("click", editBurgLegend);
|
||||
byId("burgLock").addEventListener("click", toggleBurgLockButton);
|
||||
byId("burgRemove").addEventListener("click", removeSelectedBurg);
|
||||
byId("burgTemperatureGraph").addEventListener("click", showTemperatureGraph);
|
||||
|
||||
function updateBurgValues() {
|
||||
const id = +elSelected.attr("data-id");
|
||||
|
|
@ -60,46 +59,46 @@ function editBurg(id) {
|
|||
const province = pack.cells.province[b.cell];
|
||||
const provinceName = province ? pack.provinces[province].fullName + ", " : "";
|
||||
const stateName = pack.states[b.state].fullName || pack.states[b.state].name;
|
||||
document.getElementById("burgProvinceAndState").innerHTML = provinceName + stateName;
|
||||
byId("burgProvinceAndState").innerHTML = provinceName + stateName;
|
||||
|
||||
document.getElementById("burgName").value = b.name;
|
||||
document.getElementById("burgType").value = b.type || "Generic";
|
||||
document.getElementById("burgPopulation").value = rn(b.population * populationRate * urbanization);
|
||||
document.getElementById("burgEditAnchorStyle").style.display = +b.port ? "inline-block" : "none";
|
||||
byId("burgName").value = b.name;
|
||||
byId("burgType").value = b.type || "Generic";
|
||||
byId("burgPopulation").value = rn(b.population * populationRate * urbanization);
|
||||
byId("burgEditAnchorStyle").style.display = +b.port ? "inline-block" : "none";
|
||||
|
||||
// update list and select culture
|
||||
const cultureSelect = document.getElementById("burgCulture");
|
||||
const cultureSelect = byId("burgCulture");
|
||||
cultureSelect.options.length = 0;
|
||||
const cultures = pack.cultures.filter(c => !c.removed);
|
||||
cultures.forEach(c => cultureSelect.options.add(new Option(c.name, c.i, false, c.i === b.culture)));
|
||||
|
||||
const temperature = grid.cells.temp[pack.cells.g[b.cell]];
|
||||
document.getElementById("burgTemperature").innerHTML = convertTemperature(temperature);
|
||||
document.getElementById("burgTemperatureLikeIn").innerHTML = getTemperatureLikeness(temperature);
|
||||
document.getElementById("burgElevation").innerHTML = getHeight(pack.cells.h[b.cell]);
|
||||
byId("burgTemperature").innerHTML = convertTemperature(temperature);
|
||||
byId("burgTemperatureLikeIn").innerHTML = getTemperatureLikeness(temperature);
|
||||
byId("burgElevation").innerHTML = getHeight(pack.cells.h[b.cell]);
|
||||
|
||||
// toggle features
|
||||
if (b.capital) document.getElementById("burgCapital").classList.remove("inactive");
|
||||
else document.getElementById("burgCapital").classList.add("inactive");
|
||||
if (b.port) document.getElementById("burgPort").classList.remove("inactive");
|
||||
else document.getElementById("burgPort").classList.add("inactive");
|
||||
if (b.citadel) document.getElementById("burgCitadel").classList.remove("inactive");
|
||||
else document.getElementById("burgCitadel").classList.add("inactive");
|
||||
if (b.walls) document.getElementById("burgWalls").classList.remove("inactive");
|
||||
else document.getElementById("burgWalls").classList.add("inactive");
|
||||
if (b.plaza) document.getElementById("burgPlaza").classList.remove("inactive");
|
||||
else document.getElementById("burgPlaza").classList.add("inactive");
|
||||
if (b.temple) document.getElementById("burgTemple").classList.remove("inactive");
|
||||
else document.getElementById("burgTemple").classList.add("inactive");
|
||||
if (b.shanty) document.getElementById("burgShanty").classList.remove("inactive");
|
||||
else document.getElementById("burgShanty").classList.add("inactive");
|
||||
if (b.capital) byId("burgCapital").classList.remove("inactive");
|
||||
else byId("burgCapital").classList.add("inactive");
|
||||
if (b.port) byId("burgPort").classList.remove("inactive");
|
||||
else byId("burgPort").classList.add("inactive");
|
||||
if (b.citadel) byId("burgCitadel").classList.remove("inactive");
|
||||
else byId("burgCitadel").classList.add("inactive");
|
||||
if (b.walls) byId("burgWalls").classList.remove("inactive");
|
||||
else byId("burgWalls").classList.add("inactive");
|
||||
if (b.plaza) byId("burgPlaza").classList.remove("inactive");
|
||||
else byId("burgPlaza").classList.add("inactive");
|
||||
if (b.temple) byId("burgTemple").classList.remove("inactive");
|
||||
else byId("burgTemple").classList.add("inactive");
|
||||
if (b.shanty) byId("burgShanty").classList.remove("inactive");
|
||||
else byId("burgShanty").classList.add("inactive");
|
||||
|
||||
//toggle lock
|
||||
updateBurgLockIcon();
|
||||
|
||||
// select group
|
||||
const group = elSelected.node().parentNode.id;
|
||||
const select = document.getElementById("burgSelectGroup");
|
||||
const select = byId("burgSelectGroup");
|
||||
select.options.length = 0; // remove all options
|
||||
|
||||
burgLabels.selectAll("g").each(function () {
|
||||
|
|
@ -109,68 +108,16 @@ function editBurg(id) {
|
|||
// set emlem image
|
||||
const coaID = "burgCOA" + id;
|
||||
COArenderer.trigger(coaID, b.coa);
|
||||
document.getElementById("burgEmblem").setAttribute("href", "#" + coaID);
|
||||
byId("burgEmblem").setAttribute("href", "#" + coaID);
|
||||
|
||||
if (options.showMFCGMap) {
|
||||
document.getElementById("mfcgPreviewSection").style.display = "block";
|
||||
updateMFCGFrame(b);
|
||||
|
||||
if (b.link) {
|
||||
document.getElementById("mfcgBurgSeedSection").style.display = "none";
|
||||
} else {
|
||||
document.getElementById("mfcgBurgSeedSection").style.display = "inline-block";
|
||||
document.getElementById("mfcgBurgSeed").value = getBurgSeed(b);
|
||||
}
|
||||
if (options.showBurgPreview) {
|
||||
byId("burgPreviewSection").style.display = "block";
|
||||
updateBurgPreview(b);
|
||||
} else {
|
||||
document.getElementById("mfcgPreviewSection").style.display = "none";
|
||||
byId("burgPreviewSection").style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
// in °C, array from -1 °C; source: https://en.wikipedia.org/wiki/List_of_cities_by_average_temperature
|
||||
function getTemperatureLikeness(temperature) {
|
||||
if (temperature < -5) return "Yakutsk";
|
||||
const cities = [
|
||||
"Snag (Yukon)",
|
||||
"Yellowknife (Canada)",
|
||||
"Okhotsk (Russia)",
|
||||
"Fairbanks (Alaska)",
|
||||
"Nuuk (Greenland)",
|
||||
"Murmansk", // -5 - 0
|
||||
"Arkhangelsk",
|
||||
"Anchorage",
|
||||
"Tromsø",
|
||||
"Reykjavik",
|
||||
"Riga",
|
||||
"Stockholm",
|
||||
"Halifax",
|
||||
"Prague",
|
||||
"Copenhagen",
|
||||
"London", // 1 - 10
|
||||
"Antwerp",
|
||||
"Paris",
|
||||
"Milan",
|
||||
"Batumi",
|
||||
"Rome",
|
||||
"Dubrovnik",
|
||||
"Lisbon",
|
||||
"Barcelona",
|
||||
"Marrakesh",
|
||||
"Alexandria", // 11 - 20
|
||||
"Tegucigalpa",
|
||||
"Guangzhou",
|
||||
"Rio de Janeiro",
|
||||
"Dakar",
|
||||
"Miami",
|
||||
"Jakarta",
|
||||
"Mogadishu",
|
||||
"Bangkok",
|
||||
"Aden",
|
||||
"Khartoum"
|
||||
]; // 21 - 30
|
||||
if (temperature > 30) return "Mecca";
|
||||
return cities[temperature + 5] || null;
|
||||
}
|
||||
|
||||
function dragBurgLabel() {
|
||||
const tr = parseTransform(this.getAttribute("transform"));
|
||||
const dx = +tr[0] - d3.event.x,
|
||||
|
|
@ -186,15 +133,15 @@ function editBurg(id) {
|
|||
|
||||
function showGroupSection() {
|
||||
document.querySelectorAll("#burgBottom > button").forEach(el => (el.style.display = "none"));
|
||||
document.getElementById("burgGroupSection").style.display = "inline-block";
|
||||
byId("burgGroupSection").style.display = "inline-block";
|
||||
}
|
||||
|
||||
function hideGroupSection() {
|
||||
document.querySelectorAll("#burgBottom > button").forEach(el => (el.style.display = "inline-block"));
|
||||
document.getElementById("burgGroupSection").style.display = "none";
|
||||
document.getElementById("burgInputGroup").style.display = "none";
|
||||
document.getElementById("burgInputGroup").value = "";
|
||||
document.getElementById("burgSelectGroup").style.display = "inline-block";
|
||||
byId("burgGroupSection").style.display = "none";
|
||||
byId("burgInputGroup").style.display = "none";
|
||||
byId("burgInputGroup").value = "";
|
||||
byId("burgSelectGroup").style.display = "inline-block";
|
||||
}
|
||||
|
||||
function changeGroup() {
|
||||
|
|
@ -223,7 +170,7 @@ function editBurg(id) {
|
|||
.replace(/ /g, "_")
|
||||
.replace(/[^\w\s]/gi, "");
|
||||
|
||||
if (document.getElementById(group)) {
|
||||
if (byId(group)) {
|
||||
tip("Element with this id already exists. Please provide a unique name", false, "error");
|
||||
return;
|
||||
}
|
||||
|
|
@ -251,10 +198,10 @@ function editBurg(id) {
|
|||
// just rename if only 1 element left
|
||||
const count = elSelected.node().parentNode.childElementCount;
|
||||
if (oldGroup !== "cities" && oldGroup !== "towns" && count === 1) {
|
||||
document.getElementById("burgSelectGroup").selectedOptions[0].remove();
|
||||
document.getElementById("burgSelectGroup").options.add(new Option(group, group, false, true));
|
||||
byId("burgSelectGroup").selectedOptions[0].remove();
|
||||
byId("burgSelectGroup").options.add(new Option(group, group, false, true));
|
||||
toggleNewGroupInput();
|
||||
document.getElementById("burgInputGroup").value = "";
|
||||
byId("burgInputGroup").value = "";
|
||||
labelG.id = group;
|
||||
iconG.id = group;
|
||||
if (anchor) anchorG.id = group;
|
||||
|
|
@ -262,9 +209,9 @@ function editBurg(id) {
|
|||
}
|
||||
|
||||
// create new groups
|
||||
document.getElementById("burgSelectGroup").options.add(new Option(group, group, false, true));
|
||||
byId("burgSelectGroup").options.add(new Option(group, group, false, true));
|
||||
toggleNewGroupInput();
|
||||
document.getElementById("burgInputGroup").value = "";
|
||||
byId("burgInputGroup").value = "";
|
||||
|
||||
addBurgsGroup(group);
|
||||
moveBurgToGroup(id, group);
|
||||
|
|
@ -284,7 +231,9 @@ function editBurg(id) {
|
|||
alertMessage.innerHTML = /* html */ `Are you sure you want to remove ${
|
||||
basic || capital ? "all unlocked elements in the burg group" : "the entire burg group"
|
||||
}?
|
||||
<br />Please note that capital or locked burgs will not be deleted. <br /><br />Burgs to be removed: ${burgsToRemove.length}`;
|
||||
<br />Please note that capital or locked burgs will not be deleted. <br /><br />Burgs to be removed: ${
|
||||
burgsToRemove.length
|
||||
}`;
|
||||
$("#alert").dialog({
|
||||
resizable: false,
|
||||
title: "Remove burg group",
|
||||
|
|
@ -343,7 +292,10 @@ function editBurg(id) {
|
|||
|
||||
function changePopulation() {
|
||||
const id = +elSelected.attr("data-id");
|
||||
const burg = pack.burgs[id];
|
||||
|
||||
pack.burgs[id].population = rn(burgPopulation.value / populationRate / urbanization, 4);
|
||||
updateBurgPreview(burg);
|
||||
}
|
||||
|
||||
function toggleFeature() {
|
||||
|
|
@ -357,9 +309,9 @@ function editBurg(id) {
|
|||
if (burg[feature]) this.classList.remove("inactive");
|
||||
else if (!burg[feature]) this.classList.add("inactive");
|
||||
|
||||
if (burg.port) document.getElementById("burgEditAnchorStyle").style.display = "inline-block";
|
||||
else document.getElementById("burgEditAnchorStyle").style.display = "none";
|
||||
updateMFCGFrame(burg);
|
||||
if (burg.port) byId("burgEditAnchorStyle").style.display = "inline-block";
|
||||
else byId("burgEditAnchorStyle").style.display = "none";
|
||||
updateBurgPreview(burg);
|
||||
}
|
||||
|
||||
function toggleBurgLockButton() {
|
||||
|
|
@ -374,22 +326,22 @@ function editBurg(id) {
|
|||
const id = +elSelected.attr("data-id");
|
||||
const b = pack.burgs[id];
|
||||
if (b.lock) {
|
||||
document.getElementById("burgLock").classList.remove("icon-lock-open");
|
||||
document.getElementById("burgLock").classList.add("icon-lock");
|
||||
byId("burgLock").classList.remove("icon-lock-open");
|
||||
byId("burgLock").classList.add("icon-lock");
|
||||
} else {
|
||||
document.getElementById("burgLock").classList.remove("icon-lock");
|
||||
document.getElementById("burgLock").classList.add("icon-lock-open");
|
||||
byId("burgLock").classList.remove("icon-lock");
|
||||
byId("burgLock").classList.add("icon-lock-open");
|
||||
}
|
||||
}
|
||||
|
||||
function showStyleSection() {
|
||||
document.querySelectorAll("#burgBottom > button").forEach(el => (el.style.display = "none"));
|
||||
document.getElementById("burgStyleSection").style.display = "inline-block";
|
||||
byId("burgStyleSection").style.display = "inline-block";
|
||||
}
|
||||
|
||||
function hideStyleSection() {
|
||||
document.querySelectorAll("#burgBottom > button").forEach(el => (el.style.display = "inline-block"));
|
||||
document.getElementById("burgStyleSection").style.display = "none";
|
||||
byId("burgStyleSection").style.display = "none";
|
||||
}
|
||||
|
||||
function editGroupLabelStyle() {
|
||||
|
|
@ -407,38 +359,38 @@ function editBurg(id) {
|
|||
editStyle("anchors", g);
|
||||
}
|
||||
|
||||
function updateMFCGFrame(burg) {
|
||||
const mfcgURL = getMFCGlink(burg);
|
||||
document.getElementById("mfcgPreview").setAttribute("src", mfcgURL + "&preview=1");
|
||||
document.getElementById("mfcgLink").setAttribute("href", mfcgURL);
|
||||
function updateBurgPreview(burg) {
|
||||
const src = getBurgLink(burg) + "&preview=1";
|
||||
|
||||
// recreate object to force reload (Chrome bug)
|
||||
const container = byId("burgPreviewObject");
|
||||
container.innerHTML = "";
|
||||
const object = document.createElement("object");
|
||||
object.style.width = "100%";
|
||||
object.data = src;
|
||||
container.insertBefore(object, null);
|
||||
}
|
||||
|
||||
function changeSeed() {
|
||||
function openBurgLink() {
|
||||
const id = +elSelected.attr("data-id");
|
||||
const burg = pack.burgs[id];
|
||||
const burgSeed = +this.value;
|
||||
burg.MFCG = burgSeed;
|
||||
updateMFCGFrame(burg);
|
||||
|
||||
openURL(getBurgLink(burg));
|
||||
}
|
||||
|
||||
function randomizeSeed() {
|
||||
function changeBurgLink() {
|
||||
const id = +elSelected.attr("data-id");
|
||||
const burg = pack.burgs[id];
|
||||
const burgSeed = rand(1e9 - 1);
|
||||
burg.MFCG = burgSeed;
|
||||
updateMFCGFrame(burg);
|
||||
document.getElementById("mfcgBurgSeed").value = burgSeed;
|
||||
}
|
||||
|
||||
function addCustomMfcgLink() {
|
||||
const id = +elSelected.attr("data-id");
|
||||
const burg = pack.burgs[id];
|
||||
const message = "Enter custom link to the burg map. It can be a link to Medieval Fantasy City Generator or other tool. Keep empty to use MFCG seed";
|
||||
prompt(message, {default: burg.link || "", required: false}, link => {
|
||||
if (link) burg.link = link;
|
||||
else delete burg.link;
|
||||
updateMFCGFrame(burg);
|
||||
});
|
||||
prompt(
|
||||
"Provide custom link to the burg map. It can be a link to Medieval Fantasy City Generator, a different tool, or just an image. Leave empty to use the default map",
|
||||
{default: getBurgLink(burg), required: false},
|
||||
link => {
|
||||
if (link) burg.link = link;
|
||||
else delete burg.link;
|
||||
updateBurgPreview(burg);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function openEmblemEdit() {
|
||||
|
|
@ -447,16 +399,16 @@ function editBurg(id) {
|
|||
editEmblem("burg", "burgCOA" + id, burg);
|
||||
}
|
||||
|
||||
function toggleMFCGMap() {
|
||||
options.showMFCGMap = !options.showMFCGMap;
|
||||
document.getElementById("mfcgPreviewSection").style.display = options.showMFCGMap ? "block" : "none";
|
||||
document.getElementById("burgToggleMFCGMap").className = options.showMFCGMap ? "icon-map" : "icon-map-o";
|
||||
function toggleBurgPreview() {
|
||||
options.showBurgPreview = !options.showBurgPreview;
|
||||
byId("burgPreviewSection").style.display = options.showBurgPreview ? "block" : "none";
|
||||
byId("burgTogglePreview").className = options.showBurgPreview ? "icon-map" : "icon-map-o";
|
||||
}
|
||||
|
||||
function toggleRelocateBurg() {
|
||||
const toggler = document.getElementById("toggleCells");
|
||||
document.getElementById("burgRelocate").classList.toggle("pressed");
|
||||
if (document.getElementById("burgRelocate").classList.contains("pressed")) {
|
||||
const toggler = byId("toggleCells");
|
||||
byId("burgRelocate").classList.toggle("pressed");
|
||||
if (byId("burgRelocate").classList.contains("pressed")) {
|
||||
viewbox.style("cursor", "crosshair").on("click", relocateBurgOnClick);
|
||||
tip("Click on map to relocate burg. Hold Shift for continuous move", true);
|
||||
if (!layerIsOn("toggleCells")) {
|
||||
|
|
@ -576,8 +528,53 @@ function editBurg(id) {
|
|||
}
|
||||
|
||||
function closeBurgEditor() {
|
||||
document.getElementById("burgRelocate").classList.remove("pressed");
|
||||
byId("burgRelocate").classList.remove("pressed");
|
||||
burgLabels.selectAll("text").call(d3.drag().on("drag", null)).classed("draggable", false);
|
||||
unselect();
|
||||
}
|
||||
}
|
||||
|
||||
// in °C, array from -1 °C; source: https://en.wikipedia.org/wiki/List_of_cities_by_average_temperature
|
||||
function getTemperatureLikeness(temperature) {
|
||||
if (temperature < -5) return "Yakutsk";
|
||||
const cities = [
|
||||
"Snag (Yukon)",
|
||||
"Yellowknife (Canada)",
|
||||
"Okhotsk (Russia)",
|
||||
"Fairbanks (Alaska)",
|
||||
"Nuuk (Greenland)",
|
||||
"Murmansk", // -5 - 0
|
||||
"Arkhangelsk",
|
||||
"Anchorage",
|
||||
"Tromsø",
|
||||
"Reykjavik",
|
||||
"Riga",
|
||||
"Stockholm",
|
||||
"Halifax",
|
||||
"Prague",
|
||||
"Copenhagen",
|
||||
"London", // 1 - 10
|
||||
"Antwerp",
|
||||
"Paris",
|
||||
"Milan",
|
||||
"Batumi",
|
||||
"Rome",
|
||||
"Dubrovnik",
|
||||
"Lisbon",
|
||||
"Barcelona",
|
||||
"Marrakesh",
|
||||
"Alexandria", // 11 - 20
|
||||
"Tegucigalpa",
|
||||
"Guangzhou",
|
||||
"Rio de Janeiro",
|
||||
"Dakar",
|
||||
"Miami",
|
||||
"Jakarta",
|
||||
"Mogadishu",
|
||||
"Bangkok",
|
||||
"Aden",
|
||||
"Khartoum"
|
||||
]; // 21 - 30
|
||||
if (temperature > 30) return "Mecca";
|
||||
return cities[temperature + 5] || null;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
"use strict";
|
||||
function overviewBurgs(options = {stateId: null, cultureId: null}) {
|
||||
function overviewBurgs(settings = {stateId: null, cultureId: null}) {
|
||||
if (customization) return;
|
||||
closeDialogs("#burgsOverview, .stable");
|
||||
if (!layerIsOn("toggleIcons")) toggleIcons();
|
||||
|
|
@ -37,7 +37,6 @@ function overviewBurgs(options = {stateId: null, cultureId: null}) {
|
|||
byId("burgGroupAssign").addEventListener("click", burgGroupAssignInBulk);
|
||||
byId("burgsLockAll").addEventListener("click", toggleLockAll);
|
||||
byId("burgsRemoveAll").addEventListener("click", triggerAllBurgsRemove);
|
||||
byId("burgsInvertLock").addEventListener("click", invertLock);
|
||||
|
||||
function refreshBurgsEditor() {
|
||||
updateFilter();
|
||||
|
|
@ -46,7 +45,7 @@ function overviewBurgs(options = {stateId: null, cultureId: null}) {
|
|||
|
||||
function updateFilter() {
|
||||
const stateFilter = byId("burgsFilterState");
|
||||
const selectedState = options.stateId !== null ? options.stateId : stateFilter.value || -1;
|
||||
const selectedState = settings.stateId !== null ? settings.stateId : stateFilter.value || -1;
|
||||
stateFilter.options.length = 0; // remove all options
|
||||
stateFilter.options.add(new Option("all", -1, false, selectedState === -1));
|
||||
stateFilter.options.add(new Option(pack.states[0].name, 0, false, selectedState === 0));
|
||||
|
|
@ -54,7 +53,7 @@ function overviewBurgs(options = {stateId: null, cultureId: null}) {
|
|||
statesSorted.forEach(s => stateFilter.options.add(new Option(s.name, s.i, false, s.i == selectedState)));
|
||||
|
||||
const cultureFilter = byId("burgsFilterCulture");
|
||||
const selectedCulture = options.cultureId !== null ? options.cultureId : cultureFilter.value || -1;
|
||||
const selectedCulture = settings.cultureId !== null ? settings.cultureId : cultureFilter.value || -1;
|
||||
cultureFilter.options.length = 0; // remove all options
|
||||
cultureFilter.options.add(new Option(`all`, -1, false, selectedCulture === -1));
|
||||
cultureFilter.options.add(new Option(pack.cultures[0].name, 0, false, selectedCulture === 0));
|
||||
|
|
@ -280,7 +279,8 @@ function overviewBurgs(options = {stateId: null, cultureId: null}) {
|
|||
|
||||
function addBurgOnClick() {
|
||||
const point = d3.mouse(this);
|
||||
const cell = findCell(point[0], point[1]);
|
||||
const cell = findCell(...point);
|
||||
|
||||
if (pack.cells.h[cell] < 20)
|
||||
return tip("You cannot place state into the water. Please click on a land cell", false, "error");
|
||||
if (pack.cells.burg[cell])
|
||||
|
|
@ -481,10 +481,7 @@ function overviewBurgs(options = {stateId: null, cultureId: null}) {
|
|||
}
|
||||
|
||||
function downloadBurgsData() {
|
||||
let data = `Id,Burg,Province,Province Full Name,State,State Full Name,Culture,Religion,Population,X,Y,Latitude,Longitude,Elevation (${heightUnit.value}),Capital,Port,Citadel,Walls,Plaza,Temple,Shanty Town`; // headers
|
||||
if (options.showMFCGMap) data += `,City Generator Link`;
|
||||
data += "\n";
|
||||
|
||||
let data = `Id,Burg,Province,Province Full Name,State,State Full Name,Culture,Religion,Population,X,Y,Latitude,Longitude,Elevation (${heightUnit.value}),Temperature,Temperature likeness,Capital,Port,Citadel,Walls,Plaza,Temple,Shanty Town,Emblem,City Generator Link\n`; // headers
|
||||
const valid = pack.burgs.filter(b => b.i && !b.removed); // all valid burgs
|
||||
|
||||
valid.forEach(b => {
|
||||
|
|
@ -505,6 +502,9 @@ function overviewBurgs(options = {stateId: null, cultureId: null}) {
|
|||
data += getLatitude(b.y, 2) + ",";
|
||||
data += getLongitude(b.x, 2) + ",";
|
||||
data += parseInt(getHeight(pack.cells.h[b.cell])) + ",";
|
||||
const temperature = grid.cells.temp[pack.cells.g[b.cell]];
|
||||
data += convertTemperature(temperature) + ",";
|
||||
data += getTemperatureLikeness(temperature) + ",";
|
||||
|
||||
// add status data
|
||||
data += b.capital ? "capital," : ",";
|
||||
|
|
@ -514,7 +514,9 @@ function overviewBurgs(options = {stateId: null, cultureId: null}) {
|
|||
data += b.plaza ? "plaza," : ",";
|
||||
data += b.temple ? "temple," : ",";
|
||||
data += b.shanty ? "shanty town," : ",";
|
||||
if (options.showMFCGMap) data += getMFCGlink(b);
|
||||
data += b.coa ? JSON.stringify(b.coa).replace(/"/g, "").replace(/,/g, ";") + "," : ",";
|
||||
data += getBurgLink(b);
|
||||
|
||||
data += "\n";
|
||||
});
|
||||
|
||||
|
|
@ -628,11 +630,6 @@ function overviewBurgs(options = {stateId: null, cultureId: null}) {
|
|||
burgsOverviewAddLines();
|
||||
}
|
||||
|
||||
function invertLock() {
|
||||
pack.burgs = pack.burgs.map(burg => ({...burg, lock: !burg.lock}));
|
||||
burgsOverviewAddLines();
|
||||
}
|
||||
|
||||
function toggleLockAll() {
|
||||
const activeBurgs = pack.burgs.filter(b => b.i && !b.removed);
|
||||
const allLocked = activeBurgs.every(burg => burg.lock);
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ function clicked() {
|
|||
|
||||
if (grand.id === "emblems") editEmblem();
|
||||
else if (parent.id === "rivers") editRiver(el.id);
|
||||
else if (grand.id === "routes") editRoute();
|
||||
else if (grand.id === "routes") editRoute(el.id);
|
||||
else if (el.tagName === "tspan" && grand.parentNode.parentNode.id === "labels") editLabel();
|
||||
else if (grand.id === "burgLabels") editBurg();
|
||||
else if (grand.id === "burgIcons") editBurg();
|
||||
|
|
@ -132,27 +132,43 @@ function applySorting(headers) {
|
|||
}
|
||||
|
||||
function addBurg(point) {
|
||||
const cells = pack.cells;
|
||||
const x = rn(point[0], 2),
|
||||
y = rn(point[1], 2);
|
||||
const cell = findCell(x, point[1]);
|
||||
const i = pack.burgs.length;
|
||||
const culture = cells.culture[cell];
|
||||
const name = Names.getCulture(culture);
|
||||
const state = cells.state[cell];
|
||||
const feature = cells.f[cell];
|
||||
const {cells, states} = pack;
|
||||
const x = rn(point[0], 2);
|
||||
const y = rn(point[1], 2);
|
||||
|
||||
const temple = pack.states[state].form === "Theocracy";
|
||||
const population = Math.max((cells.s[cell] + cells.road[cell]) / 3 + i / 1000 + (cell % 100) / 1000, 0.1);
|
||||
const type = BurgsAndStates.getType(cell, false);
|
||||
const cellId = findCell(x, y);
|
||||
const i = pack.burgs.length;
|
||||
const culture = cells.culture[cellId];
|
||||
const name = Names.getCulture(culture);
|
||||
const state = cells.state[cellId];
|
||||
const feature = cells.f[cellId];
|
||||
|
||||
const population = Math.max(cells.s[cellId] / 3 + i / 1000 + (cellId % 100) / 1000, 0.1);
|
||||
const type = BurgsAndStates.getType(cellId, false);
|
||||
|
||||
// generate emblem
|
||||
const coa = COA.generate(pack.states[state].coa, 0.25, null, type);
|
||||
const coa = COA.generate(states[state].coa, 0.25, null, type);
|
||||
coa.shield = COA.getShield(culture, state);
|
||||
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});
|
||||
cells.burg[cell] = i;
|
||||
const burg = {
|
||||
name,
|
||||
cell: cellId,
|
||||
x,
|
||||
y,
|
||||
state,
|
||||
i,
|
||||
culture,
|
||||
feature,
|
||||
capital: 0,
|
||||
port: 0,
|
||||
temple: 0,
|
||||
population,
|
||||
coa,
|
||||
type
|
||||
};
|
||||
pack.burgs.push(burg);
|
||||
cells.burg[cellId] = i;
|
||||
|
||||
const townSize = burgIcons.select("#towns").attr("size") || 0.5;
|
||||
burgIcons
|
||||
|
|
@ -173,7 +189,17 @@ function addBurg(point) {
|
|||
.attr("dy", `${townSize * -1.5}px`)
|
||||
.text(name);
|
||||
|
||||
BurgsAndStates.defineBurgFeatures(pack.burgs[i]);
|
||||
BurgsAndStates.defineBurgFeatures(burg);
|
||||
|
||||
const newRoute = Routes.connect(cellId);
|
||||
if (newRoute && layerIsOn("toggleRoutes")) {
|
||||
routes
|
||||
.select("#" + newRoute.group)
|
||||
.append("path")
|
||||
.attr("d", Routes.getPath(newRoute))
|
||||
.attr("id", "route" + newRoute.i);
|
||||
}
|
||||
|
||||
return i;
|
||||
}
|
||||
|
||||
|
|
@ -223,18 +249,19 @@ function addBurgsGroup(group) {
|
|||
}
|
||||
|
||||
function removeBurg(id) {
|
||||
const label = document.querySelector("#burgLabels [data-id='" + id + "']");
|
||||
const icon = document.querySelector("#burgIcons [data-id='" + id + "']");
|
||||
const anchor = document.querySelector("#anchors [data-id='" + id + "']");
|
||||
if (label) label.remove();
|
||||
if (icon) icon.remove();
|
||||
if (anchor) anchor.remove();
|
||||
document.querySelector("#burgLabels [data-id='" + id + "']")?.remove();
|
||||
document.querySelector("#burgIcons [data-id='" + id + "']")?.remove();
|
||||
document.querySelector("#anchors [data-id='" + id + "']")?.remove();
|
||||
|
||||
const cells = pack.cells;
|
||||
const burg = pack.burgs[id];
|
||||
|
||||
const cells = pack.cells,
|
||||
burg = pack.burgs[id];
|
||||
burg.removed = true;
|
||||
cells.burg[burg.cell] = 0;
|
||||
|
||||
const noteId = notes.findIndex(note => note.id === `burg${id}`);
|
||||
if (noteId !== -1) notes.splice(noteId, 1);
|
||||
|
||||
if (burg.coa) {
|
||||
const coaId = "burgCOA" + id;
|
||||
if (byId(coaId)) byId(coaId).remove();
|
||||
|
|
@ -243,25 +270,22 @@ function removeBurg(id) {
|
|||
}
|
||||
}
|
||||
|
||||
function toggleCapital(burg) {
|
||||
const state = pack.burgs[burg].state;
|
||||
if (!state) {
|
||||
tip("Neutral lands cannot have a capital", false, "error");
|
||||
return;
|
||||
}
|
||||
if (pack.burgs[burg].capital) {
|
||||
tip("To change capital please assign a capital status to another burg of this state", false, "error");
|
||||
return;
|
||||
}
|
||||
const old = pack.states[state].capital;
|
||||
function toggleCapital(burgId) {
|
||||
const {burgs, states} = pack;
|
||||
if (burgs[burgId].capital)
|
||||
return tip("To change capital please assign a capital status to another burg of this state", false, "error");
|
||||
|
||||
// change statuses
|
||||
pack.states[state].capital = burg;
|
||||
pack.states[state].center = pack.burgs[burg].cell;
|
||||
pack.burgs[burg].capital = 1;
|
||||
pack.burgs[old].capital = 0;
|
||||
moveBurgToGroup(burg, "cities");
|
||||
moveBurgToGroup(old, "towns");
|
||||
const stateId = burgs[burgId].state;
|
||||
if (!stateId) return tip("Neutral lands cannot have a capital", false, "error");
|
||||
|
||||
const prevCapitalId = states[stateId].capital;
|
||||
states[stateId].capital = burgId;
|
||||
states[stateId].center = burgs[burgId].cell;
|
||||
burgs[burgId].capital = 1;
|
||||
burgs[prevCapitalId].capital = 0;
|
||||
|
||||
moveBurgToGroup(burgId, "cities");
|
||||
moveBurgToGroup(prevCapitalId, "towns");
|
||||
}
|
||||
|
||||
function togglePort(burg) {
|
||||
|
|
@ -291,16 +315,20 @@ function togglePort(burg) {
|
|||
.attr("height", size);
|
||||
}
|
||||
|
||||
function getBurgSeed(burg) {
|
||||
return burg.MFCG || Number(`${seed}${String(burg.i).padStart(4, 0)}`);
|
||||
}
|
||||
|
||||
function getMFCGlink(burg) {
|
||||
function getBurgLink(burg) {
|
||||
if (burg.link) return burg.link;
|
||||
|
||||
const population = burg.population * populationRate * urbanization;
|
||||
if (population >= options.villageMaxPopulation || burg.citadel || burg.walls || burg.temple || burg.shanty)
|
||||
return createMfcgLink(burg);
|
||||
|
||||
return createVillageGeneratorLink(burg);
|
||||
}
|
||||
|
||||
function createMfcgLink(burg) {
|
||||
const {cells} = pack;
|
||||
const {i, name, population: burgPopulation, cell} = burg;
|
||||
const seed = getBurgSeed(burg);
|
||||
const burgSeed = burg.MFCG || seed + String(burg.i).padStart(4, 0);
|
||||
|
||||
const sizeRaw = 2.13 * Math.pow((burgPopulation * populationRate) / urbanDensity, 0.385);
|
||||
const size = minmax(Math.ceil(sizeRaw), 6, 100);
|
||||
|
|
@ -308,35 +336,35 @@ function getMFCGlink(burg) {
|
|||
|
||||
const river = cells.r[cell] ? 1 : 0;
|
||||
const coast = Number(burg.port > 0);
|
||||
const sea = coast && cells.haven[cell] ? getSeaDirections(cell) : null;
|
||||
const sea = (() => {
|
||||
if (!coast || !cells.haven[cell]) return null;
|
||||
|
||||
// calculate see direction: 0 = south, 0.5 = west, 1 = north, 1.5 = east
|
||||
const p1 = cells.p[cell];
|
||||
const p2 = cells.p[cells.haven[cell]];
|
||||
let deg = (Math.atan2(p2[1] - p1[1], p2[0] - p1[0]) * 180) / Math.PI - 90;
|
||||
if (deg < 0) deg += 360;
|
||||
return rn(normalize(deg, 0, 360) * 2, 2);
|
||||
})();
|
||||
|
||||
const biome = cells.biome[cell];
|
||||
const arableBiomes = river ? [1, 2, 3, 4, 5, 6, 7, 8] : [5, 6, 7, 8];
|
||||
const farms = +arableBiomes.includes(biome);
|
||||
const farms = +arableBiomes.includes(cells.biome[cell]);
|
||||
|
||||
const citadel = +burg.citadel;
|
||||
const urban_castle = +(citadel && each(2)(i));
|
||||
|
||||
const hub = +cells.road[cell] > 50;
|
||||
|
||||
const hub = Routes.isCrossroad(cell);
|
||||
const walls = +burg.walls;
|
||||
const plaza = +burg.plaza;
|
||||
const temple = +burg.temple;
|
||||
const shantytown = +burg.shanty;
|
||||
|
||||
function getSeaDirections(i) {
|
||||
const p1 = cells.p[i];
|
||||
const p2 = cells.p[cells.haven[i]];
|
||||
let deg = (Math.atan2(p2[1] - p1[1], p2[0] - p1[0]) * 180) / Math.PI - 90;
|
||||
if (deg < 0) deg += 360;
|
||||
return rn(normalize(deg, 0, 360) * 2, 2); // 0 = south, 0.5 = west, 1 = north, 1.5 = east
|
||||
}
|
||||
|
||||
const parameters = {
|
||||
const url = new URL("https://watabou.github.io/city-generator/");
|
||||
url.search = new URLSearchParams({
|
||||
name,
|
||||
population,
|
||||
size,
|
||||
seed,
|
||||
seed: burgSeed,
|
||||
river,
|
||||
coast,
|
||||
farms,
|
||||
|
|
@ -348,14 +376,62 @@ function getMFCGlink(burg) {
|
|||
walls,
|
||||
shantytown,
|
||||
gates: -1
|
||||
};
|
||||
const url = new URL("https://watabou.github.io/city-generator/");
|
||||
url.search = new URLSearchParams(parameters);
|
||||
});
|
||||
if (sea) url.searchParams.append("sea", sea);
|
||||
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function createVillageGeneratorLink(burg) {
|
||||
const {cells, features} = pack;
|
||||
const {i, population, cell} = burg;
|
||||
|
||||
const pop = rn(population * populationRate * urbanization);
|
||||
const burgSeed = seed + String(i).padStart(4, 0);
|
||||
const tags = [];
|
||||
|
||||
if (cells.r[cell] && cells.haven[cell]) tags.push("estuary");
|
||||
else if (cells.haven[cell] && features[cells.f[cell]].cells === 1) tags.push("island,district");
|
||||
else if (burg.port) tags.push("coast");
|
||||
else if (cells.conf[cell]) tags.push("confluence");
|
||||
else if (cells.r[cell]) tags.push("river");
|
||||
else if (pop < 200 && each(4)(cell)) tags.push("pond");
|
||||
|
||||
const connections = pack.cells.routes[cell] || {};
|
||||
const roads = Object.values(connections).filter(routeId => {
|
||||
const route = pack.routes[routeId];
|
||||
return route.group === "roads" || route.group === "trails";
|
||||
}).length;
|
||||
tags.push(roads > 1 ? "highway" : roads === 1 ? "dead end" : "isolated");
|
||||
|
||||
const biome = cells.biome[cell];
|
||||
const arableBiomes = cells.r[cell] ? [1, 2, 3, 4, 5, 6, 7, 8] : [5, 6, 7, 8];
|
||||
if (!arableBiomes.includes(biome)) tags.push("uncultivated");
|
||||
else if (each(6)(cell)) tags.push("farmland");
|
||||
|
||||
const temp = grid.cells.temp[cells.g[cell]];
|
||||
if (temp <= 0 || temp > 28 || (temp > 25 && each(3)(cell))) tags.push("no orchards");
|
||||
|
||||
if (!burg.plaza) tags.push("no square");
|
||||
|
||||
if (pop < 100) tags.push("sparse");
|
||||
else if (pop > 300) tags.push("dense");
|
||||
|
||||
const width = (() => {
|
||||
if (pop > 1500) return 1600;
|
||||
if (pop > 1000) return 1400;
|
||||
if (pop > 500) return 1000;
|
||||
if (pop > 200) return 800;
|
||||
if (pop > 100) return 600;
|
||||
return 400;
|
||||
})();
|
||||
const height = rn(width / 2.2);
|
||||
|
||||
const url = new URL("https://watabou.github.io/village-generator/");
|
||||
url.search = new URLSearchParams({pop, name: "", seed: burgSeed, width, height, tags});
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
// draw legend box
|
||||
function drawLegend(name, data) {
|
||||
legend.selectAll("*").remove(); // fully redraw every time
|
||||
|
|
@ -1096,12 +1172,12 @@ function selectIcon(initial, callback) {
|
|||
input.oninput = e => callback(input.value);
|
||||
table.onclick = e => {
|
||||
if (e.target.tagName === "TD") {
|
||||
input.value = e.target.innerHTML;
|
||||
input.value = e.target.textContent;
|
||||
callback(input.value);
|
||||
}
|
||||
};
|
||||
table.onmouseover = e => {
|
||||
if (e.target.tagName === "TD") tip(`Click to select ${e.target.innerHTML} icon`);
|
||||
if (e.target.tagName === "TD") tip(`Click to select ${e.target.textContent} icon`);
|
||||
};
|
||||
|
||||
$("#iconSelector").dialog({
|
||||
|
|
@ -1125,7 +1201,6 @@ function getAreaUnit(squareMark = "²") {
|
|||
}
|
||||
|
||||
function getArea(rawArea) {
|
||||
const distanceScale = byId("distanceScaleInput")?.value;
|
||||
return rawArea * distanceScale ** 2;
|
||||
}
|
||||
|
||||
|
|
@ -1176,18 +1251,18 @@ function refreshAllEditors() {
|
|||
// dynamically loaded editors
|
||||
async function editStates() {
|
||||
if (customization) return;
|
||||
const Editor = await import("../dynamic/editors/states-editor.js?v=1.93.10");
|
||||
const Editor = await import("../dynamic/editors/states-editor.js?v=1.99.00");
|
||||
Editor.open();
|
||||
}
|
||||
|
||||
async function editCultures() {
|
||||
if (customization) return;
|
||||
const Editor = await import("../dynamic/editors/cultures-editor.js?v=1.95.04");
|
||||
const Editor = await import("../dynamic/editors/cultures-editor.js?v=1.96.01");
|
||||
Editor.open();
|
||||
}
|
||||
|
||||
async function editReligions() {
|
||||
if (customization) return;
|
||||
const Editor = await import("../dynamic/editors/religions-editor.js?v=1.89.10");
|
||||
const Editor = await import("../dynamic/editors/religions-editor.js?v=1.96.00");
|
||||
Editor.open();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,43 +1,14 @@
|
|||
"use strict";
|
||||
|
||||
function showEPForRoute(node) {
|
||||
const points = [];
|
||||
debug
|
||||
.select("#controlPoints")
|
||||
.selectAll("circle")
|
||||
.each(function () {
|
||||
const i = findCell(this.getAttribute("cx"), this.getAttribute("cy"));
|
||||
points.push(i);
|
||||
});
|
||||
|
||||
const routeLen = node.getTotalLength() * distanceScaleInput.value;
|
||||
showElevationProfile(points, routeLen, false);
|
||||
}
|
||||
|
||||
function showEPForRiver(node) {
|
||||
const points = [];
|
||||
debug
|
||||
.select("#controlPoints")
|
||||
.selectAll("circle")
|
||||
.each(function () {
|
||||
const i = findCell(this.getAttribute("cx"), this.getAttribute("cy"));
|
||||
points.push(i);
|
||||
});
|
||||
|
||||
const riverLen = (node.getTotalLength() / 2) * distanceScaleInput.value;
|
||||
showElevationProfile(points, riverLen, true);
|
||||
}
|
||||
|
||||
// data is an array of cell indexes, routeLen is the distance (in actual metres/feet), isRiver should be true for rivers, false otherwise
|
||||
function showElevationProfile(data, routeLen, isRiver) {
|
||||
// data is an array of cell indexes, routeLen is the distance (in actual metres/feet), isRiver should be true for rivers, false otherwise
|
||||
document.getElementById("epScaleRange").addEventListener("change", draw);
|
||||
document.getElementById("epCurve").addEventListener("change", draw);
|
||||
document.getElementById("epSave").addEventListener("click", downloadCSV);
|
||||
byId("epScaleRange").on("change", draw);
|
||||
byId("epCurve").on("change", draw);
|
||||
byId("epSave").on("click", downloadCSV);
|
||||
|
||||
$("#elevationProfile").dialog({
|
||||
title: "Elevation profile",
|
||||
resizable: false,
|
||||
width: window.width,
|
||||
close: closeElevationProfile,
|
||||
position: {my: "left top", at: "left+20 bottom-500", of: window, collision: "fit"}
|
||||
});
|
||||
|
|
@ -45,18 +16,20 @@ function showElevationProfile(data, routeLen, isRiver) {
|
|||
// prevent river graphs from showing rivers as flowing uphill - remember the general slope
|
||||
let slope = 0;
|
||||
if (isRiver) {
|
||||
if (pack.cells.h[data[0]] < pack.cells.h[data[data.length - 1]]) {
|
||||
const firstCellHeight = pack.cells.h[data.at(0)];
|
||||
const lastCellHeight = pack.cells.h[data.at(-1)];
|
||||
if (firstCellHeight < lastCellHeight) {
|
||||
slope = 1; // up-hill
|
||||
} else if (pack.cells.h[data[0]] > pack.cells.h[data[data.length - 1]]) {
|
||||
} else if (firstCellHeight > lastCellHeight) {
|
||||
slope = -1; // down-hill
|
||||
}
|
||||
}
|
||||
|
||||
const chartWidth = window.innerWidth - 180,
|
||||
chartHeight = 300; // height of our land/sea profile, excluding the biomes data below
|
||||
const xOffset = 80,
|
||||
yOffset = 80; // this is our drawing starting point from top-left (y = 0) of SVG
|
||||
const biomesHeight = 40;
|
||||
const chartWidth = window.innerWidth - 200;
|
||||
const chartHeight = 300;
|
||||
const xOffset = 80;
|
||||
const yOffset = 80;
|
||||
const biomesHeight = 10;
|
||||
|
||||
let lastBurgIndex = 0;
|
||||
let lastBurgCell = 0;
|
||||
|
|
@ -109,8 +82,8 @@ function showElevationProfile(data, routeLen, isRiver) {
|
|||
draw();
|
||||
|
||||
function downloadCSV() {
|
||||
let data =
|
||||
"Point,X,Y,Cell,Height,Height value,Population,Burg,Burg population,Biome,Biome color,Culture,Culture color,Religion,Religion color,Province,Province color,State,State color\n"; // headers
|
||||
let csv =
|
||||
"Id,x,y,lat,lon,Cell,Height,Height value,Population,Burg,Burg population,Biome,Biome color,Culture,Culture color,Religion,Religion color,Province,Province color,State,State color\n"; // headers
|
||||
|
||||
for (let k = 0; k < chartData.points.length; k++) {
|
||||
let cell = chartData.cell[k];
|
||||
|
|
@ -123,35 +96,39 @@ function showElevationProfile(data, routeLen, isRiver) {
|
|||
let pop = pack.cells.pop[cell];
|
||||
let h = pack.cells.h[cell];
|
||||
|
||||
data += k + 1 + ",";
|
||||
data += chartData.points[k][0] + ",";
|
||||
data += chartData.points[k][1] + ",";
|
||||
data += cell + ",";
|
||||
data += getHeight(h) + ",";
|
||||
data += h + ",";
|
||||
data += rn(pop * populationRate) + ",";
|
||||
csv += k + 1 + ",";
|
||||
const [x, y] = pack.cells.p[data[k]];
|
||||
csv += x + ",";
|
||||
csv += y + ",";
|
||||
const lat = getLatitude(y, 2);
|
||||
const lon = getLongitude(x, 2);
|
||||
csv += lat + ",";
|
||||
csv += lon + ",";
|
||||
csv += cell + ",";
|
||||
csv += getHeight(h) + ",";
|
||||
csv += h + ",";
|
||||
csv += rn(pop * populationRate) + ",";
|
||||
if (burg) {
|
||||
data += pack.burgs[burg].name + ",";
|
||||
data += pack.burgs[burg].population * populationRate * urbanization + ",";
|
||||
csv += pack.burgs[burg].name + ",";
|
||||
csv += pack.burgs[burg].population * populationRate * urbanization + ",";
|
||||
} else {
|
||||
data += ",0,";
|
||||
csv += ",0,";
|
||||
}
|
||||
data += biomesData.name[biome] + ",";
|
||||
data += biomesData.color[biome] + ",";
|
||||
data += pack.cultures[culture].name + ",";
|
||||
data += pack.cultures[culture].color + ",";
|
||||
data += pack.religions[religion].name + ",";
|
||||
data += pack.religions[religion].color + ",";
|
||||
data += pack.provinces[province].name + ",";
|
||||
data += pack.provinces[province].color + ",";
|
||||
data += pack.states[state].name + ",";
|
||||
data += pack.states[state].color + ",";
|
||||
|
||||
data = data + "\n";
|
||||
csv += biomesData.name[biome] + ",";
|
||||
csv += biomesData.color[biome] + ",";
|
||||
csv += pack.cultures[culture].name + ",";
|
||||
csv += pack.cultures[culture].color + ",";
|
||||
csv += pack.religions[religion].name + ",";
|
||||
csv += pack.religions[religion].color + ",";
|
||||
csv += pack.provinces[province].name + ",";
|
||||
csv += pack.provinces[province].color + ",";
|
||||
csv += pack.states[state].name + ",";
|
||||
csv += pack.states[state].color + ",";
|
||||
csv += "\n";
|
||||
}
|
||||
|
||||
const name = getFileName("elevation profile") + ".csv";
|
||||
downloadFile(data, name);
|
||||
downloadFile(csv, name);
|
||||
}
|
||||
|
||||
function draw() {
|
||||
|
|
@ -170,7 +147,7 @@ function showElevationProfile(data, routeLen, isRiver) {
|
|||
chartData.points.push([xscale(i) + xOffset, yscale(chartData.height[i]) + yOffset]);
|
||||
}
|
||||
|
||||
document.getElementById("elevationGraph").innerHTML = "";
|
||||
byId("elevationGraph").innerHTML = "";
|
||||
|
||||
const chart = d3
|
||||
.select("#elevationGraph")
|
||||
|
|
@ -193,8 +170,15 @@ function showElevationProfile(data, routeLen, isRiver) {
|
|||
.attr("d", "M0,0 V4 L2,2 Z")
|
||||
.attr("fill", "darkgray");
|
||||
|
||||
let colors = getColorScheme(terrs.attr("scheme"));
|
||||
const landdef = chart.select("defs").append("linearGradient").attr("id", "landdef").attr("x1", "0%").attr("y1", "0%").attr("x2", "0%").attr("y2", "100%");
|
||||
const colors = getColorScheme("natural");
|
||||
const landdef = chart
|
||||
.select("defs")
|
||||
.append("linearGradient")
|
||||
.attr("id", "landdef")
|
||||
.attr("x1", "0%")
|
||||
.attr("y1", "0%")
|
||||
.attr("x2", "0%")
|
||||
.attr("y2", "100%");
|
||||
|
||||
if (chartData.mah == chartData.mih) {
|
||||
landdef
|
||||
|
|
@ -247,7 +231,14 @@ function showElevationProfile(data, routeLen, isRiver) {
|
|||
path += " L" + parseInt(xscale(extra.length) + +xOffset) + "," + parseInt(yscale(0) + +yOffset);
|
||||
path += " L" + parseInt(xscale(0) + +xOffset) + "," + parseInt(yscale(0) + +yOffset);
|
||||
path += "Z";
|
||||
chart.append("g").attr("id", "epland").append("path").attr("d", path).attr("stroke", "purple").attr("stroke-width", "0").attr("fill", "url(#landdef)");
|
||||
chart
|
||||
.append("g")
|
||||
.attr("id", "epland")
|
||||
.append("path")
|
||||
.attr("d", path)
|
||||
.attr("stroke", "purple")
|
||||
.attr("stroke-width", "0")
|
||||
.attr("fill", "url(#landdef)");
|
||||
|
||||
// biome / heights
|
||||
let g = chart.append("g").attr("id", "epbiomes");
|
||||
|
|
@ -289,7 +280,14 @@ function showElevationProfile(data, routeLen, isRiver) {
|
|||
chartData.cell[k] +
|
||||
")";
|
||||
|
||||
g.append("rect").attr("stroke", c).attr("fill", c).attr("x", x).attr("y", y).attr("width", xscale(1)).attr("height", 15).attr("data-tip", dataTip);
|
||||
g.append("rect")
|
||||
.attr("stroke", c)
|
||||
.attr("fill", c)
|
||||
.attr("x", x)
|
||||
.attr("y", y)
|
||||
.attr("width", xscale(1))
|
||||
.attr("height", biomesHeight)
|
||||
.attr("data-tip", dataTip);
|
||||
}
|
||||
|
||||
const xAxis = d3
|
||||
|
|
@ -314,10 +312,7 @@ function showElevationProfile(data, routeLen, isRiver) {
|
|||
.attr("transform", "translate(" + xOffset + "," + parseInt(chartHeight + +yOffset + 20) + ")")
|
||||
.call(xAxis)
|
||||
.selectAll("text")
|
||||
.style("text-anchor", "center")
|
||||
.attr("transform", function (d) {
|
||||
return "rotate(0)"; // used to rotate labels, - anti-clockwise, + clockwise
|
||||
});
|
||||
.style("text-anchor", "center");
|
||||
|
||||
chart
|
||||
.append("g")
|
||||
|
|
@ -366,12 +361,22 @@ function showElevationProfile(data, routeLen, isRiver) {
|
|||
.attr("x", x1)
|
||||
.attr("y", y1)
|
||||
.attr("text-anchor", "middle");
|
||||
document.getElementById("ep" + b).innerHTML = pack.burgs[b].name;
|
||||
byId("ep" + b).innerHTML = pack.burgs[b].name;
|
||||
|
||||
// arrow from burg name to graph line
|
||||
g.append("path")
|
||||
.attr("id", "eparrow" + b)
|
||||
.attr("d", "M" + x1.toString() + "," + (y1 + 3).toString() + "L" + x1.toString() + "," + parseInt(chartData.points[k][1] - 3).toString())
|
||||
.attr(
|
||||
"d",
|
||||
"M" +
|
||||
x1.toString() +
|
||||
"," +
|
||||
(y1 + 3).toString() +
|
||||
"L" +
|
||||
x1.toString() +
|
||||
"," +
|
||||
parseInt(chartData.points[k][1] - 3).toString()
|
||||
)
|
||||
.attr("stroke", "darkgray")
|
||||
.attr("fill", "lightgray")
|
||||
.attr("stroke-width", "1")
|
||||
|
|
@ -381,10 +386,10 @@ function showElevationProfile(data, routeLen, isRiver) {
|
|||
}
|
||||
|
||||
function closeElevationProfile() {
|
||||
document.getElementById("epScaleRange").removeEventListener("change", draw);
|
||||
document.getElementById("epCurve").removeEventListener("change", draw);
|
||||
document.getElementById("epSave").removeEventListener("click", downloadCSV);
|
||||
document.getElementById("elevationGraph").innerHTML = "";
|
||||
byId("epScaleRange").removeEventListener("change", draw);
|
||||
byId("epCurve").removeEventListener("change", draw);
|
||||
byId("epSave").removeEventListener("click", downloadCSV);
|
||||
byId("elevationGraph").innerHTML = "";
|
||||
modules.elevation = false;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -67,9 +67,9 @@ function showDataTip(event) {
|
|||
function showElementLockTip(event) {
|
||||
const locked = event?.target?.classList?.contains("icon-lock");
|
||||
if (locked) {
|
||||
tip("Click to unlock the element and allow it to be changed by regeneration tools");
|
||||
tip("Locked. Click to unlock the element and allow it to be changed by regeneration tools");
|
||||
} else {
|
||||
tip("Click to lock the element and prevent changes to it by regeneration tools");
|
||||
tip("Unlocked. Click to lock the element and prevent changes to it by regeneration tools");
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -151,7 +151,12 @@ function showMapTooltip(point, e, i, g) {
|
|||
return;
|
||||
}
|
||||
|
||||
if (group === "routes") return tip("Click to edit the Route");
|
||||
if (group === "routes") {
|
||||
const routeId = +e.target.id.slice(5);
|
||||
const name = pack.routes[routeId]?.name;
|
||||
if (name) return tip(`${name}. Click to edit the Route`);
|
||||
return tip("Click to edit the Route");
|
||||
}
|
||||
|
||||
if (group === "terrain") return tip("Click to edit the Relief Icon");
|
||||
|
||||
|
|
@ -285,7 +290,7 @@ function toDMS(coord, c) {
|
|||
const minutes = Math.floor(minutesNotTruncated);
|
||||
const seconds = Math.floor((minutesNotTruncated - minutes) * 60);
|
||||
const cardinal = c === "lat" ? (coord >= 0 ? "N" : "S") : coord >= 0 ? "E" : "W";
|
||||
return degrees + "° " + minutes + "′ " + seconds + "″ " + cardinal;
|
||||
return degrees + "°" + minutes + "′" + seconds + "″" + cardinal;
|
||||
}
|
||||
|
||||
// get surface elevation
|
||||
|
|
|
|||
|
|
@ -246,6 +246,7 @@ function editHeightmap(options) {
|
|||
Cultures.expand();
|
||||
|
||||
BurgsAndStates.generate();
|
||||
Routes.generate();
|
||||
Religions.generate();
|
||||
BurgsAndStates.defineStateForms();
|
||||
BurgsAndStates.generateProvinces();
|
||||
|
|
@ -281,8 +282,7 @@ function editHeightmap(options) {
|
|||
const l = grid.cells.i.length;
|
||||
const biome = new Uint8Array(l);
|
||||
const pop = new Uint16Array(l);
|
||||
const road = new Uint16Array(l);
|
||||
const crossroad = new Uint16Array(l);
|
||||
const routes = {};
|
||||
const s = new Uint16Array(l);
|
||||
const burg = new Uint16Array(l);
|
||||
const state = new Uint16Array(l);
|
||||
|
|
@ -300,8 +300,7 @@ function editHeightmap(options) {
|
|||
biome[g] = pack.cells.biome[i];
|
||||
culture[g] = pack.cells.culture[i];
|
||||
pop[g] = pack.cells.pop[i];
|
||||
road[g] = pack.cells.road[i];
|
||||
crossroad[g] = pack.cells.crossroad[i];
|
||||
routes[g] = pack.cells.routes[i];
|
||||
s[g] = pack.cells.s[i];
|
||||
state[g] = pack.cells.state[i];
|
||||
province[g] = pack.cells.province[i];
|
||||
|
|
@ -353,8 +352,7 @@ function editHeightmap(options) {
|
|||
// assign saved pack data from grid back to pack
|
||||
const n = pack.cells.i.length;
|
||||
pack.cells.pop = new Float32Array(n);
|
||||
pack.cells.road = new Uint16Array(n);
|
||||
pack.cells.crossroad = new Uint16Array(n);
|
||||
pack.cells.routes = {};
|
||||
pack.cells.s = new Uint16Array(n);
|
||||
pack.cells.burg = new Uint16Array(n);
|
||||
pack.cells.state = new Uint16Array(n);
|
||||
|
|
@ -389,8 +387,7 @@ function editHeightmap(options) {
|
|||
if (!isLand) continue;
|
||||
pack.cells.culture[i] = culture[g];
|
||||
pack.cells.pop[i] = pop[g];
|
||||
pack.cells.road[i] = road[g];
|
||||
pack.cells.crossroad[i] = crossroad[g];
|
||||
pack.cells.routes[i] = routes[g];
|
||||
pack.cells.s[i] = s[g];
|
||||
pack.cells.state[i] = state[g];
|
||||
pack.cells.province[i] = province[g];
|
||||
|
|
|
|||
|
|
@ -50,6 +50,7 @@ function handleKeyup(event) {
|
|||
else if (shift && code === "KeyO") editNotes();
|
||||
else if (shift && code === "KeyA") overviewCharts();
|
||||
else if (shift && code === "KeyT") overviewBurgs();
|
||||
else if (shift && code === "KeyU") overviewRoutes();
|
||||
else if (shift && code === "KeyV") overviewRivers();
|
||||
else if (shift && code === "KeyM") overviewMilitary();
|
||||
else if (shift && code === "KeyK") overviewMarkers();
|
||||
|
|
@ -57,7 +58,7 @@ function handleKeyup(event) {
|
|||
else if (key === "!") toggleAddBurg();
|
||||
else if (key === "@") toggleAddLabel();
|
||||
else if (key === "#") toggleAddRiver();
|
||||
else if (key === "$") toggleAddRoute();
|
||||
else if (key === "$") createRoute();
|
||||
else if (key === "%") toggleAddMarker();
|
||||
else if (alt && code === "KeyB") console.table(pack.burgs);
|
||||
else if (alt && code === "KeyS") console.table(pack.states);
|
||||
|
|
|
|||
|
|
@ -48,8 +48,7 @@ function editLake() {
|
|||
document.getElementById("lakeArea").value = si(getArea(l.area)) + " " + getAreaUnit();
|
||||
|
||||
const length = d3.polygonLength(l.vertices.map(v => pack.vertices.p[v]));
|
||||
document.getElementById("lakeShoreLength").value =
|
||||
si(length * distanceScaleInput.value) + " " + distanceUnitInput.value;
|
||||
document.getElementById("lakeShoreLength").value = si(length * distanceScale) + " " + distanceUnitInput.value;
|
||||
|
||||
const lakeCells = Array.from(cells.i.filter(i => cells.f[i] === l.i));
|
||||
const heights = lakeCells.map(i => cells.h[i]);
|
||||
|
|
|
|||
|
|
@ -169,6 +169,7 @@ function restoreLayers() {
|
|||
if (layerIsOn("toggleGrid")) drawGrid();
|
||||
if (layerIsOn("toggleCoordinates")) drawCoordinates();
|
||||
if (layerIsOn("toggleCompass")) compass.style("display", "block");
|
||||
if (layerIsOn("toggleRoutes")) drawRoutes();
|
||||
if (layerIsOn("toggleTemp")) drawTemp();
|
||||
if (layerIsOn("togglePrec")) drawPrec();
|
||||
if (layerIsOn("togglePopulation")) drawPopulation();
|
||||
|
|
@ -188,92 +189,135 @@ function restoreLayers() {
|
|||
}
|
||||
|
||||
function toggleHeight(event) {
|
||||
if (customization === 1) {
|
||||
tip("You cannot turn off the layer when heightmap is in edit mode", false, "error");
|
||||
return;
|
||||
}
|
||||
if (customization === 1) return tip("You cannot turn off the layer when heightmap is in edit mode", false, "error");
|
||||
|
||||
if (!terrs.selectAll("*").size()) {
|
||||
const children = terrs.selectAll("#oceanHeights > *, #landHeights > *");
|
||||
if (!children.size()) {
|
||||
turnButtonOn("toggleHeight");
|
||||
drawHeightmap();
|
||||
if (event && isCtrlClick(event)) editStyle("terrs");
|
||||
} else {
|
||||
if (event && isCtrlClick(event)) {
|
||||
editStyle("terrs");
|
||||
return;
|
||||
}
|
||||
if (event && isCtrlClick(event)) return editStyle("terrs");
|
||||
turnButtonOff("toggleHeight");
|
||||
terrs.selectAll("*").remove();
|
||||
children.remove();
|
||||
}
|
||||
}
|
||||
|
||||
function drawHeightmap() {
|
||||
TIME && console.time("drawHeightmap");
|
||||
terrs.selectAll("*").remove();
|
||||
|
||||
const {cells, vertices} = pack;
|
||||
const n = cells.i.length;
|
||||
const used = new Uint8Array(cells.i.length);
|
||||
const paths = new Array(101).fill("");
|
||||
const ocean = terrs.select("#oceanHeights");
|
||||
const land = terrs.select("#landHeights");
|
||||
|
||||
const scheme = getColorScheme(terrs.attr("scheme"));
|
||||
const terracing = terrs.attr("terracing") / 10; // add additional shifted darker layer for pseudo-3d effect
|
||||
const skip = +terrs.attr("skip") + 1;
|
||||
const simplification = +terrs.attr("relax");
|
||||
ocean.selectAll("*").remove();
|
||||
land.selectAll("*").remove();
|
||||
|
||||
switch (+terrs.attr("curve")) {
|
||||
case 0:
|
||||
lineGen.curve(d3.curveBasisClosed);
|
||||
break;
|
||||
case 1:
|
||||
lineGen.curve(d3.curveLinear);
|
||||
break;
|
||||
case 2:
|
||||
lineGen.curve(d3.curveStep);
|
||||
break;
|
||||
default:
|
||||
lineGen.curve(d3.curveBasisClosed);
|
||||
const paths = new Array(101);
|
||||
|
||||
// ocean cells
|
||||
const renderOceanCells = Boolean(+ocean.attr("data-render"));
|
||||
if (renderOceanCells) {
|
||||
const {cells, vertices} = grid;
|
||||
const used = new Uint8Array(cells.i.length);
|
||||
|
||||
const skip = +ocean.attr("skip") + 1 || 1;
|
||||
const relax = +ocean.attr("relax") || 0;
|
||||
lineGen.curve(d3[ocean.attr("curve") || "curveBasisClosed"]);
|
||||
|
||||
let currentLayer = 0;
|
||||
const heights = Array.from(cells.i).sort((a, b) => cells.h[a] - cells.h[b]);
|
||||
|
||||
for (const i of heights) {
|
||||
const h = cells.h[i];
|
||||
if (h > currentLayer) currentLayer += skip;
|
||||
if (h < currentLayer) continue;
|
||||
if (currentLayer >= 20) break;
|
||||
if (used[i]) continue; // already marked
|
||||
const onborder = cells.c[i].some(n => cells.h[n] < h);
|
||||
if (!onborder) continue;
|
||||
const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.h[i] < h));
|
||||
const chain = connectVertices(cells, vertices, vertex, h, used);
|
||||
if (chain.length < 3) continue;
|
||||
const points = simplifyLine(chain, relax).map(v => vertices.p[v]);
|
||||
if (!paths[h]) paths[h] = "";
|
||||
paths[h] += round(lineGen(points));
|
||||
}
|
||||
}
|
||||
|
||||
let currentLayer = 20;
|
||||
const heights = cells.i.sort((a, b) => cells.h[a] - cells.h[b]);
|
||||
for (const i of heights) {
|
||||
const h = cells.h[i];
|
||||
if (h > currentLayer) currentLayer += skip;
|
||||
if (currentLayer > 100) break; // no layers possible with height > 100
|
||||
if (h < currentLayer) continue;
|
||||
if (used[i]) continue; // already marked
|
||||
const onborder = cells.c[i].some(n => cells.h[n] < h);
|
||||
if (!onborder) continue;
|
||||
const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.h[i] < h));
|
||||
const chain = connectVertices(vertex, h);
|
||||
if (chain.length < 3) continue;
|
||||
const points = simplifyLine(chain).map(v => vertices.p[v]);
|
||||
paths[h] += round(lineGen(points));
|
||||
// land cells
|
||||
{
|
||||
const {cells, vertices} = pack;
|
||||
const used = new Uint8Array(cells.i.length);
|
||||
|
||||
const skip = +land.attr("skip") + 1 || 1;
|
||||
const relax = +land.attr("relax") || 0;
|
||||
lineGen.curve(d3[land.attr("curve") || "curveBasisClosed"]);
|
||||
|
||||
let currentLayer = 20;
|
||||
const heights = Array.from(cells.i).sort((a, b) => cells.h[a] - cells.h[b]);
|
||||
for (const i of heights) {
|
||||
const h = cells.h[i];
|
||||
if (h > currentLayer) currentLayer += skip;
|
||||
if (h < currentLayer) continue;
|
||||
if (currentLayer > 100) break; // no layers possible with height > 100
|
||||
if (used[i]) continue; // already marked
|
||||
const onborder = cells.c[i].some(n => cells.h[n] < h);
|
||||
if (!onborder) continue;
|
||||
const vertex = cells.v[i].find(v => vertices.c[v].some(i => cells.h[i] < h));
|
||||
const chain = connectVertices(cells, vertices, vertex, h, used);
|
||||
if (chain.length < 3) continue;
|
||||
const points = simplifyLine(chain, relax).map(v => vertices.p[v]);
|
||||
if (!paths[h]) paths[h] = "";
|
||||
paths[h] += round(lineGen(points));
|
||||
}
|
||||
}
|
||||
|
||||
terrs
|
||||
.append("rect")
|
||||
.attr("x", 0)
|
||||
.attr("y", 0)
|
||||
.attr("width", graphWidth)
|
||||
.attr("height", graphHeight)
|
||||
.attr("fill", scheme(0.8)); // draw base layer
|
||||
for (const i of d3.range(20, 101)) {
|
||||
if (paths[i].length < 10) continue;
|
||||
const color = getColor(i, scheme);
|
||||
if (terracing)
|
||||
terrs
|
||||
.append("path")
|
||||
.attr("d", paths[i])
|
||||
.attr("transform", "translate(.7,1.4)")
|
||||
.attr("fill", d3.color(color).darker(terracing))
|
||||
.attr("data-height", i);
|
||||
terrs.append("path").attr("d", paths[i]).attr("fill", color).attr("data-height", i);
|
||||
// render paths
|
||||
for (const height of d3.range(0, 101)) {
|
||||
const group = height < 20 ? ocean : land;
|
||||
const scheme = getColorScheme(group.attr("scheme"));
|
||||
|
||||
if (height === 0 && renderOceanCells) {
|
||||
// draw base ocean layer
|
||||
group
|
||||
.append("rect")
|
||||
.attr("x", 0)
|
||||
.attr("y", 0)
|
||||
.attr("width", graphWidth)
|
||||
.attr("height", graphHeight)
|
||||
.attr("fill", scheme(1));
|
||||
}
|
||||
|
||||
if (height === 20) {
|
||||
// draw base land layer
|
||||
group
|
||||
.append("rect")
|
||||
.attr("x", 0)
|
||||
.attr("y", 0)
|
||||
.attr("width", graphWidth)
|
||||
.attr("height", graphHeight)
|
||||
.attr("fill", scheme(0.8));
|
||||
}
|
||||
|
||||
if (paths[height] && paths[height].length >= 10) {
|
||||
const terracing = group.attr("terracing") / 10 || 0;
|
||||
const color = getColor(height, scheme);
|
||||
|
||||
if (terracing) {
|
||||
group
|
||||
.append("path")
|
||||
.attr("d", paths[height])
|
||||
.attr("transform", "translate(.7,1.4)")
|
||||
.attr("fill", d3.color(color).darker(terracing))
|
||||
.attr("data-height", height);
|
||||
}
|
||||
group.append("path").attr("d", paths[height]).attr("fill", color).attr("data-height", height);
|
||||
}
|
||||
}
|
||||
|
||||
// connect vertices to chain
|
||||
function connectVertices(start, h) {
|
||||
function connectVertices(cells, vertices, start, h, used) {
|
||||
const n = cells.i.length;
|
||||
const chain = []; // vertices chain to form a path
|
||||
for (let i = 0, current = start; i === 0 || (current !== start && i < 20000); i++) {
|
||||
const prev = chain[chain.length - 1]; // previous vertex in chain
|
||||
|
|
@ -295,7 +339,7 @@ function drawHeightmap() {
|
|||
return chain;
|
||||
}
|
||||
|
||||
function simplifyLine(chain) {
|
||||
function simplifyLine(chain, simplification) {
|
||||
if (!simplification) return chain;
|
||||
const n = simplification + 1; // filter each nth element
|
||||
return chain.filter((d, i) => i % n === 0);
|
||||
|
|
@ -349,7 +393,6 @@ function drawTemp() {
|
|||
const start = findStart(i, t);
|
||||
if (!start) continue;
|
||||
used[i] = 1;
|
||||
//debug.append("circle").attr("r", 3).attr("cx", vertices.p[start][0]).attr("cy", vertices.p[start][1]).attr("fill", "red").attr("stroke", "black").attr("stroke-width", .3);
|
||||
|
||||
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));
|
||||
|
|
@ -1027,27 +1070,29 @@ function drawStates() {
|
|||
|
||||
const bodyData = body.map((p, s) => [p.length > 10 ? p : null, s, states[s].color]).filter(d => d[0]);
|
||||
const gapData = gap.map((p, s) => [p.length > 10 ? p : null, s, states[s].color]).filter(d => d[0]);
|
||||
const haloData = halo.map((p, s) => [p.length > 10 ? p : null, s, states[s].color]).filter(d => d[0]);
|
||||
|
||||
const bodyString = bodyData.map(d => `<path id="state${d[1]}" d="${d[0]}" fill="${d[2]}" stroke="none"/>`).join("");
|
||||
const gapString = gapData.map(d => `<path id="state-gap${d[1]}" d="${d[0]}" fill="none" stroke="${d[2]}"/>`).join("");
|
||||
const clipString = bodyData
|
||||
.map(d => `<clipPath id="state-clip${d[1]}"><use href="#state${d[1]}"/></clipPath>`)
|
||||
.join("");
|
||||
const haloString = haloData
|
||||
.map(
|
||||
d =>
|
||||
`<path id="state-border${d[1]}" d="${d[0]}" clip-path="url(#state-clip${d[1]})" stroke="${
|
||||
d3.color(d[2]) ? d3.color(d[2]).darker().hex() : "#666666"
|
||||
}"/>`
|
||||
)
|
||||
.join("");
|
||||
|
||||
statesBody.html(bodyString + gapString);
|
||||
defs.select("#statePaths").html(clipString);
|
||||
statesHalo.html(haloString);
|
||||
|
||||
// connect vertices to chain
|
||||
const isOptimized = shapeRendering.value === "optimizeSpeed";
|
||||
if (!isOptimized) {
|
||||
const haloData = halo.map((p, s) => [p.length > 10 ? p : null, s, states[s].color]).filter(d => d[0]);
|
||||
|
||||
const haloString = haloData
|
||||
.map(d => {
|
||||
const stroke = d3.color(d[2]) ? d3.color(d[2]).darker().hex() : "#666666";
|
||||
return `<path id="state-border${d[1]}" d="${d[0]}" clip-path="url(#state-clip${d[1]})" stroke="${stroke}"/>`;
|
||||
})
|
||||
.join("");
|
||||
statesHalo.html(haloString);
|
||||
|
||||
const clipString = bodyData
|
||||
.map(d => `<clipPath id="state-clip${d[1]}"><use href="#state${d[1]}"/></clipPath>`)
|
||||
.join("");
|
||||
defs.select("#statePaths").html(clipString);
|
||||
}
|
||||
|
||||
function connectVertices(start, state) {
|
||||
const chain = []; // vertices chain to form a path
|
||||
const getType = c => {
|
||||
|
|
@ -1482,10 +1527,6 @@ function toggleCompass(event) {
|
|||
if (!layerIsOn("toggleCompass")) {
|
||||
turnButtonOn("toggleCompass");
|
||||
$("#compass").fadeIn();
|
||||
if (!compass.selectAll("*").size()) {
|
||||
compass.append("use").attr("xlink:href", "#rose");
|
||||
shiftCompass();
|
||||
}
|
||||
if (event && isCtrlClick(event)) editStyle("compass");
|
||||
} else {
|
||||
if (event && isCtrlClick(event)) {
|
||||
|
|
@ -1581,18 +1622,33 @@ function drawRivers() {
|
|||
function toggleRoutes(event) {
|
||||
if (!layerIsOn("toggleRoutes")) {
|
||||
turnButtonOn("toggleRoutes");
|
||||
$("#routes").fadeIn();
|
||||
drawRoutes();
|
||||
if (event && isCtrlClick(event)) editStyle("routes");
|
||||
} else {
|
||||
if (event && isCtrlClick(event)) {
|
||||
editStyle("routes");
|
||||
return;
|
||||
}
|
||||
$("#routes").fadeOut();
|
||||
if (event && isCtrlClick(event)) return editStyle("routes");
|
||||
routes.selectAll("path").remove();
|
||||
turnButtonOff("toggleRoutes");
|
||||
}
|
||||
}
|
||||
|
||||
function drawRoutes() {
|
||||
TIME && console.time("drawRoutes");
|
||||
const routePaths = {};
|
||||
|
||||
for (const route of pack.routes) {
|
||||
const {i, group} = route;
|
||||
if (!routePaths[group]) routePaths[group] = [];
|
||||
routePaths[group].push(`<path id="route${i}" d="${Routes.getPath(route)}"/>`);
|
||||
}
|
||||
|
||||
routes.selectAll("path").remove();
|
||||
for (const group in routePaths) {
|
||||
routes.select("#" + group).html(routePaths[group].join(""));
|
||||
}
|
||||
|
||||
TIME && console.timeEnd("drawRoutes");
|
||||
}
|
||||
|
||||
function toggleMilitary() {
|
||||
if (!layerIsOn("toggleMilitary")) {
|
||||
turnButtonOn("toggleMilitary");
|
||||
|
|
@ -1670,10 +1726,7 @@ function toggleLabels(event) {
|
|||
invokeActiveZooming();
|
||||
if (event && isCtrlClick(event)) editStyle("labels");
|
||||
} else {
|
||||
if (event && isCtrlClick(event)) {
|
||||
editStyle("labels");
|
||||
return;
|
||||
}
|
||||
if (event && isCtrlClick(event)) return editStyle("labels");
|
||||
turnButtonOff("toggleLabels");
|
||||
labels.style("display", "none");
|
||||
}
|
||||
|
|
@ -1685,10 +1738,7 @@ function toggleIcons(event) {
|
|||
$("#icons").fadeIn();
|
||||
if (event && isCtrlClick(event)) editStyle("burgIcons");
|
||||
} else {
|
||||
if (event && isCtrlClick(event)) {
|
||||
editStyle("burgIcons");
|
||||
return;
|
||||
}
|
||||
if (event && isCtrlClick(event)) return editStyle("burgIcons");
|
||||
turnButtonOff("toggleIcons");
|
||||
$("#icons").fadeOut();
|
||||
}
|
||||
|
|
@ -1701,10 +1751,7 @@ function toggleRulers(event) {
|
|||
rulers.draw();
|
||||
ruler.style("display", null);
|
||||
} else {
|
||||
if (event && isCtrlClick(event)) {
|
||||
editStyle("ruler");
|
||||
return;
|
||||
}
|
||||
if (event && isCtrlClick(event)) return editStyle("ruler");
|
||||
turnButtonOff("toggleRulers");
|
||||
ruler.selectAll("*").remove();
|
||||
ruler.style("display", "none");
|
||||
|
|
@ -1715,17 +1762,112 @@ function toggleScaleBar(event) {
|
|||
if (!layerIsOn("toggleScaleBar")) {
|
||||
turnButtonOn("toggleScaleBar");
|
||||
$("#scaleBar").fadeIn();
|
||||
if (event && isCtrlClick(event)) editUnits();
|
||||
if (event && isCtrlClick(event)) editStyle("scaleBar");
|
||||
} else {
|
||||
if (event && isCtrlClick(event)) {
|
||||
editUnits();
|
||||
return;
|
||||
}
|
||||
if (event && isCtrlClick(event)) return editStyle("scaleBar");
|
||||
$("#scaleBar").fadeOut();
|
||||
turnButtonOff("toggleScaleBar");
|
||||
}
|
||||
}
|
||||
|
||||
function drawScaleBar(scaleBar, scaleLevel) {
|
||||
if (!scaleBar.size() || scaleBar.style("display") === "none") return;
|
||||
|
||||
const unit = distanceUnitInput.value;
|
||||
const size = +scaleBar.attr("data-bar-size");
|
||||
|
||||
const length = (function () {
|
||||
const init = 100;
|
||||
let val = (init * size * distanceScale) / scaleLevel; // bar length in distance unit
|
||||
if (val > 900) val = rn(val, -3); // round to 1000
|
||||
else if (val > 90) val = rn(val, -2); // round to 100
|
||||
else if (val > 9) val = rn(val, -1); // round to 10
|
||||
else val = rn(val); // round to 1
|
||||
const length = (val * scaleLevel) / distanceScale; // actual length in pixels on this scale
|
||||
return length;
|
||||
})();
|
||||
|
||||
scaleBar.select("#scaleBarContent").remove(); // redraw content every time
|
||||
const content = scaleBar.append("g").attr("id", "scaleBarContent");
|
||||
|
||||
const lines = content.append("g");
|
||||
lines
|
||||
.append("line")
|
||||
.attr("x1", 0.5)
|
||||
.attr("y1", 0)
|
||||
.attr("x2", length + size - 0.5)
|
||||
.attr("y2", 0)
|
||||
.attr("stroke-width", size)
|
||||
.attr("stroke", "white");
|
||||
lines
|
||||
.append("line")
|
||||
.attr("x1", 0)
|
||||
.attr("y1", size)
|
||||
.attr("x2", length + size)
|
||||
.attr("y2", size)
|
||||
.attr("stroke-width", size)
|
||||
.attr("stroke", "#3d3d3d");
|
||||
lines
|
||||
.append("line")
|
||||
.attr("x1", 0)
|
||||
.attr("y1", 0)
|
||||
.attr("x2", length + size)
|
||||
.attr("y2", 0)
|
||||
.attr("stroke-width", rn(size * 3, 2))
|
||||
.attr("stroke-dasharray", size + " " + rn(length / 5 - size, 2))
|
||||
.attr("stroke", "#3d3d3d");
|
||||
|
||||
const texts = content.append("g").attr("text-anchor", "middle").attr("font-family", "var(--serif)");
|
||||
texts
|
||||
.selectAll("text")
|
||||
.data(d3.range(0, 6))
|
||||
.enter()
|
||||
.append("text")
|
||||
.attr("x", d => rn((d * length) / 5, 2))
|
||||
.attr("y", 0)
|
||||
.attr("dy", "-.6em")
|
||||
.text(d => rn((((d * length) / 5) * distanceScale) / scaleLevel) + (d < 5 ? "" : " " + unit));
|
||||
|
||||
const label = scaleBar.attr("data-label");
|
||||
if (label) {
|
||||
texts
|
||||
.append("text")
|
||||
.attr("x", (length + 1) / 2)
|
||||
.attr("dy", ".6em")
|
||||
.attr("dominant-baseline", "text-before-edge")
|
||||
.text(label);
|
||||
}
|
||||
|
||||
const scaleBarBack = scaleBar.select("#scaleBarBack");
|
||||
if (scaleBarBack.size()) {
|
||||
const bbox = content.node().getBBox();
|
||||
const paddingTop = +scaleBarBack.attr("data-top") || 0;
|
||||
const paddingLeft = +scaleBarBack.attr("data-left") || 0;
|
||||
const paddingRight = +scaleBarBack.attr("data-right") || 0;
|
||||
const paddingBottom = +scaleBarBack.attr("data-bottom") || 0;
|
||||
|
||||
scaleBar
|
||||
.select("#scaleBarBack")
|
||||
.attr("x", -paddingLeft)
|
||||
.attr("y", -paddingTop)
|
||||
.attr("width", bbox.width + paddingRight)
|
||||
.attr("height", bbox.height + paddingBottom);
|
||||
}
|
||||
}
|
||||
|
||||
// fit ScaleBar to screen size
|
||||
function fitScaleBar(scaleBar, fullWidth, fullHeight) {
|
||||
if (!scaleBar.select("rect").size() || scaleBar.style("display") === "none") return;
|
||||
|
||||
const posX = +scaleBar.attr("data-x") || 99;
|
||||
const posY = +scaleBar.attr("data-y") || 99;
|
||||
const bbox = scaleBar.select("rect").node().getBBox();
|
||||
|
||||
const x = rn((fullWidth * posX) / 100 - bbox.width + 10);
|
||||
const y = rn((fullHeight * posY) / 100 - bbox.height + 20);
|
||||
scaleBar.attr("transform", `translate(${x},${y})`);
|
||||
}
|
||||
|
||||
function toggleZones(event) {
|
||||
if (!layerIsOn("toggleZones")) {
|
||||
turnButtonOn("toggleZones");
|
||||
|
|
@ -1748,10 +1890,7 @@ function toggleEmblems(event) {
|
|||
$("#emblems").fadeIn();
|
||||
if (event && isCtrlClick(event)) editStyle("emblems");
|
||||
} else {
|
||||
if (event && isCtrlClick(event)) {
|
||||
editStyle("emblems");
|
||||
return;
|
||||
}
|
||||
if (event && isCtrlClick(event)) return editStyle("emblems");
|
||||
$("#emblems").fadeOut();
|
||||
turnButtonOff("toggleEmblems");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -66,7 +66,7 @@ class Measurer {
|
|||
}
|
||||
|
||||
getDash() {
|
||||
return rn(30 / distanceScaleInput.value, 2);
|
||||
return rn(30 / distanceScale, 2);
|
||||
}
|
||||
|
||||
drag() {
|
||||
|
|
@ -205,7 +205,7 @@ class Ruler extends Measurer {
|
|||
|
||||
updateLabel() {
|
||||
const length = this.getLength();
|
||||
const text = rn(length * distanceScaleInput.value) + " " + distanceUnitInput.value;
|
||||
const text = rn(length * distanceScale) + " " + distanceUnitInput.value;
|
||||
const [x, y] = last(this.points);
|
||||
this.el.select("text").attr("x", x).attr("y", y).text(text);
|
||||
}
|
||||
|
|
@ -337,7 +337,7 @@ class Opisometer extends Measurer {
|
|||
|
||||
updateLabel() {
|
||||
const length = this.el.select("path").node().getTotalLength();
|
||||
const text = rn(length * distanceScaleInput.value) + " " + distanceUnitInput.value;
|
||||
const text = rn(length * distanceScale) + " " + distanceUnitInput.value;
|
||||
const [x, y] = last(this.points);
|
||||
this.el.select("text").attr("x", x).attr("y", y).text(text);
|
||||
}
|
||||
|
|
@ -475,7 +475,7 @@ class RouteOpisometer extends Measurer {
|
|||
|
||||
updateLabel() {
|
||||
const length = this.el.select("path").node().getTotalLength();
|
||||
const text = rn(length * distanceScaleInput.value) + " " + distanceUnitInput.value;
|
||||
const text = rn(length * distanceScale) + " " + distanceUnitInput.value;
|
||||
const [x, y] = last(this.points);
|
||||
this.el.select("text").attr("x", x).attr("y", y).text(text);
|
||||
}
|
||||
|
|
@ -486,9 +486,7 @@ class RouteOpisometer extends Measurer {
|
|||
const cells = pack.cells;
|
||||
|
||||
const c = findCell(mousePoint[0], mousePoint[1]);
|
||||
if (!cells.road[c] && !d3.event.sourceEvent.shiftKey) {
|
||||
return;
|
||||
}
|
||||
if (!Routes.isConnected(c) && !d3.event.sourceEvent.shiftKey) return;
|
||||
|
||||
context.trackCell(c, rigth);
|
||||
});
|
||||
|
|
@ -532,101 +530,3 @@ class Planimeter extends Measurer {
|
|||
this.el.select("text").attr("x", c[0]).attr("y", c[1]).text(area);
|
||||
}
|
||||
}
|
||||
|
||||
// Scale bar
|
||||
function drawScaleBar(scaleBar, scaleLevel) {
|
||||
if (!scaleBar.size() || scaleBar.style("display") === "none") return;
|
||||
scaleBar.selectAll("*").remove(); // fully redraw every time
|
||||
|
||||
const distanceScale = +distanceScaleInput.value;
|
||||
const unit = distanceUnitInput.value;
|
||||
const size = +barSizeInput.value;
|
||||
|
||||
// calculate size
|
||||
const init = 100;
|
||||
let val = (init * size * distanceScale) / scaleLevel; // bar length in distance unit
|
||||
if (val > 900) val = rn(val, -3);
|
||||
// round to 1000
|
||||
else if (val > 90) val = rn(val, -2);
|
||||
// round to 100
|
||||
else if (val > 9) val = rn(val, -1);
|
||||
// round to 10
|
||||
else val = rn(val); // round to 1
|
||||
const length = (val * scaleLevel) / distanceScale; // actual length in pixels on this scale
|
||||
|
||||
scaleBar
|
||||
.append("line")
|
||||
.attr("x1", 0.5)
|
||||
.attr("y1", 0)
|
||||
.attr("x2", length + size - 0.5)
|
||||
.attr("y2", 0)
|
||||
.attr("stroke-width", size)
|
||||
.attr("stroke", "white");
|
||||
scaleBar
|
||||
.append("line")
|
||||
.attr("x1", 0)
|
||||
.attr("y1", size)
|
||||
.attr("x2", length + size)
|
||||
.attr("y2", size)
|
||||
.attr("stroke-width", size)
|
||||
.attr("stroke", "#3d3d3d");
|
||||
const dash = size + " " + rn(length / 5 - size, 2);
|
||||
scaleBar
|
||||
.append("line")
|
||||
.attr("x1", 0)
|
||||
.attr("y1", 0)
|
||||
.attr("x2", length + size)
|
||||
.attr("y2", 0)
|
||||
.attr("stroke-width", rn(size * 3, 2))
|
||||
.attr("stroke-dasharray", dash)
|
||||
.attr("stroke", "#3d3d3d");
|
||||
|
||||
const fontSize = rn(5 * size, 1);
|
||||
scaleBar
|
||||
.selectAll("text")
|
||||
.data(d3.range(0, 6))
|
||||
.enter()
|
||||
.append("text")
|
||||
.attr("x", d => rn((d * length) / 5, 2))
|
||||
.attr("y", 0)
|
||||
.attr("dy", "-.6em")
|
||||
.attr("font-size", fontSize)
|
||||
.text(d => rn((((d * length) / 5) * distanceScale) / scaleLevel) + (d < 5 ? "" : " " + unit));
|
||||
|
||||
if (barLabel.value !== "") {
|
||||
scaleBar
|
||||
.append("text")
|
||||
.attr("x", (length + 1) / 2)
|
||||
.attr("y", 2 * size)
|
||||
.attr("dominant-baseline", "text-before-edge")
|
||||
.attr("font-size", fontSize)
|
||||
.text(barLabel.value);
|
||||
}
|
||||
|
||||
const bbox = scaleBar.node().getBBox();
|
||||
// append backbround rectangle
|
||||
scaleBar
|
||||
.insert("rect", ":first-child")
|
||||
.attr("x", -10)
|
||||
.attr("y", -20)
|
||||
.attr("width", bbox.width + 10)
|
||||
.attr("height", bbox.height + 15)
|
||||
.attr("stroke-width", size)
|
||||
.attr("stroke", "none")
|
||||
.attr("filter", "url(#blur5)")
|
||||
.attr("fill", barBackColor.value)
|
||||
.attr("opacity", +barBackOpacity.value);
|
||||
}
|
||||
|
||||
// fit ScaleBar to screen size
|
||||
function fitScaleBar(scaleBar, fullWidth, fullHeight) {
|
||||
if (!scaleBar.select("rect").size() || scaleBar.style("display") === "none") return;
|
||||
|
||||
const px = isNaN(+barPosX.value) ? 0.99 : barPosX.value / 100;
|
||||
const py = isNaN(+barPosY.value) ? 0.99 : barPosY.value / 100;
|
||||
const bbox = scaleBar.select("rect").node().getBBox();
|
||||
|
||||
const x = rn(fullWidth * px - bbox.width + 10);
|
||||
const y = rn(fullHeight * py - bbox.height + 20);
|
||||
scaleBar.attr("transform", `translate(${x},${y})`);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -54,7 +54,11 @@ function overviewMilitary() {
|
|||
const insert = html => document.getElementById("militaryTotal").insertAdjacentHTML("beforebegin", html);
|
||||
for (const u of options.military) {
|
||||
const label = capitalize(u.name.replace(/_/g, " "));
|
||||
insert(`<div data-tip="State ${u.name} units number. Click to sort" class="sortable removable" data-sortby="${u.name}">${label} </div>`);
|
||||
insert(
|
||||
`<div data-tip="State ${
|
||||
u.name
|
||||
} units number. Click to sort" class="sortable removable" data-sortby="${u.name.toLowerCase()}">${label} </div>`
|
||||
);
|
||||
}
|
||||
header.querySelectorAll(".removable").forEach(function (e) {
|
||||
e.addEventListener("click", function () {
|
||||
|
|
@ -75,8 +79,10 @@ function overviewMilitary() {
|
|||
const total = options.military.reduce((s, u) => s + getForces(u) * u.crew, 0);
|
||||
const rate = (total / population) * 100;
|
||||
|
||||
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 sortData = options.military.map(u => `data-${u.name.toLowerCase()}="${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(" ");
|
||||
|
||||
lines += /* html */ `<div
|
||||
class="states"
|
||||
|
|
@ -91,9 +97,14 @@ function overviewMilitary() {
|
|||
<fill-box data-tip="${s.fullName}" fill="${s.color}" disabled></fill-box>
|
||||
<input data-tip="${s.fullName}" style="width:6em" value="${s.name}" readonly />
|
||||
${lineData}
|
||||
<div data-type="total" data-tip="Total state military personnel (considering crew)" style="font-weight: bold">${si(total)}</div>
|
||||
<div data-type="total" data-tip="Total state military personnel (considering crew)" style="font-weight: bold">${si(
|
||||
total
|
||||
)}</div>
|
||||
<div data-type="population" data-tip="State population">${si(population)}</div>
|
||||
<div data-type="rate" data-tip="Military personnel rate (% of state population). Depends on war alert">${rn(rate, 2)}%</div>
|
||||
<div data-type="rate" data-tip="Military personnel rate (% of state population). Depends on war alert">${rn(
|
||||
rate,
|
||||
2
|
||||
)}%</div>
|
||||
<input
|
||||
data-tip="War Alert. Editable modifier to military forces number, depends of political situation"
|
||||
style="width:4.1em"
|
||||
|
|
@ -131,7 +142,9 @@ function overviewMilitary() {
|
|||
});
|
||||
|
||||
const getForces = u => s.military.reduce((s, r) => s + (r.u[u.name] || 0), 0);
|
||||
options.military.forEach(u => (line.dataset[u.name] = line.querySelector(`div[data-type='${u.name}']`).innerHTML = getForces(u)));
|
||||
options.military.forEach(
|
||||
u => (line.dataset[u.name] = line.querySelector(`div[data-type='${u.name}']`).innerHTML = getForces(u))
|
||||
);
|
||||
|
||||
const population = rn((s.rural + s.urban * urbanization) * populationRate);
|
||||
const total = (line.dataset.total = options.military.reduce((s, u) => s + getForces(u) * u.crew, 0));
|
||||
|
|
@ -237,7 +250,16 @@ function overviewMilitary() {
|
|||
position: {my: "center", at: "center", of: "svg"},
|
||||
buttons: {
|
||||
Apply: applyMilitaryOptions,
|
||||
Add: () => addUnitLine({icon: "🛡️", name: "custom" + militaryOptionsTable.rows.length, rural: 0.2, urban: 0.5, crew: 1, power: 1, type: "melee"}),
|
||||
Add: () =>
|
||||
addUnitLine({
|
||||
icon: "🛡️",
|
||||
name: "custom" + militaryOptionsTable.rows.length,
|
||||
rural: 0.2,
|
||||
urban: 0.5,
|
||||
crew: 1,
|
||||
power: 1,
|
||||
type: "melee"
|
||||
}),
|
||||
Restore: restoreDefaultUnits,
|
||||
Cancel: function () {
|
||||
$(this).dialog("close");
|
||||
|
|
@ -262,7 +284,7 @@ function overviewMilitary() {
|
|||
if (el.tagName !== "BUTTON") return;
|
||||
const type = el.dataset.type;
|
||||
|
||||
if (type === "icon") return selectIcon(el.innerHTML, v => (el.innerHTML = v));
|
||||
if (type === "icon") return selectIcon(el.textContent, v => (el.textContent = v));
|
||||
if (type === "biomes") {
|
||||
const {i, name, color} = biomesData;
|
||||
const biomesArray = Array(i.length).fill(null);
|
||||
|
|
@ -294,7 +316,9 @@ function overviewMilitary() {
|
|||
function addUnitLine(unit) {
|
||||
const {type, icon, name, rural, urban, power, crew, separate} = unit;
|
||||
const row = document.createElement("tr");
|
||||
const typeOptions = types.map(t => `<option ${type === t ? "selected" : ""} value="${t}">${t}</option>`).join(" ");
|
||||
const typeOptions = types
|
||||
.map(t => `<option ${type === t ? "selected" : ""} value="${t}">${t}</option>`)
|
||||
.join(" ");
|
||||
|
||||
const getLimitButton = attr =>
|
||||
`<button
|
||||
|
|
@ -305,7 +329,9 @@ function overviewMilitary() {
|
|||
${getLimitText(unit[attr])}
|
||||
</button>`;
|
||||
|
||||
row.innerHTML = /* html */ `<td><button data-type="icon" data-tip="Click to select unit icon">${icon || " "}</button></td>
|
||||
row.innerHTML = /* html */ `<td><button data-type="icon" data-tip="Click to select unit icon">${
|
||||
icon || " "
|
||||
}</button></td>
|
||||
<td><input data-tip="Type unit name. If name is changed for existing unit, old unit will be replaced" value="${name}" /></td>
|
||||
<td>${getLimitButton("biomes")}</td>
|
||||
<td>${getLimitButton("states")}</td>
|
||||
|
|
@ -344,7 +370,9 @@ function overviewMilitary() {
|
|||
const lines = filtered.map(
|
||||
({i, name, fullName, color}) =>
|
||||
`<tr data-tip="${name}"><td><span style="color:${color}">⬤</span></td>
|
||||
<td><input data-i="${i}" id="el${i}" type="checkbox" class="checkbox" ${!initial.length || initial.includes(i) ? "checked" : ""} >
|
||||
<td><input data-i="${i}" id="el${i}" type="checkbox" class="checkbox" ${
|
||||
!initial.length || initial.includes(i) ? "checked" : ""
|
||||
} >
|
||||
<label for="el${i}" class="checkbox-label">${fullName || name}</label>
|
||||
</td></tr>`
|
||||
);
|
||||
|
|
@ -387,22 +415,21 @@ function overviewMilitary() {
|
|||
function applyMilitaryOptions() {
|
||||
const unitLines = Array.from(tableBody.querySelectorAll("tr"));
|
||||
const names = unitLines.map(r => r.querySelector("input").value.replace(/[&\/\\#, +()$~%.'":*?<>{}]/g, "_"));
|
||||
if (new Set(names).size !== names.length) {
|
||||
tip("All units should have unique names", false, "error");
|
||||
return;
|
||||
}
|
||||
if (new Set(names).size !== names.length) return tip("All units should have unique names", false, "error");
|
||||
|
||||
$("#militaryOptions").dialog("close");
|
||||
|
||||
options.military = unitLines.map((r, i) => {
|
||||
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 {type, value} = el.dataset || {};
|
||||
if (type === "icon") return el.innerHTML || "⠀";
|
||||
if (type) return value ? value.split(",").map(v => parseInt(v)) : null;
|
||||
if (el.type === "number") return +el.value || 0;
|
||||
if (el.type === "checkbox") return +el.checked || 0;
|
||||
return el.value;
|
||||
});
|
||||
const [icon, name, biomes, states, cultures, religions, rural, urban, crew, power, type, separate] =
|
||||
elements.map(el => {
|
||||
const {type, value} = el.dataset || {};
|
||||
if (type === "icon") return el.textContent || "⠀";
|
||||
if (type) return value ? value.split(",").map(v => parseInt(v)) : null;
|
||||
if (el.type === "number") return +el.value || 0;
|
||||
if (el.type === "checkbox") return +el.checked || 0;
|
||||
return el.value;
|
||||
});
|
||||
|
||||
const unit = {icon, name: names[i], rural, urban, crew, power, type, separate};
|
||||
if (biomes) unit.biomes = biomes;
|
||||
|
|
@ -419,7 +446,8 @@ function overviewMilitary() {
|
|||
}
|
||||
|
||||
function militaryRecalculate() {
|
||||
alertMessage.innerHTML = "Are you sure you want to recalculate military forces for all states?<br>Regiments for all states will be regenerated";
|
||||
alertMessage.innerHTML =
|
||||
"Are you sure you want to recalculate military forces for all states?<br>Regiments for all states will be regenerated";
|
||||
$("#alert").dialog({
|
||||
resizable: false,
|
||||
title: "Remove regiment",
|
||||
|
|
@ -443,7 +471,7 @@ function overviewMilitary() {
|
|||
body.querySelectorAll(":scope > div").forEach(function (el) {
|
||||
data += el.dataset.id + ",";
|
||||
data += el.dataset.state + ",";
|
||||
data += units.map(u => el.dataset[u]).join(",") + ",";
|
||||
data += units.map(u => el.dataset[u.toLowerCase()]).join(",") + ",";
|
||||
data += el.dataset.total + ",";
|
||||
data += el.dataset.population + ",";
|
||||
data += rn(el.dataset.rate, 2) + "%,";
|
||||
|
|
|
|||
|
|
@ -64,7 +64,7 @@ function editNotes(id, name) {
|
|||
|
||||
async function initEditor() {
|
||||
if (!window.tinymce) {
|
||||
const url = "https://cdn.tiny.cloud/1/4i6a79ymt2y0cagke174jp3meoi28vyecrch12e5puyw3p9a/tinymce/5/tinymce.min.js";
|
||||
const url = "https://azgaar.github.io/Fantasy-Map-Generator/libs/tinymce/tinymce.min.js";
|
||||
try {
|
||||
await import(url);
|
||||
} catch (error) {
|
||||
|
|
@ -79,11 +79,13 @@ function editNotes(id, name) {
|
|||
}
|
||||
|
||||
if (window.tinymce) {
|
||||
window.tinymce._setBaseUrl("https://azgaar.github.io/Fantasy-Map-Generator/libs/tinymce");
|
||||
tinymce.init({
|
||||
license_key: "gpl",
|
||||
selector: "#notesLegend",
|
||||
height: "90%",
|
||||
menubar: false,
|
||||
plugins: `autolink lists link charmap print code fullscreen image link media table paste hr wordcount`,
|
||||
plugins: `autolink lists link charmap code fullscreen image link media table wordcount`,
|
||||
toolbar: `code | undo redo | removeformat | bold italic strikethrough | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image media table | fontselect fontsizeselect | blockquote hr charmap | print fullscreen`,
|
||||
media_alt_source: false,
|
||||
media_poster: false,
|
||||
|
|
|
|||
|
|
@ -76,7 +76,7 @@ document
|
|||
|
||||
// show popup with a list of Patreon supportes (updated manually)
|
||||
async function showSupporters() {
|
||||
const {supporters} = await import("../dynamic/supporters.js?v=1.93.08");
|
||||
const {supporters} = await import("../dynamic/supporters.js?v=1.97.14");
|
||||
const list = supporters.split("\n").sort();
|
||||
const columns = window.innerWidth < 800 ? 2 : 5;
|
||||
|
||||
|
|
@ -119,9 +119,9 @@ function updateOutputToFollowInput(ev) {
|
|||
|
||||
// Option listeners
|
||||
const optionsContent = byId("optionsContent");
|
||||
optionsContent.addEventListener("input", function (event) {
|
||||
const id = event.target.id;
|
||||
const value = event.target.value;
|
||||
|
||||
optionsContent.addEventListener("input", event => {
|
||||
const {id, value} = event.target;
|
||||
if (id === "mapWidthInput" || id === "mapHeightInput") mapSizeInputChange();
|
||||
else if (id === "pointsInput") changeCellsDensity(+value);
|
||||
else if (id === "culturesSet") changeCultureSet();
|
||||
|
|
@ -133,10 +133,8 @@ optionsContent.addEventListener("input", function (event) {
|
|||
else if (id === "transparencyInput") changeDialogsTheme(themeColorInput.value, value);
|
||||
});
|
||||
|
||||
optionsContent.addEventListener("change", function (event) {
|
||||
const id = event.target.id;
|
||||
const value = event.target.value;
|
||||
|
||||
optionsContent.addEventListener("change", event => {
|
||||
const {id, value} = event.target;
|
||||
if (id === "zoomExtentMin" || id === "zoomExtentMax") changeZoomExtent(value);
|
||||
else if (id === "optionsSeed") generateMapWithSeed("seed change");
|
||||
else if (id === "uiSizeInput" || id === "uiSizeOutput") changeUiSize(value);
|
||||
|
|
@ -146,8 +144,8 @@ optionsContent.addEventListener("change", function (event) {
|
|||
else if (id === "stateLabelsModeInput") options.stateLabelsMode = value;
|
||||
});
|
||||
|
||||
optionsContent.addEventListener("click", function (event) {
|
||||
const id = event.target.id;
|
||||
optionsContent.addEventListener("click", event => {
|
||||
const {id} = event.target;
|
||||
if (id === "restoreDefaultCanvasSize") restoreDefaultCanvasSize();
|
||||
else if (id === "optionsMapHistory") showSeedHistoryDialog();
|
||||
else if (id === "optionsCopySeed") copyMapURL();
|
||||
|
|
@ -327,6 +325,7 @@ const cellsDensityMap = {
|
|||
};
|
||||
|
||||
function changeCellsDensity(value) {
|
||||
pointsInput.value = value;
|
||||
const cells = cellsDensityMap[value] || 1000;
|
||||
pointsInput.dataset.cells = cells;
|
||||
pointsOutputFormatted.value = getCellsDensityValue(cells);
|
||||
|
|
@ -536,6 +535,7 @@ function applyStoredOptions() {
|
|||
const key = localStorage.key(i);
|
||||
|
||||
if (key === "speakerVoice") continue;
|
||||
|
||||
const input = byId(key + "Input") || byId(key);
|
||||
const output = byId(key + "Output");
|
||||
|
||||
|
|
@ -544,6 +544,9 @@ function applyStoredOptions() {
|
|||
if (output) output.value = value;
|
||||
lock(key);
|
||||
|
||||
if (key === "points") changeCellsDensity(+value);
|
||||
if (key === "distanceScale") distanceScale = +value;
|
||||
|
||||
// add saved style presets to options
|
||||
if (key.slice(0, 5) === "style") applyOption(stylePreset, key, key.slice(5));
|
||||
}
|
||||
|
|
@ -581,6 +584,7 @@ function randomizeOptions() {
|
|||
const randomize = new URL(window.location.href).searchParams.get("options") === "default"; // ignore stored options
|
||||
|
||||
// 'Options' settings
|
||||
if (randomize || !locked("points")) changeCellsDensity(4); // reset to default, no need to randomize
|
||||
if (randomize || !locked("template")) randomizeHeightmapTemplate();
|
||||
if (randomize || !locked("regions")) regionsInput.value = regionsOutput.value = gauss(18, 5, 2, 30);
|
||||
if (randomize || !locked("provinces")) provincesInput.value = provincesOutput.value = gauss(20, 10, 20, 100);
|
||||
|
|
@ -602,7 +606,8 @@ function randomizeOptions() {
|
|||
|
||||
// 'Units Editor' settings
|
||||
const US = navigator.language === "en-US";
|
||||
if (randomize || !locked("distanceScale")) distanceScaleOutput.value = distanceScaleInput.value = gauss(3, 1, 1, 5);
|
||||
if (randomize || !locked("distanceScale"))
|
||||
distanceScale = distanceScaleOutput.value = distanceScaleInput.value = gauss(3, 1, 1, 5);
|
||||
if (!stored("distanceUnit")) distanceUnitInput.value = US ? "mi" : "km";
|
||||
if (!stored("heightUnit")) heightUnit.value = US ? "ft" : "m";
|
||||
if (!stored("temperatureScale")) temperatureScale.value = US ? "°F" : "°C";
|
||||
|
|
@ -641,17 +646,16 @@ function randomizeCultureSet() {
|
|||
function setRendering(value) {
|
||||
viewbox.attr("shape-rendering", value);
|
||||
|
||||
// if (value === "optimizeSpeed") {
|
||||
// // block some styles
|
||||
// coastline.select("#sea_island").style("filter", "none");
|
||||
// statesHalo.style("display", "none");
|
||||
// emblems.style("opacity", 1);
|
||||
// } else {
|
||||
// // remove style block
|
||||
// coastline.select("#sea_island").style("filter", null);
|
||||
// statesHalo.style("display", null);
|
||||
// emblems.style("opacity", null);
|
||||
// }
|
||||
if (value === "optimizeSpeed") {
|
||||
// block some styles
|
||||
coastline.select("#sea_island").style("filter", "none");
|
||||
statesHalo.style("display", "none");
|
||||
} else {
|
||||
// remove style block
|
||||
coastline.select("#sea_island").style("filter", null);
|
||||
statesHalo.style("display", null);
|
||||
if (pack.cells && statesHalo.selectAll("*").size() === 0) drawStates();
|
||||
}
|
||||
}
|
||||
|
||||
// generate current year and era name
|
||||
|
|
@ -691,7 +695,7 @@ function changeEra() {
|
|||
}
|
||||
|
||||
async function openTemplateSelectionDialog() {
|
||||
const HeightmapSelectionDialog = await import("../dynamic/heightmap-selection.js?v=1.93.12");
|
||||
const HeightmapSelectionDialog = await import("../dynamic/heightmap-selection.js?v=1.96.00");
|
||||
HeightmapSelectionDialog.open();
|
||||
}
|
||||
|
||||
|
|
@ -774,7 +778,7 @@ function showExportPane() {
|
|||
}
|
||||
|
||||
async function exportToJson(type) {
|
||||
const {exportToJson} = await import("../dynamic/export-json.js?v=1.93.03");
|
||||
const {exportToJson} = await import("../dynamic/export-json.js?v=1.97.08");
|
||||
exportToJson(type);
|
||||
}
|
||||
|
||||
|
|
@ -867,11 +871,9 @@ byId("mapToLoad").addEventListener("change", function () {
|
|||
});
|
||||
|
||||
function openExportToPngTiles() {
|
||||
byId("tileStatus").innerHTML = "";
|
||||
closeDialogs();
|
||||
updateTilesOptions();
|
||||
const status = byId("tileStatus");
|
||||
status.innerHTML = "";
|
||||
let loading = null;
|
||||
|
||||
const inputs = byId("exportToPngTilesScreen").querySelectorAll("input");
|
||||
inputs.forEach(input => input.addEventListener("input", updateTilesOptions));
|
||||
|
|
@ -881,16 +883,7 @@ function openExportToPngTiles() {
|
|||
title: "Download tiles",
|
||||
width: "23em",
|
||||
buttons: {
|
||||
Download: function () {
|
||||
status.innerHTML = "Preparing for download...";
|
||||
setTimeout(() => (status.innerHTML = "Downloading. It may take some time."), 1000);
|
||||
loading = setInterval(() => (status.innerHTML += "."), 1000);
|
||||
exportToPngTiles().then(() => {
|
||||
clearInterval(loading);
|
||||
status.innerHTML = /* html */ `Done. Check file in "Downloads" (crtl + J)`;
|
||||
setTimeout(() => (status.innerHTML = ""), 8000);
|
||||
});
|
||||
},
|
||||
Download: () => exportToPngTiles(),
|
||||
Cancel: function () {
|
||||
$(this).dialog("close");
|
||||
}
|
||||
|
|
@ -898,7 +891,6 @@ function openExportToPngTiles() {
|
|||
close: () => {
|
||||
inputs.forEach(input => input.removeEventListener("input", updateTilesOptions));
|
||||
debug.selectAll("*").remove();
|
||||
clearInterval(loading);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
|
@ -911,9 +903,9 @@ function updateTilesOptions() {
|
|||
}
|
||||
|
||||
const tileSize = byId("tileSize");
|
||||
const tilesX = +byId("tileColsOutput").value;
|
||||
const tilesY = +byId("tileRowsOutput").value;
|
||||
const scale = +byId("tileScaleOutput").value;
|
||||
const tilesX = +byId("tileColsOutput").value || 2;
|
||||
const tilesY = +byId("tileRowsOutput").value || 2;
|
||||
const scale = +byId("tileScaleOutput").value || 1;
|
||||
|
||||
// calculate size
|
||||
const sizeX = graphWidth * scale * tilesX;
|
||||
|
|
@ -928,18 +920,27 @@ function updateTilesOptions() {
|
|||
const labels = [];
|
||||
const tileW = (graphWidth / tilesX) | 0;
|
||||
const tileH = (graphHeight / tilesY) | 0;
|
||||
for (let y = 0, i = 0; y + tileH <= graphHeight; y += tileH) {
|
||||
for (let x = 0; x + tileW <= graphWidth; x += tileW, i++) {
|
||||
|
||||
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
function getRowLabel(row) {
|
||||
const first = row >= alphabet.length ? alphabet[Math.floor(row / alphabet.length) - 1] : "";
|
||||
const last = alphabet[row % alphabet.length];
|
||||
return first + last;
|
||||
}
|
||||
|
||||
for (let y = 0, row = 0; y + tileH <= graphHeight; y += tileH, row++) {
|
||||
for (let x = 0, column = 1; x + tileW <= graphWidth; x += tileW, column++) {
|
||||
rects.push(`<rect x=${x} y=${y} width=${tileW} height=${tileH} />`);
|
||||
labels.push(`<text x=${x + tileW / 2} y=${y + tileH / 2}>${i}</text>`);
|
||||
labels.push(`<text x=${x + tileW / 2} y=${y + tileH / 2}>${getRowLabel(row)}${column}</text>`);
|
||||
}
|
||||
}
|
||||
const rectsG = "<g fill='none' stroke='#000'>" + rects.join("") + "</g>";
|
||||
const labelsG =
|
||||
"<g fill='#000' stroke='none' text-anchor='middle' dominant-baseline='central' font-size='24px'>" +
|
||||
labels.join("") +
|
||||
"</g>";
|
||||
debug.html(rectsG + labelsG);
|
||||
|
||||
debug.html(`
|
||||
<g fill='none' stroke='#000'>${rects.join("")}</g>
|
||||
<g fill='#000' stroke='none' text-anchor='middle' dominant-baseline='central' font-size='18px'>${labels.join(
|
||||
""
|
||||
)}</g>
|
||||
`);
|
||||
}
|
||||
|
||||
// View mode
|
||||
|
|
|
|||
|
|
@ -44,12 +44,14 @@ function editProvinces() {
|
|||
cl = el.classList,
|
||||
line = el.parentNode,
|
||||
p = +line.dataset.id;
|
||||
const stateId = pack.provinces[p].state;
|
||||
|
||||
if (el.tagName === "FILL-BOX") changeFill(el);
|
||||
else if (cl.contains("name")) editProvinceName(p);
|
||||
else if (cl.contains("coaIcon")) editEmblem("province", "provinceCOA" + p, pack.provinces[p]);
|
||||
else if (cl.contains("icon-star-empty")) capitalZoomIn(p);
|
||||
else if (cl.contains("icon-flag-empty")) triggerIndependencePromps(p);
|
||||
else if (cl.contains("icon-dot-circled")) overviewBurgs({stateId});
|
||||
else if (cl.contains("culturePopulation")) changePopulation(p);
|
||||
else if (cl.contains("icon-pin")) toggleFog(p, cl);
|
||||
else if (cl.contains("icon-trash-empty")) removeProvince(p);
|
||||
|
|
@ -71,9 +73,8 @@ function editProvinces() {
|
|||
}
|
||||
|
||||
function collectStatistics() {
|
||||
const cells = pack.cells,
|
||||
provinces = pack.provinces,
|
||||
burgs = pack.burgs;
|
||||
const {cells, provinces, burgs} = pack;
|
||||
|
||||
provinces.forEach(p => {
|
||||
if (!p.i || p.removed) return;
|
||||
p.area = p.rural = p.urban = 0;
|
||||
|
|
@ -107,16 +108,18 @@ function editProvinces() {
|
|||
statesSorted.forEach(s => stateFilter.options.add(new Option(s.name, s.i, false, s.i == selectedState)));
|
||||
}
|
||||
|
||||
// add line for each state
|
||||
// add line for each province
|
||||
function provincesEditorAddLines() {
|
||||
const unit = " " + getAreaUnit();
|
||||
const selectedState = +document.getElementById("provincesFilterState").value;
|
||||
let filtered = pack.provinces.filter(p => p.i && !p.removed); // all valid burgs
|
||||
if (selectedState != -1) filtered = filtered.filter(p => p.state === selectedState); // filtered by state
|
||||
body.innerHTML = "";
|
||||
let lines = "",
|
||||
totalArea = 0,
|
||||
totalPopulation = 0;
|
||||
|
||||
let lines = "";
|
||||
let totalArea = 0;
|
||||
let totalPopulation = 0;
|
||||
let totalBurgs = 0;
|
||||
|
||||
for (const p of filtered) {
|
||||
const area = getArea(p.area);
|
||||
|
|
@ -128,6 +131,7 @@ function editProvinces() {
|
|||
rural
|
||||
)}; Urban population: ${si(urban)}`;
|
||||
totalPopulation += population;
|
||||
totalBurgs += p.burgs.length;
|
||||
|
||||
const stateName = pack.states[p.state].name;
|
||||
const capital = p.burg ? pack.burgs[p.burg].name : "";
|
||||
|
|
@ -144,6 +148,7 @@ function editProvinces() {
|
|||
data-state="${stateName}"
|
||||
data-area=${area}
|
||||
data-population=${population}
|
||||
data-burgs=${p.burgs.length}
|
||||
>
|
||||
<fill-box fill="${p.color}"></fill-box>
|
||||
<input data-tip="Province name. Click to change" class="name pointer" value="${p.name}" readonly />
|
||||
|
|
@ -163,6 +168,8 @@ function editProvinces() {
|
|||
${p.burgs.length ? getCapitalOptions(p.burgs, p.burg) : ""}
|
||||
</select>
|
||||
<input data-tip="Province owner" class="provinceOwner" value="${stateName}" disabled">
|
||||
<span data-tip="Click to overview province burgs" style="padding-right: 1px" class="icon-dot-circled pointer hide"></span>
|
||||
<div data-tip="Burgs count" class="provinceBurgs hide">${p.burgs.length}</div>
|
||||
<span data-tip="Province area" style="padding-right: 4px" class="icon-map-o hide"></span>
|
||||
<div data-tip="Province area" class="biomeArea hide">${si(area) + unit}</div>
|
||||
<span data-tip="${populationTip}" class="icon-male hide"></span>
|
||||
|
|
@ -179,11 +186,12 @@ function editProvinces() {
|
|||
body.innerHTML = lines;
|
||||
|
||||
// update footer
|
||||
provincesFooterNumber.innerHTML = filtered.length;
|
||||
provincesFooterArea.innerHTML = filtered.length ? si(totalArea / filtered.length) + unit : 0 + unit;
|
||||
provincesFooterPopulation.innerHTML = filtered.length ? si(totalPopulation / filtered.length) : 0;
|
||||
provincesFooterArea.dataset.area = totalArea;
|
||||
provincesFooterPopulation.dataset.population = totalPopulation;
|
||||
byId("provincesFooterNumber").innerHTML = filtered.length;
|
||||
byId("provincesFooterBurgs").innerHTML = totalBurgs;
|
||||
byId("provincesFooterArea").innerHTML = filtered.length ? si(totalArea / filtered.length) + unit : 0 + unit;
|
||||
byId("provincesFooterPopulation").innerHTML = filtered.length ? si(totalPopulation / filtered.length) : 0;
|
||||
byId("provincesFooterArea").dataset.area = totalArea;
|
||||
byId("provincesFooterPopulation").dataset.population = totalPopulation;
|
||||
|
||||
body.querySelectorAll("div.states").forEach(el => {
|
||||
el.addEventListener("click", selectProvinceOnLineClick);
|
||||
|
|
@ -294,7 +302,7 @@ function editProvinces() {
|
|||
// move all burgs to a new state
|
||||
province.burgs.forEach(b => (burgs[b].state = newStateId));
|
||||
|
||||
// difine new state attributes
|
||||
// define new state attributes
|
||||
const {cell: center, culture} = burgs[burgId];
|
||||
const color = getRandomColor();
|
||||
const coa = province.coa;
|
||||
|
|
@ -501,6 +509,9 @@ function editProvinces() {
|
|||
applyOption(provinceNameEditorSelectForm, p.formName);
|
||||
document.getElementById("provinceNameEditorFull").value = p.fullName;
|
||||
|
||||
const cultureId = pack.cells.culture[p.center];
|
||||
document.getElementById("provinceCultureDisplay").innerText = pack.cultures[cultureId].name;
|
||||
|
||||
$("#provinceNameEditor").dialog({
|
||||
resizable: false,
|
||||
title: "Change province name",
|
||||
|
|
@ -520,12 +531,12 @@ function editProvinces() {
|
|||
modules.editProvinceName = true;
|
||||
|
||||
// add listeners
|
||||
document.getElementById("provinceNameEditorShortCulture").addEventListener("click", regenerateShortNameCuture);
|
||||
document.getElementById("provinceNameEditorShortCulture").addEventListener("click", regenerateShortNameCulture);
|
||||
document.getElementById("provinceNameEditorShortRandom").addEventListener("click", regenerateShortNameRandom);
|
||||
document.getElementById("provinceNameEditorAddForm").addEventListener("click", addCustomForm);
|
||||
document.getElementById("provinceNameEditorFullRegenerate").addEventListener("click", regenerateFullName);
|
||||
|
||||
function regenerateShortNameCuture() {
|
||||
function regenerateShortNameCulture() {
|
||||
const province = +provinceNameEditor.dataset.province;
|
||||
const culture = pack.cells.culture[pack.provinces[province].center];
|
||||
const name = Names.getState(Names.getCultureShort(culture), culture);
|
||||
|
|
@ -576,12 +587,15 @@ function editProvinces() {
|
|||
function togglePercentageMode() {
|
||||
if (body.dataset.type === "absolute") {
|
||||
body.dataset.type = "percentage";
|
||||
const totalBurgs = +byId("provincesFooterBurgs").innerText;
|
||||
const totalArea = +provincesFooterArea.dataset.area;
|
||||
const totalPopulation = +provincesFooterPopulation.dataset.population;
|
||||
|
||||
body.querySelectorAll(":scope > div").forEach(function (el) {
|
||||
el.querySelector(".biomeArea").innerHTML = rn((+el.dataset.area / totalArea) * 100) + "%";
|
||||
el.querySelector(".culturePopulation").innerHTML = rn((+el.dataset.population / totalPopulation) * 100) + "%";
|
||||
const {cells, burgs, area, population} = el.dataset;
|
||||
el.querySelector(".provinceBurgs").innerText = rn((+burgs / totalBurgs) * 100) + "%";
|
||||
el.querySelector(".biomeArea").innerHTML = rn((+area / totalArea) * 100) + "%";
|
||||
el.querySelector(".culturePopulation").innerHTML = rn((+population / totalPopulation) * 100) + "%";
|
||||
});
|
||||
} else {
|
||||
body.dataset.type = "absolute";
|
||||
|
|
@ -872,7 +886,7 @@ function editProvinces() {
|
|||
const p = d3.mouse(this);
|
||||
moveCircle(p[0], p[1], r);
|
||||
|
||||
const found = r > 5 ? findAll(p[0], p[1], r) : [findCell(p[0], p[1], r)];
|
||||
const found = r > 5 ? findAll(p[0], p[1], r) : [findCell(p[0], p[1])];
|
||||
const selection = found.filter(isLand);
|
||||
if (selection) changeForSelection(selection);
|
||||
});
|
||||
|
|
@ -1064,10 +1078,7 @@ function editProvinces() {
|
|||
|
||||
function downloadProvincesData() {
|
||||
const unit = areaUnit.value === "square" ? distanceUnitInput.value + "2" : areaUnit.value;
|
||||
let data =
|
||||
"Id,Province,Full Name,Form,State,Color,Capital,Area " +
|
||||
unit +
|
||||
",Total Population,Rural Population,Urban Population\n"; // headers
|
||||
let data = `Id,Province,Full Name,Form,State,Color,Capital,Area ${unit},Total Population,Rural Population,Urban Population,Burgs\n`; // headers
|
||||
|
||||
body.querySelectorAll(":scope > div").forEach(function (el) {
|
||||
const key = parseInt(el.dataset.id);
|
||||
|
|
@ -1081,8 +1092,9 @@ function editProvinces() {
|
|||
data += el.dataset.capital + ",";
|
||||
data += el.dataset.area + ",";
|
||||
data += el.dataset.population + ",";
|
||||
data += `${Math.round(provincePack.rural * populationRate)},`;
|
||||
data += `${Math.round(provincePack.urban * populationRate * urbanization)}\n`;
|
||||
data += Math.round(provincePack.rural * populationRate) + ",";
|
||||
data += Math.round(provincePack.urban * populationRate * urbanization) + ",";
|
||||
data += el.dataset.burgs + "\n";
|
||||
});
|
||||
|
||||
const name = getFileName("Provinces") + ".csv";
|
||||
|
|
|
|||
|
|
@ -8,9 +8,10 @@ function editRegiment(selector) {
|
|||
armies.selectAll(":scope > g > g").call(d3.drag().on("drag", dragRegiment));
|
||||
elSelected = selector ? document.querySelector(selector) : d3.event.target.parentElement; // select g element
|
||||
if (!pack.states[elSelected.dataset.state]) return;
|
||||
if (!regiment()) return;
|
||||
updateRegimentData(regiment());
|
||||
if (!getRegiment()) return;
|
||||
updateRegimentData(getRegiment());
|
||||
drawBase();
|
||||
drawRotationControl();
|
||||
|
||||
$("#regimentEditor").dialog({
|
||||
title: "Edit Regiment",
|
||||
|
|
@ -37,8 +38,8 @@ function editRegiment(selector) {
|
|||
document.getElementById("regimentRemove").addEventListener("click", removeRegiment);
|
||||
|
||||
// get regiment data element
|
||||
function regiment() {
|
||||
return pack.states[elSelected.dataset.state].military.find(r => r.i == elSelected.dataset.id);
|
||||
function getRegiment() {
|
||||
return pack.states[elSelected.dataset.state]?.military.find(r => r.i == elSelected.dataset.id);
|
||||
}
|
||||
|
||||
function updateRegimentData(regiment) {
|
||||
|
|
@ -60,7 +61,7 @@ function editRegiment(selector) {
|
|||
}
|
||||
|
||||
function drawBase() {
|
||||
const reg = regiment();
|
||||
const reg = getRegiment();
|
||||
const clr = pack.states[elSelected.dataset.state].color;
|
||||
const base = viewbox
|
||||
.insert("g", "g#armies")
|
||||
|
|
@ -69,12 +70,8 @@ function editRegiment(selector) {
|
|||
.attr("stroke", "#000")
|
||||
.attr("cursor", "move");
|
||||
base
|
||||
.on("mouseenter", () => {
|
||||
tip("Regiment base. Drag to re-base the regiment", true);
|
||||
})
|
||||
.on("mouseleave", () => {
|
||||
tip("", true);
|
||||
});
|
||||
.on("mouseenter", () => tip("Regiment base. Drag to re-base the regiment", true))
|
||||
.on("mouseleave", () => tip("", true));
|
||||
|
||||
base
|
||||
.append("line")
|
||||
|
|
@ -92,8 +89,42 @@ function editRegiment(selector) {
|
|||
.call(d3.drag().on("drag", dragBase));
|
||||
}
|
||||
|
||||
function drawRotationControl() {
|
||||
const reg = getRegiment();
|
||||
const {x, width, y, height} = elSelected.getBBox();
|
||||
|
||||
debug
|
||||
.append("circle")
|
||||
.attr("id", "rotationControl")
|
||||
.attr("cx", x + width)
|
||||
.attr("cy", y + height / 2)
|
||||
.attr("r", 1)
|
||||
.attr("opacity", 1)
|
||||
.attr("fill", "yellow")
|
||||
.attr("stroke-width", 0.3)
|
||||
.attr("stroke", "black")
|
||||
.attr("cursor", "alias")
|
||||
.attr("transform", `rotate(${reg.angle || 0})`)
|
||||
.attr("transform-origin", `${reg.x}px ${reg.y}px`)
|
||||
.on("mouseenter", () => tip("Drag to rotate the regiment", true))
|
||||
.on("mouseleave", () => tip("", true))
|
||||
.call(d3.drag().on("start", rotateRegiment));
|
||||
}
|
||||
|
||||
function rotateRegiment() {
|
||||
const reg = getRegiment();
|
||||
|
||||
d3.event.on("drag", function () {
|
||||
const {x, y} = d3.event;
|
||||
const angle = rn(Math.atan2(y - reg.y, x - reg.x) * (180 / Math.PI), 2);
|
||||
elSelected.setAttribute("transform", `rotate(${angle})`);
|
||||
this.setAttribute("transform", `rotate(${angle})`);
|
||||
reg.angle = rn(angle, 2);
|
||||
});
|
||||
}
|
||||
|
||||
function changeType() {
|
||||
const reg = regiment();
|
||||
const reg = getRegiment();
|
||||
reg.n = +!reg.n;
|
||||
document.getElementById("regimentType").className = reg.n ? "icon-anchor" : "icon-users";
|
||||
|
||||
|
|
@ -110,11 +141,11 @@ function editRegiment(selector) {
|
|||
}
|
||||
|
||||
function changeName() {
|
||||
elSelected.dataset.name = regiment().name = this.value;
|
||||
elSelected.dataset.name = getRegiment().name = this.value;
|
||||
}
|
||||
|
||||
function restoreName() {
|
||||
const reg = regiment(),
|
||||
const reg = getRegiment(),
|
||||
regs = pack.states[elSelected.dataset.state].military;
|
||||
const name = Military.getName(reg, regs);
|
||||
elSelected.dataset.name = reg.name = document.getElementById("regimentName").value = name;
|
||||
|
|
@ -129,12 +160,12 @@ function editRegiment(selector) {
|
|||
|
||||
function changeEmblem() {
|
||||
const emblem = document.getElementById("regimentEmblem").value;
|
||||
regiment().icon = elSelected.querySelector(".regimentIcon").innerHTML = emblem;
|
||||
getRegiment().icon = elSelected.querySelector(".regimentIcon").innerHTML = emblem;
|
||||
}
|
||||
|
||||
function changeUnit() {
|
||||
const u = this.dataset.u;
|
||||
const reg = regiment();
|
||||
const reg = getRegiment();
|
||||
reg.u[u] = +this.value || 0;
|
||||
reg.a = d3.sum(Object.values(reg.u));
|
||||
elSelected.querySelector("text").innerHTML = Military.getTotal(reg);
|
||||
|
|
@ -143,7 +174,7 @@ function editRegiment(selector) {
|
|||
}
|
||||
|
||||
function splitRegiment() {
|
||||
const reg = regiment(),
|
||||
const reg = getRegiment(),
|
||||
u1 = reg.u;
|
||||
const state = +elSelected.dataset.state,
|
||||
military = pack.states[state].military;
|
||||
|
|
@ -206,8 +237,7 @@ function editRegiment(selector) {
|
|||
function addRegimentOnClick() {
|
||||
const point = d3.mouse(this);
|
||||
const cell = findCell(point[0], point[1]);
|
||||
const x = pack.cells.p[cell][0],
|
||||
y = pack.cells.p[cell][1];
|
||||
const [x, y] = pack.cells.p[cell];
|
||||
const state = +elSelected.dataset.state,
|
||||
military = pack.states[state].military;
|
||||
const i = military.length ? last(military).i + 1 : 0;
|
||||
|
|
@ -254,7 +284,7 @@ function editRegiment(selector) {
|
|||
return;
|
||||
}
|
||||
|
||||
const attacker = regiment();
|
||||
const attacker = getRegiment();
|
||||
const defender = pack.states[regSelected.dataset.state].military.find(r => r.i == regSelected.dataset.id);
|
||||
if (!attacker.a || !defender.a) {
|
||||
tip("Regiment has no troops to battle", false, "error");
|
||||
|
|
@ -322,7 +352,7 @@ function editRegiment(selector) {
|
|||
return;
|
||||
}
|
||||
|
||||
const reg = regiment(); // reg to be attached
|
||||
const reg = getRegiment(); // reg to be attached
|
||||
const sel = pack.states[newState].military.find(r => r.i == regSelected.dataset.id); // reg to attach to
|
||||
|
||||
for (const unit of options.military) {
|
||||
|
|
@ -349,11 +379,11 @@ function editRegiment(selector) {
|
|||
if (index != -1) notes.splice(index, 1);
|
||||
|
||||
const s = pack.states[elSelected.dataset.state];
|
||||
Military.generateNote(regiment(), s);
|
||||
Military.generateNote(getRegiment(), s);
|
||||
}
|
||||
|
||||
function editLegend() {
|
||||
editNotes(elSelected.id, regiment().name);
|
||||
editNotes(elSelected.id, getRegiment().name);
|
||||
}
|
||||
|
||||
function removeRegiment() {
|
||||
|
|
@ -365,7 +395,7 @@ function editRegiment(selector) {
|
|||
Remove: function () {
|
||||
$(this).dialog("close");
|
||||
const military = pack.states[elSelected.dataset.state].military;
|
||||
const regIndex = military.indexOf(regiment());
|
||||
const regIndex = military.indexOf(getRegiment());
|
||||
if (regIndex === -1) return;
|
||||
military.splice(regIndex, 1);
|
||||
|
||||
|
|
@ -392,8 +422,6 @@ function editRegiment(selector) {
|
|||
const size = +armies.attr("box-size");
|
||||
const w = reg.n ? size * 4 : size * 6;
|
||||
const h = size * 2;
|
||||
const x1 = x => rn(x - w / 2, 2);
|
||||
const y1 = y => rn(y - size, 2);
|
||||
|
||||
const baseRect = this.querySelector("rect");
|
||||
const text = this.querySelector("text");
|
||||
|
|
@ -402,26 +430,37 @@ function editRegiment(selector) {
|
|||
|
||||
const self = elSelected === this;
|
||||
const baseLine = viewbox.select("g#regimentBase > line");
|
||||
const rotationControl = debug.select("#rotationControl");
|
||||
|
||||
d3.event.on("drag", function () {
|
||||
const x = (reg.x = d3.event.x),
|
||||
y = (reg.y = d3.event.y);
|
||||
const {x, y} = d3.event;
|
||||
reg.x = x;
|
||||
reg.y = y;
|
||||
const x1 = rn(x - w / 2, 2);
|
||||
const y1 = rn(y - size, 2);
|
||||
|
||||
baseRect.setAttribute("x", x1(x));
|
||||
baseRect.setAttribute("y", y1(y));
|
||||
this.setAttribute("transform-origin", `${x}px ${y}px`);
|
||||
baseRect.setAttribute("x", x1);
|
||||
baseRect.setAttribute("y", y1);
|
||||
text.setAttribute("x", x);
|
||||
text.setAttribute("y", y);
|
||||
iconRect.setAttribute("x", x1(x) - h);
|
||||
iconRect.setAttribute("y", y1(y));
|
||||
icon.setAttribute("x", x1(x) - size);
|
||||
iconRect.setAttribute("x", x1 - h);
|
||||
iconRect.setAttribute("y", y1);
|
||||
icon.setAttribute("x", x1 - size);
|
||||
icon.setAttribute("y", y);
|
||||
if (self) baseLine.attr("x2", x).attr("y2", y);
|
||||
if (self) {
|
||||
baseLine.attr("x2", x).attr("y2", y);
|
||||
rotationControl
|
||||
.attr("cx", x1 + w)
|
||||
.attr("cy", y)
|
||||
.attr("transform-origin", `${x}px ${y}px`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function dragBase() {
|
||||
const baseLine = viewbox.select("g#regimentBase > line");
|
||||
const reg = regiment();
|
||||
const reg = getRegiment();
|
||||
|
||||
d3.event.on("drag", function () {
|
||||
this.setAttribute("cx", d3.event.x);
|
||||
|
|
@ -436,9 +475,10 @@ function editRegiment(selector) {
|
|||
}
|
||||
|
||||
function closeEditor() {
|
||||
debug.selectAll("*").remove();
|
||||
viewbox.selectAll("g#regimentBase").remove();
|
||||
armies.selectAll(":scope > g").classed("draggable", false);
|
||||
armies.selectAll("g>g").call(d3.drag().on("drag", null));
|
||||
viewbox.selectAll("g#regimentBase").remove();
|
||||
document.getElementById("regimentAdd").classList.remove("pressed");
|
||||
document.getElementById("regimentAttack").classList.remove("pressed");
|
||||
document.getElementById("regimentAttach").classList.remove("pressed");
|
||||
|
|
|
|||
|
|
@ -5,12 +5,15 @@ function editRiver(id) {
|
|||
closeDialogs(".stable");
|
||||
if (!layerIsOn("toggleRivers")) toggleRivers();
|
||||
|
||||
document.getElementById("toggleCells").dataset.forced = +!layerIsOn("toggleCells");
|
||||
byId("toggleCells").dataset.forced = +!layerIsOn("toggleCells");
|
||||
if (!layerIsOn("toggleCells")) toggleCells();
|
||||
|
||||
elSelected = d3.select("#" + id).on("click", addControlPoint);
|
||||
|
||||
tip("Drag control points to change the river course. Click on point to remove it. Click on river to add additional control point. For major changes please create a new river instead", true);
|
||||
tip(
|
||||
"Drag control points to change the river course. Click on point to remove it. Click on river to add additional control point. For major changes please create a new river instead",
|
||||
true
|
||||
);
|
||||
debug.append("g").attr("id", "controlCells");
|
||||
debug.append("g").attr("id", "controlPoints");
|
||||
|
||||
|
|
@ -33,18 +36,18 @@ function editRiver(id) {
|
|||
modules.editRiver = true;
|
||||
|
||||
// add listeners
|
||||
document.getElementById("riverCreateSelectingCells").addEventListener("click", createRiver);
|
||||
document.getElementById("riverEditStyle").addEventListener("click", () => editStyle("rivers"));
|
||||
document.getElementById("riverElevationProfile").addEventListener("click", showElevationProfile);
|
||||
document.getElementById("riverLegend").addEventListener("click", editRiverLegend);
|
||||
document.getElementById("riverRemove").addEventListener("click", removeRiver);
|
||||
document.getElementById("riverName").addEventListener("input", changeName);
|
||||
document.getElementById("riverType").addEventListener("input", changeType);
|
||||
document.getElementById("riverNameCulture").addEventListener("click", generateNameCulture);
|
||||
document.getElementById("riverNameRandom").addEventListener("click", generateNameRandom);
|
||||
document.getElementById("riverMainstem").addEventListener("change", changeParent);
|
||||
document.getElementById("riverSourceWidth").addEventListener("input", changeSourceWidth);
|
||||
document.getElementById("riverWidthFactor").addEventListener("input", changeWidthFactor);
|
||||
byId("riverCreateSelectingCells").on("click", createRiver);
|
||||
byId("riverEditStyle").on("click", () => editStyle("rivers"));
|
||||
byId("riverElevationProfile").on("click", showRiverElevationProfile);
|
||||
byId("riverLegend").on("click", editRiverLegend);
|
||||
byId("riverRemove").on("click", removeRiver);
|
||||
byId("riverName").on("input", changeName);
|
||||
byId("riverType").on("input", changeType);
|
||||
byId("riverNameCulture").on("click", generateNameCulture);
|
||||
byId("riverNameRandom").on("click", generateNameRandom);
|
||||
byId("riverMainstem").on("change", changeParent);
|
||||
byId("riverSourceWidth").on("input", changeSourceWidth);
|
||||
byId("riverWidthFactor").on("input", changeWidthFactor);
|
||||
|
||||
function getRiver() {
|
||||
const riverId = +elSelected.attr("id").slice(5);
|
||||
|
|
@ -55,10 +58,10 @@ function editRiver(id) {
|
|||
function updateRiverData() {
|
||||
const r = getRiver();
|
||||
|
||||
document.getElementById("riverName").value = r.name;
|
||||
document.getElementById("riverType").value = r.type;
|
||||
byId("riverName").value = r.name;
|
||||
byId("riverType").value = r.type;
|
||||
|
||||
const parentSelect = document.getElementById("riverMainstem");
|
||||
const parentSelect = byId("riverMainstem");
|
||||
parentSelect.options.length = 0;
|
||||
const parent = r.parent || r.i;
|
||||
const sortedRivers = pack.rivers.slice().sort((a, b) => (a.name > b.name ? 1 : -1));
|
||||
|
|
@ -66,11 +69,11 @@ function editRiver(id) {
|
|||
const opt = new Option(river.name, river.i, false, river.i === parent);
|
||||
parentSelect.options.add(opt);
|
||||
});
|
||||
document.getElementById("riverBasin").value = pack.rivers.find(river => river.i === r.basin).name;
|
||||
byId("riverBasin").value = pack.rivers.find(river => river.i === r.basin).name;
|
||||
|
||||
document.getElementById("riverDischarge").value = r.discharge + " m³/s";
|
||||
document.getElementById("riverSourceWidth").value = r.sourceWidth;
|
||||
document.getElementById("riverWidthFactor").value = r.widthFactor;
|
||||
byId("riverDischarge").value = r.discharge + " m³/s";
|
||||
byId("riverSourceWidth").value = r.sourceWidth;
|
||||
byId("riverWidthFactor").value = r.widthFactor;
|
||||
|
||||
updateRiverLength(r);
|
||||
updateRiverWidth(r);
|
||||
|
|
@ -78,8 +81,8 @@ function editRiver(id) {
|
|||
|
||||
function updateRiverLength(river) {
|
||||
river.length = rn(elSelected.node().getTotalLength() / 2, 2);
|
||||
const lengthUI = `${rn(river.length * distanceScaleInput.value)} ${distanceUnitInput.value}`;
|
||||
document.getElementById("riverLength").value = lengthUI;
|
||||
const lengthUI = `${rn(river.length * distanceScale)} ${distanceUnitInput.value}`;
|
||||
byId("riverLength").value = lengthUI;
|
||||
}
|
||||
|
||||
function updateRiverWidth(river) {
|
||||
|
|
@ -88,8 +91,8 @@ function editRiver(id) {
|
|||
const meanderedPoints = addMeandering(cells);
|
||||
river.width = getWidth(getOffset(discharge, meanderedPoints.length, widthFactor, sourceWidth));
|
||||
|
||||
const width = `${rn(river.width * distanceScaleInput.value, 3)} ${distanceUnitInput.value}`;
|
||||
document.getElementById("riverWidth").value = width;
|
||||
const width = `${rn(river.width * distanceScale, 3)} ${distanceUnitInput.value}`;
|
||||
byId("riverWidth").value = width;
|
||||
}
|
||||
|
||||
function drawControlPoints(points) {
|
||||
|
|
@ -163,7 +166,7 @@ function editRiver(id) {
|
|||
elSelected.attr("d", path);
|
||||
|
||||
updateRiverLength(river);
|
||||
if (modules.elevation) showEPForRiver(elSelected.node());
|
||||
if (byId("elevationProfile").offsetParent) showRiverElevationProfile();
|
||||
}
|
||||
|
||||
function addControlPoint() {
|
||||
|
|
@ -209,7 +212,7 @@ function editRiver(id) {
|
|||
const r = getRiver();
|
||||
r.parent = +this.value;
|
||||
r.basin = pack.rivers.find(river => river.i === r.parent).basin;
|
||||
document.getElementById("riverBasin").value = pack.rivers.find(river => river.i === r.basin).name;
|
||||
byId("riverBasin").value = pack.rivers.find(river => river.i === r.basin).name;
|
||||
}
|
||||
|
||||
function changeSourceWidth() {
|
||||
|
|
@ -226,9 +229,14 @@ function editRiver(id) {
|
|||
redrawRiver();
|
||||
}
|
||||
|
||||
function showElevationProfile() {
|
||||
modules.elevation = true;
|
||||
showEPForRiver(elSelected.node());
|
||||
function showRiverElevationProfile() {
|
||||
const points = debug
|
||||
.selectAll("#controlPoints > *")
|
||||
.data()
|
||||
.map(([x, y]) => findCell(x, y));
|
||||
const river = getRiver();
|
||||
const riverLen = rn(river.length * distanceScale);
|
||||
showElevationProfile(points, riverLen, true);
|
||||
}
|
||||
|
||||
function editRiverLegend() {
|
||||
|
|
@ -266,8 +274,8 @@ function editRiver(id) {
|
|||
unselect();
|
||||
clearMainTip();
|
||||
|
||||
const forced = +document.getElementById("toggleCells").dataset.forced;
|
||||
document.getElementById("toggleCells").dataset.forced = 0;
|
||||
const forced = +byId("toggleCells").dataset.forced;
|
||||
byId("toggleCells").dataset.forced = 0;
|
||||
if (forced && layerIsOn("toggleCells")) toggleCells();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
"use strict";
|
||||
|
||||
function overviewRivers() {
|
||||
if (customization) return;
|
||||
closeDialogs("#riversOverview, .stable");
|
||||
|
|
@ -34,8 +35,8 @@ function overviewRivers() {
|
|||
|
||||
for (const r of pack.rivers) {
|
||||
const discharge = r.discharge + " m³/s";
|
||||
const length = rn(r.length * distanceScaleInput.value) + " " + unit;
|
||||
const width = rn(r.width * distanceScaleInput.value, 3) + " " + unit;
|
||||
const length = rn(r.length * distanceScale) + " " + unit;
|
||||
const width = rn(r.width * distanceScale, 3) + " " + unit;
|
||||
const basin = pack.rivers.find(river => river.i === r.basin)?.name;
|
||||
|
||||
lines += /* html */ `<div
|
||||
|
|
@ -49,7 +50,7 @@ function overviewRivers() {
|
|||
data-basin="${basin}"
|
||||
>
|
||||
<span data-tip="Click to focus on river" class="icon-dot-circled pointer"></span>
|
||||
<div data-tip="River name" class="riverName">${r.name}</div>
|
||||
<div data-tip="River name" style="margin-left: 0.4em;" class="riverName">${r.name}</div>
|
||||
<div data-tip="River type name" class="riverType">${r.type}</div>
|
||||
<div data-tip="River discharge (flux power)" class="biomeArea">${discharge}</div>
|
||||
<div data-tip="River length from source to mouth" class="biomeArea">${length}</div>
|
||||
|
|
@ -66,16 +67,18 @@ function overviewRivers() {
|
|||
const averageDischarge = rn(d3.mean(pack.rivers.map(r => r.discharge)));
|
||||
riversFooterDischarge.innerHTML = averageDischarge + " m³/s";
|
||||
const averageLength = rn(d3.mean(pack.rivers.map(r => r.length)));
|
||||
riversFooterLength.innerHTML = averageLength * distanceScaleInput.value + " " + unit;
|
||||
riversFooterLength.innerHTML = averageLength * distanceScale + " " + unit;
|
||||
const averageWidth = rn(d3.mean(pack.rivers.map(r => r.width)), 3);
|
||||
riversFooterWidth.innerHTML = rn(averageWidth * distanceScaleInput.value, 3) + " " + unit;
|
||||
riversFooterWidth.innerHTML = rn(averageWidth * distanceScale, 3) + " " + unit;
|
||||
|
||||
// add listeners
|
||||
body.querySelectorAll("div.states").forEach(el => el.addEventListener("mouseenter", ev => riverHighlightOn(ev)));
|
||||
body.querySelectorAll("div.states").forEach(el => el.addEventListener("mouseleave", ev => riverHighlightOff(ev)));
|
||||
body.querySelectorAll("div > span.icon-dot-circled").forEach(el => el.addEventListener("click", zoomToRiver));
|
||||
body.querySelectorAll("div > span.icon-pencil").forEach(el => el.addEventListener("click", openRiverEditor));
|
||||
body.querySelectorAll("div > span.icon-trash-empty").forEach(el => el.addEventListener("click", triggerRiverRemove));
|
||||
body
|
||||
.querySelectorAll("div > span.icon-trash-empty")
|
||||
.forEach(el => el.addEventListener("click", triggerRiverRemove));
|
||||
|
||||
applySorting(riversHeader);
|
||||
}
|
||||
|
|
@ -110,7 +113,18 @@ function overviewRivers() {
|
|||
} else {
|
||||
rivers.attr("data-basin", "hightlighted");
|
||||
const basins = [...new Set(pack.rivers.map(r => r.basin))];
|
||||
const colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"];
|
||||
const colors = [
|
||||
"#1f77b4",
|
||||
"#ff7f0e",
|
||||
"#2ca02c",
|
||||
"#d62728",
|
||||
"#9467bd",
|
||||
"#8c564b",
|
||||
"#e377c2",
|
||||
"#7f7f7f",
|
||||
"#bcbd22",
|
||||
"#17becf"
|
||||
];
|
||||
|
||||
basins.forEach((b, i) => {
|
||||
const color = colors[i % colors.length];
|
||||
|
|
@ -129,8 +143,8 @@ function overviewRivers() {
|
|||
body.querySelectorAll(":scope > div").forEach(function (el) {
|
||||
const d = el.dataset;
|
||||
const discharge = d.discharge + " m³/s";
|
||||
const length = rn(d.length * distanceScaleInput.value) + " " + distanceUnitInput.value;
|
||||
const width = rn(d.width * distanceScaleInput.value, 3) + " " + distanceUnitInput.value;
|
||||
const length = rn(d.length * distanceScale) + " " + distanceUnitInput.value;
|
||||
const width = rn(d.width * distanceScale, 3) + " " + distanceUnitInput.value;
|
||||
data += [d.id, d.name, d.type, discharge, length, width, d.basin].join(",") + "\n";
|
||||
});
|
||||
|
||||
|
|
|
|||
85
modules/ui/route-group-editor.js
Normal file
85
modules/ui/route-group-editor.js
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
"use strict";
|
||||
|
||||
function editRouteGroups() {
|
||||
if (customization) return;
|
||||
if (!layerIsOn("toggleRoutes")) toggleRoutes();
|
||||
|
||||
addLines();
|
||||
|
||||
$("#routeGroupsEditor").dialog({
|
||||
title: "Edit Route groups",
|
||||
resizable: false,
|
||||
position: {my: "left top", at: "left+10 top+140", of: "#map"}
|
||||
});
|
||||
|
||||
if (modules.editRouteGroups) return;
|
||||
modules.editRouteGroups = true;
|
||||
|
||||
// add listeners
|
||||
byId("routeGroupsEditorAdd").addEventListener("click", addGroup);
|
||||
byId("routeGroupsEditorBody").on("click", ev => {
|
||||
const group = ev.target.parentNode.dataset.id;
|
||||
if (ev.target.classList.contains("editStyle")) editStyle("routes", group);
|
||||
else if (ev.target.classList.contains("removeGroup")) removeGroup(group);
|
||||
});
|
||||
|
||||
function addLines() {
|
||||
byId("routeGroupsEditorBody").innerHTML = "";
|
||||
|
||||
const lines = Array.from(routes.selectAll("g")._groups[0]).map(el => {
|
||||
const count = el.children.length;
|
||||
return /* html */ `<div data-id="${el.id}" class="states" style="display: flex; justify-content: space-between;">
|
||||
<span>${el.id} (${count})</span>
|
||||
<div style="width: auto; display: flex; gap: 0.4em;">
|
||||
<span data-tip="Edit style" class="editStyle icon-brush pointer" style="font-size: smaller;"></span>
|
||||
<span data-tip="Remove group" class="removeGroup icon-trash pointer"></span>
|
||||
</div>
|
||||
</div>`;
|
||||
});
|
||||
|
||||
byId("routeGroupsEditorBody").innerHTML = lines.join("");
|
||||
}
|
||||
|
||||
const DEFAULT_GROUPS = ["roads", "trails", "searoutes"];
|
||||
|
||||
function addGroup() {
|
||||
prompt("Type group name", {default: "route-group-new"}, v => {
|
||||
let group = v
|
||||
.toLowerCase()
|
||||
.replace(/ /g, "_")
|
||||
.replace(/[^\w\s]/gi, "");
|
||||
|
||||
if (!group) return tip("Invalid group name", false, "error");
|
||||
if (!group.startsWith("route-")) group = "route-" + group;
|
||||
if (byId(group)) return tip("Element with this name already exists. Provide a unique name", false, "error");
|
||||
if (Number.isFinite(+group.charAt(0))) return tip("Group name should start with a letter", false, "error");
|
||||
|
||||
routes
|
||||
.append("g")
|
||||
.attr("id", group)
|
||||
.attr("stroke", "#000000")
|
||||
.attr("stroke-width", 0.5)
|
||||
.attr("stroke-dasharray", "1 0.5")
|
||||
.attr("stroke-linecap", "butt");
|
||||
byId("routeGroup")?.options.add(new Option(group, group));
|
||||
addLines();
|
||||
|
||||
byId("routeCreatorGroupSelect").options.add(new Option(group, group));
|
||||
});
|
||||
}
|
||||
|
||||
function removeGroup(group) {
|
||||
confirmationDialog({
|
||||
title: "Remove route group",
|
||||
message:
|
||||
"Are you sure you want to remove the entire route group? All routes in this group will be removed. This action can't be reverted.",
|
||||
confirm: "Remove",
|
||||
onConfirm: () => {
|
||||
const routes = pack.routes.filter(r => r.group === group);
|
||||
routes.forEach(r => Routes.remove(r));
|
||||
if (DEFAULT_GROUPS.includes(group)) routes.select(`#${group}`).remove();
|
||||
addLines();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
140
modules/ui/routes-creator.js
Normal file
140
modules/ui/routes-creator.js
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
"use strict";
|
||||
|
||||
function createRoute(defaultGroup) {
|
||||
if (customization) return;
|
||||
closeDialogs();
|
||||
if (!layerIsOn("toggleRoutes")) toggleRoutes();
|
||||
|
||||
byId("toggleCells").dataset.forced = +!layerIsOn("toggleCells");
|
||||
if (!layerIsOn("toggleCells")) toggleCells();
|
||||
|
||||
tip("Click to add route point, click again to remove", true);
|
||||
debug.append("g").attr("id", "controlCells");
|
||||
debug.append("g").attr("id", "controlPoints");
|
||||
viewbox.style("cursor", "crosshair").on("click", onClick);
|
||||
|
||||
createRoute.points = [];
|
||||
const body = byId("routeCreatorBody");
|
||||
|
||||
// update route groups
|
||||
byId("routeCreatorGroupSelect").innerHTML = Array.from(routes.selectAll("g")._groups[0]).map(el => {
|
||||
const selected = defaultGroup || "roads";
|
||||
return `<option value="${el.id}" ${el.id === selected ? "selected" : ""}>${el.id}</option>`;
|
||||
});
|
||||
|
||||
$("#routeCreator").dialog({
|
||||
title: "Create Route",
|
||||
resizable: false,
|
||||
position: {my: "left top", at: "left+10 top+10", of: "#map"},
|
||||
close: closeRouteCreator
|
||||
});
|
||||
|
||||
if (modules.createRoute) return;
|
||||
modules.createRoute = true;
|
||||
|
||||
// add listeners
|
||||
byId("routeCreatorGroupSelect").on("change", () => drawRoute(createRoute.points));
|
||||
byId("routeCreatorGroupEdit").on("click", editRouteGroups);
|
||||
byId("routeCreatorComplete").on("click", completeCreation);
|
||||
byId("routeCreatorCancel").on("click", () => $("#routeCreator").dialog("close"));
|
||||
body.on("click", ev => {
|
||||
if (ev.target.classList.contains("icon-trash-empty")) removePoint(ev.target.parentNode.dataset.point);
|
||||
});
|
||||
|
||||
function onClick() {
|
||||
const [x, y] = d3.mouse(this);
|
||||
const cellId = findCell(x, y);
|
||||
const point = [rn(x, 2), rn(y, 2), cellId];
|
||||
createRoute.points.push(point);
|
||||
|
||||
drawRoute(createRoute.points);
|
||||
|
||||
body.innerHTML += `<div class="editorLine" style="display: grid; grid-template-columns: 1fr 1fr 1fr auto; gap: 1em;" data-point="${point.join(
|
||||
"-"
|
||||
)}">
|
||||
<span><b>Cell</b>: ${cellId}</span>
|
||||
<span><b>X</b>: ${point[0]}</span>
|
||||
<span><b>Y</b>: ${point[1]}</span>
|
||||
<span data-tip="Remove the point" class="icon-trash-empty pointer"></span>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function removePoint(pointString) {
|
||||
createRoute.points = createRoute.points.filter(p => p.join("-") !== pointString);
|
||||
drawRoute(createRoute.points);
|
||||
body.querySelector(`[data-point='${pointString}']`)?.remove();
|
||||
}
|
||||
|
||||
function drawRoute(points) {
|
||||
debug
|
||||
.select("#controlCells")
|
||||
.selectAll("polygon")
|
||||
.data(points)
|
||||
.join("polygon")
|
||||
.attr("points", p => getPackPolygon(p[2]))
|
||||
.attr("class", "current");
|
||||
|
||||
debug
|
||||
.select("#controlPoints")
|
||||
.selectAll("circle")
|
||||
.data(points)
|
||||
.join("circle")
|
||||
.attr("cx", d => d[0])
|
||||
.attr("cy", d => d[1])
|
||||
.attr("r", 0.6);
|
||||
|
||||
const group = byId("routeCreatorGroupSelect").value;
|
||||
|
||||
routes.select("#routeTemp").remove();
|
||||
routes
|
||||
.select("#" + group)
|
||||
.append("path")
|
||||
.attr("d", Routes.getPath({group, points}))
|
||||
.attr("id", "routeTemp");
|
||||
}
|
||||
|
||||
function completeCreation() {
|
||||
const points = createRoute.points;
|
||||
if (points.length < 2) return tip("Add at least 2 points", false, "error");
|
||||
|
||||
const routeId = Routes.getNextId();
|
||||
const group = byId("routeCreatorGroupSelect").value;
|
||||
const feature = pack.cells.f[points[0][2]];
|
||||
const route = {points, group, feature, i: routeId};
|
||||
pack.routes.push(route);
|
||||
|
||||
const links = pack.cells.routes;
|
||||
for (let i = 0; i < points.length; i++) {
|
||||
const point = points[i];
|
||||
const nextPoint = points[i + 1];
|
||||
|
||||
if (nextPoint) {
|
||||
const cellId = point[2];
|
||||
const nextId = nextPoint[2];
|
||||
|
||||
if (!links[cellId]) links[cellId] = {};
|
||||
links[cellId][nextId] = routeId;
|
||||
|
||||
if (!links[nextId]) links[nextId] = {};
|
||||
links[nextId][cellId] = routeId;
|
||||
}
|
||||
}
|
||||
|
||||
routes.select("#routeTemp").attr("id", "route" + routeId);
|
||||
editRoute("route" + routeId);
|
||||
}
|
||||
|
||||
function closeRouteCreator() {
|
||||
body.innerHTML = "";
|
||||
debug.select("#controlCells").remove();
|
||||
debug.select("#controlPoints").remove();
|
||||
routes.select("#routeTemp").remove();
|
||||
|
||||
restoreDefaultEvents();
|
||||
clearMainTip();
|
||||
|
||||
const forced = +byId("toggleCells").dataset.forced;
|
||||
byId("toggleCells").dataset.forced = 0;
|
||||
if (forced && layerIsOn("toggleCells")) toggleCells();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,308 +1,403 @@
|
|||
"use strict";
|
||||
|
||||
const CONTROL_POINST_DISTANCE = 10;
|
||||
|
||||
function editRoute(onClick) {
|
||||
function editRoute(id) {
|
||||
if (customization) return;
|
||||
if (!onClick && elSelected && d3.event.target.id === elSelected.attr("id")) return;
|
||||
if (elSelected && id === elSelected.attr("id")) return;
|
||||
closeDialogs(".stable");
|
||||
|
||||
if (!layerIsOn("toggleRoutes")) toggleRoutes();
|
||||
byId("toggleCells").dataset.forced = +!layerIsOn("toggleCells");
|
||||
if (!layerIsOn("toggleCells")) toggleCells();
|
||||
|
||||
elSelected = d3.select("#" + id).on("click", addControlPoint);
|
||||
|
||||
tip(
|
||||
"Drag control points to change the route. Click on point to remove it. Click on the route to add additional control point. For major changes please create a new route instead",
|
||||
true
|
||||
);
|
||||
debug.append("g").attr("id", "controlCells");
|
||||
debug.append("g").attr("id", "controlPoints");
|
||||
|
||||
{
|
||||
const route = getRoute();
|
||||
updateRouteData(route);
|
||||
drawControlPoints(route.points);
|
||||
drawCells(route.points);
|
||||
updateLockIcon();
|
||||
}
|
||||
|
||||
$("#routeEditor").dialog({
|
||||
title: "Edit Route",
|
||||
resizable: false,
|
||||
position: {my: "center top+60", at: "top", of: d3.event, collision: "fit"},
|
||||
close: closeRoutesEditor
|
||||
position: {my: "left top", at: "left+10 top+10", of: "#map"},
|
||||
close: closeRouteEditor
|
||||
});
|
||||
|
||||
debug.append("g").attr("id", "controlPoints");
|
||||
const node = onClick ? elSelected.node() : d3.event.target;
|
||||
elSelected = d3.select(node).on("click", addInterimControlPoint);
|
||||
drawControlPoints(node);
|
||||
selectRouteGroup(node);
|
||||
|
||||
viewbox.on("touchmove mousemove", showEditorTips);
|
||||
if (onClick) toggleRouteCreationMode();
|
||||
|
||||
if (modules.editRoute) return;
|
||||
modules.editRoute = true;
|
||||
|
||||
// add listeners
|
||||
document.getElementById("routeGroupsShow").addEventListener("click", showGroupSection);
|
||||
document.getElementById("routeGroup").addEventListener("change", changeRouteGroup);
|
||||
document.getElementById("routeGroupAdd").addEventListener("click", toggleNewGroupInput);
|
||||
document.getElementById("routeGroupName").addEventListener("change", createNewGroup);
|
||||
document.getElementById("routeGroupRemove").addEventListener("click", removeRouteGroup);
|
||||
document.getElementById("routeGroupsHide").addEventListener("click", hideGroupSection);
|
||||
document.getElementById("routeElevationProfile").addEventListener("click", showElevationProfile);
|
||||
byId("routeCreateSelectingCells").on("click", showCreationDialog);
|
||||
byId("routeSplit").on("click", togglePressed);
|
||||
byId("routeJoin").on("click", openJoinRoutesDialog);
|
||||
byId("routeElevationProfile").on("click", showRouteElevationProfile);
|
||||
byId("routeLegend").on("click", editRouteLegend);
|
||||
byId("routeLock").on("click", toggleLockButton);
|
||||
byId("routeRemove").on("click", removeRoute);
|
||||
byId("routeName").on("input", changeName);
|
||||
byId("routeGroup").on("input", changeGroup);
|
||||
byId("routeGroupEdit").on("click", editRouteGroups);
|
||||
byId("routeEditStyle").on("click", editRouteGroupStyle);
|
||||
byId("routeGenerateName").on("click", generateName);
|
||||
|
||||
document.getElementById("routeEditStyle").addEventListener("click", editGroupStyle);
|
||||
document.getElementById("routeSplit").addEventListener("click", toggleRouteSplitMode);
|
||||
document.getElementById("routeLegend").addEventListener("click", editRouteLegend);
|
||||
document.getElementById("routeNew").addEventListener("click", toggleRouteCreationMode);
|
||||
document.getElementById("routeRemove").addEventListener("click", removeRoute);
|
||||
|
||||
function showEditorTips() {
|
||||
showMainTip();
|
||||
if (routeNew.classList.contains("pressed")) return;
|
||||
if (d3.event.target.id === elSelected.attr("id")) tip("Click to add a control point");
|
||||
else if (d3.event.target.parentNode.id === "controlPoints") tip("Drag to move, click to delete the control point");
|
||||
function getRoute() {
|
||||
const routeId = +elSelected.attr("id").slice(5);
|
||||
return pack.routes.find(route => route.i === routeId);
|
||||
}
|
||||
|
||||
function drawControlPoints(node) {
|
||||
const totalLength = node.getTotalLength();
|
||||
const increment = totalLength / Math.ceil(totalLength / CONTROL_POINST_DISTANCE);
|
||||
for (let i = 0; i <= totalLength; i += increment) {
|
||||
const point = node.getPointAtLength(i);
|
||||
addControlPoint([point.x, point.y]);
|
||||
}
|
||||
routeLength.innerHTML = rn(totalLength * distanceScaleInput.value) + " " + distanceUnitInput.value;
|
||||
function updateRouteData(route) {
|
||||
route.name = route.name || Routes.generateName(route);
|
||||
byId("routeName").value = route.name;
|
||||
|
||||
const routeGroup = byId("routeGroup");
|
||||
routeGroup.options.length = 0;
|
||||
routes.selectAll("g").each(function () {
|
||||
routeGroup.options.add(new Option(this.id, this.id, false, this.id === route.group));
|
||||
});
|
||||
|
||||
updateRouteLength(route);
|
||||
|
||||
const isWater = route.points.some(([x, y, cellId]) => pack.cells.h[cellId] < 20);
|
||||
byId("routeElevationProfile").style.display = isWater ? "none" : "inline-block";
|
||||
}
|
||||
|
||||
function addControlPoint(point, before = null) {
|
||||
debug
|
||||
.select("#controlPoints")
|
||||
.insert("circle", before)
|
||||
.attr("cx", point[0])
|
||||
.attr("cy", point[1])
|
||||
.attr("r", 0.6)
|
||||
.call(d3.drag().on("drag", dragControlPoint))
|
||||
.on("click", clickControlPoint);
|
||||
function updateRouteLength(route) {
|
||||
route.length = Routes.getLength(route.i);
|
||||
byId("routeLength").value = rn(route.length * distanceScale) + " " + distanceUnitInput.value;
|
||||
}
|
||||
|
||||
function addInterimControlPoint() {
|
||||
const point = d3.mouse(this);
|
||||
const controls = document.getElementById("controlPoints").querySelectorAll("circle");
|
||||
const points = Array.from(controls).map(circle => [+circle.getAttribute("cx"), +circle.getAttribute("cy")]);
|
||||
const index = getSegmentId(points, point, 2);
|
||||
addControlPoint(point, ":nth-child(" + (index + 1) + ")");
|
||||
|
||||
redrawRoute();
|
||||
}
|
||||
|
||||
function dragControlPoint() {
|
||||
this.setAttribute("cx", d3.event.x);
|
||||
this.setAttribute("cy", d3.event.y);
|
||||
redrawRoute();
|
||||
}
|
||||
|
||||
function redrawRoute() {
|
||||
lineGen.curve(d3.curveCatmullRom.alpha(0.1));
|
||||
const points = [];
|
||||
function drawControlPoints(points) {
|
||||
debug
|
||||
.select("#controlPoints")
|
||||
.selectAll("circle")
|
||||
.each(function () {
|
||||
points.push([this.getAttribute("cx"), this.getAttribute("cy")]);
|
||||
});
|
||||
|
||||
elSelected.attr("d", round(lineGen(points)));
|
||||
const l = elSelected.node().getTotalLength();
|
||||
routeLength.innerHTML = rn(l * distanceScaleInput.value) + " " + distanceUnitInput.value;
|
||||
|
||||
if (modules.elevation) showEPForRoute(elSelected.node());
|
||||
.data(points)
|
||||
.join("circle")
|
||||
.attr("cx", d => d[0])
|
||||
.attr("cy", d => d[1])
|
||||
.attr("r", 0.6)
|
||||
.call(d3.drag().on("start", dragControlPoint))
|
||||
.on("click", handleControlPointClick);
|
||||
}
|
||||
|
||||
function showElevationProfile() {
|
||||
modules.elevation = true;
|
||||
showEPForRoute(elSelected.node());
|
||||
function drawCells(points) {
|
||||
debug
|
||||
.select("#controlCells")
|
||||
.selectAll("polygon")
|
||||
.data(points)
|
||||
.join("polygon")
|
||||
.attr("points", p => getPackPolygon(p[2]));
|
||||
}
|
||||
|
||||
function showGroupSection() {
|
||||
document.querySelectorAll("#routeEditor > button").forEach(el => (el.style.display = "none"));
|
||||
document.getElementById("routeGroupsSelection").style.display = "inline-block";
|
||||
}
|
||||
function dragControlPoint() {
|
||||
const route = getRoute();
|
||||
const initCell = d3.event.subject[2];
|
||||
const pointIndex = route.points.indexOf(d3.event.subject);
|
||||
|
||||
function hideGroupSection() {
|
||||
document.querySelectorAll("#routeEditor > button").forEach(el => (el.style.display = "inline-block"));
|
||||
document.getElementById("routeGroupsSelection").style.display = "none";
|
||||
document.getElementById("routeGroupName").style.display = "none";
|
||||
document.getElementById("routeGroupName").value = "";
|
||||
document.getElementById("routeGroup").style.display = "inline-block";
|
||||
}
|
||||
d3.event.on("drag", function () {
|
||||
this.setAttribute("cx", d3.event.x);
|
||||
this.setAttribute("cy", d3.event.y);
|
||||
|
||||
function selectRouteGroup(node) {
|
||||
const group = node.parentNode.id;
|
||||
const select = document.getElementById("routeGroup");
|
||||
select.options.length = 0; // remove all options
|
||||
const x = rn(d3.event.x, 2);
|
||||
const y = rn(d3.event.y, 2);
|
||||
const cellId = findCell(x, y);
|
||||
|
||||
routes.selectAll("g").each(function () {
|
||||
select.options.add(new Option(this.id, this.id, false, this.id === group));
|
||||
this.__data__ = route.points[pointIndex] = [x, y, cellId];
|
||||
redrawRoute(route);
|
||||
drawCells(route.points);
|
||||
});
|
||||
}
|
||||
|
||||
function changeRouteGroup() {
|
||||
document.getElementById(this.value).appendChild(elSelected.node());
|
||||
}
|
||||
d3.event.on("end", () => {
|
||||
const movedToCell = findCell(d3.event.x, d3.event.y);
|
||||
|
||||
function toggleNewGroupInput() {
|
||||
if (routeGroupName.style.display === "none") {
|
||||
routeGroupName.style.display = "inline-block";
|
||||
routeGroupName.focus();
|
||||
routeGroup.style.display = "none";
|
||||
} else {
|
||||
routeGroupName.style.display = "none";
|
||||
routeGroup.style.display = "inline-block";
|
||||
}
|
||||
}
|
||||
if (movedToCell !== initCell) {
|
||||
const prev = route.points[pointIndex - 1];
|
||||
if (prev) {
|
||||
removeConnection(initCell, prev[2]);
|
||||
addConnection(movedToCell, prev[2], route.i);
|
||||
}
|
||||
|
||||
function createNewGroup() {
|
||||
if (!this.value) {
|
||||
tip("Please provide a valid group name");
|
||||
return;
|
||||
}
|
||||
const group = this.value
|
||||
.toLowerCase()
|
||||
.replace(/ /g, "_")
|
||||
.replace(/[^\w\s]/gi, "");
|
||||
|
||||
if (document.getElementById(group)) {
|
||||
tip("Element with this id already exists. Please provide a unique name", false, "error");
|
||||
return;
|
||||
}
|
||||
|
||||
if (Number.isFinite(+group.charAt(0))) {
|
||||
tip("Group name should start with a letter", false, "error");
|
||||
return;
|
||||
}
|
||||
// just rename if only 1 element left
|
||||
const oldGroup = elSelected.node().parentNode;
|
||||
const basic = ["roads", "trails", "searoutes"].includes(oldGroup.id);
|
||||
if (!basic && oldGroup.childElementCount === 1) {
|
||||
document.getElementById("routeGroup").selectedOptions[0].remove();
|
||||
document.getElementById("routeGroup").options.add(new Option(group, group, false, true));
|
||||
oldGroup.id = group;
|
||||
toggleNewGroupInput();
|
||||
document.getElementById("routeGroupName").value = "";
|
||||
return;
|
||||
}
|
||||
|
||||
const newGroup = elSelected.node().parentNode.cloneNode(false);
|
||||
document.getElementById("routes").appendChild(newGroup);
|
||||
newGroup.id = group;
|
||||
document.getElementById("routeGroup").options.add(new Option(group, group, false, true));
|
||||
document.getElementById(group).appendChild(elSelected.node());
|
||||
|
||||
toggleNewGroupInput();
|
||||
document.getElementById("routeGroupName").value = "";
|
||||
}
|
||||
|
||||
function removeRouteGroup() {
|
||||
const group = elSelected.node().parentNode.id;
|
||||
const basic = ["roads", "trails", "searoutes"].includes(group);
|
||||
const count = elSelected.node().parentNode.childElementCount;
|
||||
alertMessage.innerHTML = /* html */ `Are you sure you want to remove ${
|
||||
basic ? "all elements in the group" : "the entire route group"
|
||||
}? <br /><br />Routes to be
|
||||
removed: ${count}`;
|
||||
$("#alert").dialog({
|
||||
resizable: false,
|
||||
title: "Remove route group",
|
||||
buttons: {
|
||||
Remove: function () {
|
||||
$(this).dialog("close");
|
||||
$("#routeEditor").dialog("close");
|
||||
hideGroupSection();
|
||||
if (basic)
|
||||
routes
|
||||
.select("#" + group)
|
||||
.selectAll("path")
|
||||
.remove();
|
||||
else routes.select("#" + group).remove();
|
||||
},
|
||||
Cancel: function () {
|
||||
$(this).dialog("close");
|
||||
const next = route.points[pointIndex + 1];
|
||||
if (next) {
|
||||
removeConnection(initCell, next[2]);
|
||||
addConnection(movedToCell, next[2], route.i);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function editGroupStyle() {
|
||||
const g = elSelected.node().parentNode.id;
|
||||
editStyle("routes", g);
|
||||
function redrawRoute(route) {
|
||||
elSelected.attr("d", Routes.getPath(route));
|
||||
updateRouteLength(route);
|
||||
if (byId("elevationProfile").offsetParent) showRouteElevationProfile();
|
||||
}
|
||||
|
||||
function toggleRouteSplitMode() {
|
||||
document.getElementById("routeNew").classList.remove("pressed");
|
||||
function addControlPoint() {
|
||||
const route = getRoute();
|
||||
const [x, y] = d3.mouse(this);
|
||||
const cellId = findCell(x, y);
|
||||
|
||||
const point = [rn(x, 2), rn(y, 2), cellId];
|
||||
const isNewCell = !route.points.some(p => p[2] === cellId);
|
||||
|
||||
const index = getSegmentId(route.points, point, 2);
|
||||
route.points.splice(index, 0, point);
|
||||
|
||||
// check if added point is in new cell
|
||||
if (isNewCell) {
|
||||
const prev = route.points[index - 1];
|
||||
const next = route.points[index + 1];
|
||||
|
||||
if (!prev) ERROR && console.error("Can't add control point to the start of the route");
|
||||
if (!next) ERROR && console.error("Can't add control point to the end of the route");
|
||||
if (!prev || !next) return;
|
||||
|
||||
removeConnection(prev[2], next[2]);
|
||||
addConnection(prev[2], cellId, route.i);
|
||||
addConnection(cellId, next[2], route.i);
|
||||
|
||||
drawCells(route.points);
|
||||
}
|
||||
|
||||
drawControlPoints(route.points);
|
||||
redrawRoute(route);
|
||||
}
|
||||
|
||||
function handleControlPointClick() {
|
||||
const controlPoint = d3.select(this);
|
||||
|
||||
const point = controlPoint.datum();
|
||||
const route = getRoute();
|
||||
const index = route.points.indexOf(point);
|
||||
|
||||
const isSplitMode = byId("routeSplit").classList.contains("pressed");
|
||||
return isSplitMode ? splitRoute() : removeControlPoint(controlPoint);
|
||||
|
||||
function splitRoute() {
|
||||
const oldRoutePoints = route.points.slice(0, index + 1);
|
||||
const newRoutePoints = route.points.slice(index);
|
||||
|
||||
// update old route
|
||||
route.points = oldRoutePoints;
|
||||
drawControlPoints(route.points);
|
||||
drawCells(route.points);
|
||||
redrawRoute(route);
|
||||
|
||||
// create new route
|
||||
const newRoute = {
|
||||
i: Routes.getNextId(),
|
||||
group: route.group,
|
||||
feature: route.feature,
|
||||
name: route.name,
|
||||
points: newRoutePoints
|
||||
};
|
||||
pack.routes.push(newRoute);
|
||||
|
||||
for (let i = 0; i < newRoute.points.length; i++) {
|
||||
const cellId = newRoute.points[i][2];
|
||||
const nextPoint = newRoute.points[i + 1];
|
||||
if (nextPoint) addConnection(cellId, nextPoint[2], newRoute.i);
|
||||
}
|
||||
|
||||
routes
|
||||
.select("#" + newRoute.group)
|
||||
.append("path")
|
||||
.attr("d", Routes.getPath(newRoute))
|
||||
.attr("id", "route" + newRoute.i);
|
||||
|
||||
byId("routeSplit").classList.remove("pressed");
|
||||
}
|
||||
|
||||
function removeControlPoint(controlPoint) {
|
||||
const isOnlyPointInCell = route.points.filter(p => p[2] === point[2]).length === 1;
|
||||
if (isOnlyPointInCell) {
|
||||
const prev = route.points[index - 1];
|
||||
const next = route.points[index + 1];
|
||||
if (prev) removeConnection(prev[2], point[2]);
|
||||
if (next) removeConnection(point[2], next[2]);
|
||||
if (prev && next) addConnection(prev[2], next[2], route.i);
|
||||
}
|
||||
|
||||
controlPoint.remove();
|
||||
route.points = route.points.filter(p => p !== point);
|
||||
|
||||
drawCells(route.points);
|
||||
redrawRoute(route);
|
||||
}
|
||||
}
|
||||
|
||||
function openJoinRoutesDialog() {
|
||||
const route = getRoute();
|
||||
const firstCell = route.points.at(0)[2];
|
||||
const lastCell = route.points.at(-1)[2];
|
||||
|
||||
const candidateRoutes = pack.routes.filter(r => {
|
||||
if (r.i === route.i) return false;
|
||||
if (r.group !== route.group) return false;
|
||||
if (r.points.at(0)[2] === lastCell) return true;
|
||||
if (r.points.at(-1)[2] === firstCell) return true;
|
||||
if (r.points.at(0)[2] === firstCell) return true;
|
||||
if (r.points.at(-1)[2] === lastCell) return true;
|
||||
return false;
|
||||
});
|
||||
|
||||
if (candidateRoutes.length) {
|
||||
const options = candidateRoutes.map(r => {
|
||||
r.name = r.name || Routes.generateName(r);
|
||||
r.length = r.length || Routes.getLength(r.i);
|
||||
const length = rn(r.length * distanceScale) + " " + distanceUnitInput.value;
|
||||
return `<option value="${r.i}">${r.name} (${length})</option>`;
|
||||
});
|
||||
alertMessage.innerHTML = /* html */ `<div>Route to join with:
|
||||
<select>${options.join("")}</select>
|
||||
</div>`;
|
||||
|
||||
$("#alert").dialog({
|
||||
title: "Join routes",
|
||||
width: fitContent(),
|
||||
position: {my: "left top", at: "left+10 top+150", of: "#map"},
|
||||
buttons: {
|
||||
Cancel: () => {
|
||||
$("#alert").dialog("close");
|
||||
},
|
||||
Join: () => {
|
||||
const selectedRouteId = +alertMessage.querySelector("select").value;
|
||||
const selectedRoute = pack.routes.find(r => r.i === selectedRouteId);
|
||||
joinRoutes(route, selectedRoute);
|
||||
tip("Routes joined", false, "success", 5000);
|
||||
$("#alert").dialog("close");
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
tip("No routes to join with. Route must start or end at current route's start or end cell", false, "error", 4000);
|
||||
}
|
||||
}
|
||||
|
||||
function joinRoutes(route, joinedRoute) {
|
||||
if (route.points.at(-1)[2] === joinedRoute.points.at(0)[2]) {
|
||||
// joinedRoute starts at the end of current route
|
||||
route.points = [...route.points, ...joinedRoute.points.slice(1)];
|
||||
} else if (route.points.at(0)[2] === joinedRoute.points.at(-1)[2]) {
|
||||
// joinedRoute ends at the start of current route
|
||||
route.points = [...joinedRoute.points, ...route.points.slice(1)];
|
||||
} else if (route.points.at(0)[2] === joinedRoute.points.at(0)[2]) {
|
||||
// joinedRoute and current route both start at the same cell
|
||||
route.points = [...route.points.reverse(), ...joinedRoute.points.slice(1)];
|
||||
} else if (route.points.at(-1)[2] === joinedRoute.points.at(-1)[2]) {
|
||||
// joinedRoute and current route both end at the same cell
|
||||
route.points = [...route.points, ...joinedRoute.points.reverse().slice(1)];
|
||||
}
|
||||
|
||||
for (let i = 0; i < route.points.length; i++) {
|
||||
const point = route.points[i];
|
||||
const nextPoint = route.points[i + 1];
|
||||
if (nextPoint) addConnection(point[2], nextPoint[2], route.i);
|
||||
}
|
||||
|
||||
Routes.remove(joinedRoute);
|
||||
drawControlPoints(route.points);
|
||||
redrawRoute(route);
|
||||
drawCells(route.points);
|
||||
}
|
||||
|
||||
function showCreationDialog() {
|
||||
const route = getRoute();
|
||||
createRoute(route.group);
|
||||
}
|
||||
|
||||
function togglePressed() {
|
||||
this.classList.toggle("pressed");
|
||||
}
|
||||
|
||||
function clickControlPoint() {
|
||||
if (routeSplit.classList.contains("pressed")) splitRoute(this);
|
||||
else {
|
||||
this.remove();
|
||||
redrawRoute();
|
||||
}
|
||||
function removeConnection(from, to) {
|
||||
const routes = pack.cells.routes;
|
||||
if (routes[from]) delete routes[from][to];
|
||||
if (routes[to]) delete routes[to][from];
|
||||
}
|
||||
|
||||
function splitRoute(clicked) {
|
||||
lineGen.curve(d3.curveCatmullRom.alpha(0.1));
|
||||
const group = d3.select(elSelected.node().parentNode);
|
||||
routeSplit.classList.remove("pressed");
|
||||
function addConnection(from, to, routeId) {
|
||||
const routes = pack.cells.routes;
|
||||
|
||||
const points1 = [],
|
||||
points2 = [];
|
||||
let points = points1;
|
||||
debug
|
||||
.select("#controlPoints")
|
||||
.selectAll("circle")
|
||||
.each(function () {
|
||||
points.push([this.getAttribute("cx"), this.getAttribute("cy")]);
|
||||
if (this === clicked) {
|
||||
points = points2;
|
||||
points.push([this.getAttribute("cx"), this.getAttribute("cy")]);
|
||||
}
|
||||
this.remove();
|
||||
});
|
||||
if (!routes[from]) routes[from] = {};
|
||||
routes[from][to] = routeId;
|
||||
|
||||
elSelected.attr("d", round(lineGen(points1)));
|
||||
const id = getNextId("route");
|
||||
group.append("path").attr("id", id).attr("d", lineGen(points2));
|
||||
debug.select("#controlPoints").selectAll("circle").remove();
|
||||
drawControlPoints(elSelected.node());
|
||||
if (!routes[to]) routes[to] = {};
|
||||
routes[to][from] = routeId;
|
||||
}
|
||||
|
||||
function toggleRouteCreationMode() {
|
||||
document.getElementById("routeSplit").classList.remove("pressed");
|
||||
document.getElementById("routeNew").classList.toggle("pressed");
|
||||
if (document.getElementById("routeNew").classList.contains("pressed")) {
|
||||
tip("Click on map to add control points", true);
|
||||
viewbox.on("click", addPointOnClick).style("cursor", "crosshair");
|
||||
elSelected.on("click", null);
|
||||
} else {
|
||||
clearMainTip();
|
||||
viewbox.on("click", clicked).style("cursor", "default");
|
||||
elSelected.on("click", addInterimControlPoint).attr("data-new", null);
|
||||
}
|
||||
function changeName() {
|
||||
getRoute().name = this.value;
|
||||
}
|
||||
|
||||
function addPointOnClick() {
|
||||
// create new route
|
||||
if (!elSelected.attr("data-new")) {
|
||||
debug.select("#controlPoints").selectAll("circle").remove();
|
||||
const parent = elSelected.node().parentNode;
|
||||
const id = getNextId("route");
|
||||
elSelected = d3.select(parent).append("path").attr("id", id).attr("data-new", 1);
|
||||
}
|
||||
function changeGroup() {
|
||||
const group = this.value;
|
||||
byId(group).appendChild(elSelected.node());
|
||||
getRoute().group = group;
|
||||
}
|
||||
|
||||
addControlPoint(d3.mouse(this));
|
||||
redrawRoute();
|
||||
function generateName() {
|
||||
const route = getRoute();
|
||||
route.name = routeName.value = Routes.generateName(route);
|
||||
}
|
||||
|
||||
function showRouteElevationProfile() {
|
||||
const route = getRoute();
|
||||
const length = rn(route.length * distanceScale);
|
||||
showElevationProfile(
|
||||
route.points.map(p => p[2]),
|
||||
length,
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
function editRouteLegend() {
|
||||
const id = elSelected.attr("id");
|
||||
editNotes(id, id);
|
||||
const route = getRoute();
|
||||
editNotes(id, route.name);
|
||||
}
|
||||
|
||||
function editRouteGroupStyle() {
|
||||
const {group} = getRoute();
|
||||
editStyle("routes", group);
|
||||
}
|
||||
|
||||
function toggleLockButton() {
|
||||
const route = getRoute();
|
||||
route.lock = !route.lock;
|
||||
updateLockIcon();
|
||||
}
|
||||
|
||||
function updateLockIcon() {
|
||||
const route = getRoute();
|
||||
if (route.lock) {
|
||||
byId("routeLock").classList.remove("icon-lock-open");
|
||||
byId("routeLock").classList.add("icon-lock");
|
||||
} else {
|
||||
byId("routeLock").classList.remove("icon-lock");
|
||||
byId("routeLock").classList.add("icon-lock-open");
|
||||
}
|
||||
}
|
||||
|
||||
function removeRoute() {
|
||||
alertMessage.innerHTML = "Are you sure you want to remove the route?";
|
||||
alertMessage.innerHTML = "Are you sure you want to remove the route";
|
||||
$("#alert").dialog({
|
||||
resizable: false,
|
||||
width: "22em",
|
||||
title: "Remove route",
|
||||
buttons: {
|
||||
Remove: function () {
|
||||
Routes.remove(getRoute());
|
||||
$(this).dialog("close");
|
||||
elSelected.remove();
|
||||
$("#routeEditor").dialog("close");
|
||||
},
|
||||
Cancel: function () {
|
||||
|
|
@ -312,12 +407,16 @@ function editRoute(onClick) {
|
|||
});
|
||||
}
|
||||
|
||||
function closeRoutesEditor() {
|
||||
elSelected.attr("data-new", null).on("click", null);
|
||||
clearMainTip();
|
||||
routeSplit.classList.remove("pressed");
|
||||
routeNew.classList.remove("pressed");
|
||||
function closeRouteEditor() {
|
||||
debug.select("#controlPoints").remove();
|
||||
debug.select("#controlCells").remove();
|
||||
|
||||
elSelected.on("click", null);
|
||||
unselect();
|
||||
clearMainTip();
|
||||
|
||||
const forced = +byId("toggleCells").dataset.forced;
|
||||
byId("toggleCells").dataset.forced = 0;
|
||||
if (forced && layerIsOn("toggleCells")) toggleCells();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
187
modules/ui/routes-overview.js
Normal file
187
modules/ui/routes-overview.js
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
"use strict";
|
||||
|
||||
function overviewRoutes() {
|
||||
if (customization) return;
|
||||
closeDialogs("#routesOverview, .stable");
|
||||
if (!layerIsOn("toggleRoutes")) toggleRoutes();
|
||||
|
||||
const body = byId("routesBody");
|
||||
routesOverviewAddLines();
|
||||
$("#routesOverview").dialog();
|
||||
|
||||
if (modules.overviewRoutes) return;
|
||||
modules.overviewRoutes = true;
|
||||
|
||||
$("#routesOverview").dialog({
|
||||
title: "Routes Overview",
|
||||
resizable: false,
|
||||
width: fitContent(),
|
||||
position: {my: "right top", at: "right-10 top+10", of: "svg", collision: "fit"}
|
||||
});
|
||||
|
||||
// add listeners
|
||||
byId("routesOverviewRefresh").on("click", routesOverviewAddLines);
|
||||
byId("routesCreateNew").on("click", createRoute);
|
||||
byId("routesExport").on("click", downloadRoutesData);
|
||||
byId("routesLockAll").on("click", toggleLockAll);
|
||||
byId("routesRemoveAll").on("click", triggerAllRoutesRemove);
|
||||
|
||||
// add line for each route
|
||||
function routesOverviewAddLines() {
|
||||
body.innerHTML = "";
|
||||
let lines = "";
|
||||
|
||||
for (const route of pack.routes) {
|
||||
route.name = route.name || Routes.generateName(route);
|
||||
route.length = route.length || Routes.getLength(route.i);
|
||||
const length = rn(route.length * distanceScale) + " " + distanceUnitInput.value;
|
||||
|
||||
lines += /* html */ `<div
|
||||
class="states"
|
||||
data-id="${route.i}"
|
||||
data-name="${route.name}"
|
||||
data-group="${route.group}"
|
||||
data-length="${route.length}"
|
||||
>
|
||||
<span data-tip="Click to focus on route" class="icon-dot-circled pointer"></span>
|
||||
<div data-tip="Route name" style="width: 15em; margin-left: 0.4em;">${route.name}</div>
|
||||
<div data-tip="Route group" style="width: 8em;">${route.group}</div>
|
||||
<div data-tip="Route length" style="width: 6em;">${length}</div>
|
||||
<span data-tip="Edit route" class="icon-pencil"></span>
|
||||
<span class="locks pointer ${
|
||||
route.lock ? "icon-lock" : "icon-lock-open inactive"
|
||||
}" onmouseover="showElementLockTip(event)"></span>
|
||||
<span data-tip="Remove route" class="icon-trash-empty"></span>
|
||||
</div>`;
|
||||
}
|
||||
body.insertAdjacentHTML("beforeend", lines);
|
||||
|
||||
// update footer
|
||||
routesFooterNumber.innerHTML = pack.routes.length;
|
||||
const averageLength = rn(d3.mean(pack.routes.map(r => r.length)) || 0);
|
||||
routesFooterLength.innerHTML = averageLength * distanceScale + " " + distanceUnitInput.value;
|
||||
|
||||
// add listeners
|
||||
body.querySelectorAll("div.states").forEach(el => el.on("mouseenter", routeHighlightOn));
|
||||
body.querySelectorAll("div.states").forEach(el => el.on("mouseleave", routeHighlightOff));
|
||||
body.querySelectorAll("div > span.icon-dot-circled").forEach(el => el.on("click", zoomToRoute));
|
||||
body.querySelectorAll("div > span.icon-pencil").forEach(el => el.on("click", openRouteEditor));
|
||||
body.querySelectorAll("div > span.locks").forEach(el => el.addEventListener("click", toggleLockStatus));
|
||||
body.querySelectorAll("div > span.icon-trash-empty").forEach(el => el.on("click", triggerRouteRemove));
|
||||
|
||||
applySorting(routesHeader);
|
||||
}
|
||||
|
||||
function routeHighlightOn(event) {
|
||||
if (!layerIsOn("toggleRoutes")) toggleRoutes();
|
||||
const routeId = +event.target.dataset.id;
|
||||
routes
|
||||
.select("#route" + routeId)
|
||||
.attr("stroke", "red")
|
||||
.attr("stroke-width", 2)
|
||||
.attr("stroke-dasharray", "none");
|
||||
}
|
||||
|
||||
function routeHighlightOff(e) {
|
||||
const routeId = +e.target.dataset.id;
|
||||
routes
|
||||
.select("#route" + routeId)
|
||||
.attr("stroke", null)
|
||||
.attr("stroke-width", null)
|
||||
.attr("stroke-dasharray", null);
|
||||
}
|
||||
|
||||
function zoomToRoute() {
|
||||
const r = +this.parentNode.dataset.id;
|
||||
const route = routes.select("#route" + r).node();
|
||||
highlightElement(route, 3);
|
||||
}
|
||||
|
||||
function downloadRoutesData() {
|
||||
let data = "Id,Route,Group,Length\n"; // headers
|
||||
|
||||
body.querySelectorAll(":scope > div").forEach(function (el) {
|
||||
const d = el.dataset;
|
||||
const length = rn(d.length * distanceScale) + " " + distanceUnitInput.value;
|
||||
data += [d.id, d.name, d.group, length].join(",") + "\n";
|
||||
});
|
||||
|
||||
const name = getFileName("Routes") + ".csv";
|
||||
downloadFile(data, name);
|
||||
}
|
||||
|
||||
function openRouteEditor() {
|
||||
const id = "route" + this.parentNode.dataset.id;
|
||||
editRoute(id);
|
||||
}
|
||||
|
||||
function toggleLockStatus() {
|
||||
const routeId = +this.parentNode.dataset.id;
|
||||
const route = pack.routes[routeId];
|
||||
route.lock = !route.lock;
|
||||
|
||||
if (this.classList.contains("icon-lock")) {
|
||||
this.classList.remove("icon-lock");
|
||||
this.classList.add("icon-lock-open");
|
||||
this.classList.add("inactive");
|
||||
} else {
|
||||
this.classList.remove("icon-lock-open");
|
||||
this.classList.add("icon-lock");
|
||||
this.classList.remove("inactive");
|
||||
}
|
||||
}
|
||||
|
||||
function toggleLockAll() {
|
||||
const allLocked = pack.routes.every(route => route.lock);
|
||||
|
||||
pack.routes.forEach(route => {
|
||||
route.lock = !allLocked;
|
||||
});
|
||||
|
||||
routesOverviewAddLines();
|
||||
byId("routesLockAll").className = allLocked ? "icon-lock" : "icon-lock-open";
|
||||
}
|
||||
|
||||
function triggerRouteRemove() {
|
||||
const routeId = +this.parentNode.dataset.id;
|
||||
|
||||
alertMessage.innerHTML = `Are you sure you want to remove the route?`;
|
||||
$("#alert").dialog({
|
||||
resizable: false,
|
||||
width: "22em",
|
||||
title: "Remove route",
|
||||
buttons: {
|
||||
Remove: function () {
|
||||
const route = pack.routes.find(r => r.i === routeId);
|
||||
Routes.remove(route);
|
||||
routesOverviewAddLines();
|
||||
$(this).dialog("close");
|
||||
},
|
||||
Cancel: function () {
|
||||
$(this).dialog("close");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function triggerAllRoutesRemove() {
|
||||
alertMessage.innerHTML = /* html */ `Are you sure you want to remove all routes? This action can't be undone`;
|
||||
$("#alert").dialog({
|
||||
resizable: false,
|
||||
title: "Remove all routes",
|
||||
buttons: {
|
||||
Remove: function () {
|
||||
pack.cells.routes = {};
|
||||
pack.routes = [];
|
||||
routes.selectAll("path").remove();
|
||||
|
||||
routesOverviewAddLines();
|
||||
$(this).dialog("close");
|
||||
},
|
||||
Cancel: function () {
|
||||
$(this).dialog("close");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -14,6 +14,7 @@
|
|||
|
||||
byId("styleFilterInput").innerHTML = allOptions;
|
||||
byId("styleStatesBodyFilter").innerHTML = allOptions;
|
||||
byId("styleScaleBarBackgroundFilter").innerHTML = allOptions;
|
||||
}
|
||||
|
||||
// store some style inputs as options
|
||||
|
|
@ -31,6 +32,7 @@ function editStyle(element, group) {
|
|||
|
||||
styleElementSelect.classList.add("glow");
|
||||
if (group) styleGroupSelect.classList.add("glow");
|
||||
|
||||
setTimeout(() => {
|
||||
styleElementSelect.classList.remove("glow");
|
||||
if (group) styleGroupSelect.classList.remove("glow");
|
||||
|
|
@ -81,10 +83,10 @@ function selectStyleElement() {
|
|||
styleIsOff.style.display = isLayerOff ? "block" : "none";
|
||||
|
||||
// active group element
|
||||
const group = styleGroupSelect.value;
|
||||
if (["routes", "labels", "coastline", "lakes", "anchors", "burgIcons", "borders"].includes(styleElement)) {
|
||||
const gEl = group && el.select("#" + group);
|
||||
el = group && gEl.size() ? gEl : el.select("g");
|
||||
if (["routes", "labels", "coastline", "lakes", "anchors", "burgIcons", "borders", "terrs"].includes(styleElement)) {
|
||||
const group = styleGroupSelect.value;
|
||||
const defaultGroupSelector = styleElement === "terrs" ? "#landHeights" : "g";
|
||||
el = group && el.select("#" + group).size() ? el.select("#" + group) : el.select(defaultGroupSelector);
|
||||
}
|
||||
|
||||
// opacity
|
||||
|
|
@ -94,13 +96,13 @@ function selectStyleElement() {
|
|||
}
|
||||
|
||||
// filter
|
||||
if (!["landmass", "legend", "regions"].includes(styleElement)) {
|
||||
if (!["landmass", "legend", "regions", "scaleBar"].includes(styleElement)) {
|
||||
styleFilter.style.display = "block";
|
||||
styleFilterInput.value = el.attr("filter") || "";
|
||||
}
|
||||
|
||||
// fill
|
||||
if (["rivers", "lakes", "landmass", "prec", "ice", "fogging", "vignette"].includes(styleElement)) {
|
||||
if (["rivers", "lakes", "landmass", "prec", "ice", "fogging", "scaleBar", "vignette"].includes(styleElement)) {
|
||||
styleFill.style.display = "block";
|
||||
styleFillInput.value = styleFillOutput.value = el.attr("fill");
|
||||
}
|
||||
|
|
@ -170,11 +172,14 @@ function selectStyleElement() {
|
|||
|
||||
if (styleElement === "terrs") {
|
||||
styleHeightmap.style.display = "block";
|
||||
styleHeightmapScheme.value = terrs.attr("scheme");
|
||||
styleHeightmapTerracingInput.value = styleHeightmapTerracingOutput.value = terrs.attr("terracing");
|
||||
styleHeightmapSkipInput.value = styleHeightmapSkipOutput.value = terrs.attr("skip");
|
||||
styleHeightmapSimplificationInput.value = styleHeightmapSimplificationOutput.value = terrs.attr("relax");
|
||||
styleHeightmapCurve.value = terrs.attr("curve");
|
||||
styleHeightmapRenderOceanOption.style.display = el.attr("id") === "oceanHeights" ? "block" : "none";
|
||||
styleHeightmapRenderOcean.checked = +el.attr("data-render");
|
||||
|
||||
styleHeightmapScheme.value = el.attr("scheme");
|
||||
styleHeightmapTerracingInput.value = styleHeightmapTerracingOutput.value = el.attr("terracing");
|
||||
styleHeightmapSkipInput.value = styleHeightmapSkipOutput.value = el.attr("skip");
|
||||
styleHeightmapSimplificationInput.value = styleHeightmapSimplificationOutput.value = el.attr("relax");
|
||||
styleHeightmapCurve.value = el.attr("curve");
|
||||
}
|
||||
|
||||
if (styleElement === "markers") {
|
||||
|
|
@ -336,7 +341,7 @@ function selectStyleElement() {
|
|||
|
||||
// update group options
|
||||
styleGroupSelect.options.length = 0; // remove all options
|
||||
if (["routes", "labels", "coastline", "lakes", "anchors", "burgIcons", "borders"].includes(styleElement)) {
|
||||
if (["routes", "labels", "coastline", "lakes", "anchors", "burgIcons", "borders", "terrs"].includes(styleElement)) {
|
||||
const groups = byId(styleElement).querySelectorAll("g");
|
||||
groups.forEach(el => {
|
||||
if (el.id === "burgLabels") return;
|
||||
|
|
@ -356,6 +361,31 @@ function selectStyleElement() {
|
|||
if (auto) styleFilter.style.display = "none";
|
||||
}
|
||||
|
||||
if (styleElement === "scaleBar") {
|
||||
styleScaleBar.style.display = "block";
|
||||
|
||||
styleScaleBarSize.value = el.attr("data-bar-size");
|
||||
styleScaleBarFontSize.value = el.attr("font-size");
|
||||
styleScaleBarPositionX.value = el.attr("data-x") || "99";
|
||||
styleScaleBarPositionY.value = el.attr("data-y") || "99";
|
||||
styleScaleBarLabel.value = el.attr("data-label") || "";
|
||||
|
||||
const scaleBarBack = el.select("#scaleBarBack");
|
||||
if (scaleBarBack.size()) {
|
||||
styleScaleBarBackgroundOpacityInput.value = styleScaleBarBackgroundOpacityOutput.value =
|
||||
scaleBarBack.attr("opacity");
|
||||
styleScaleBarBackgroundFillInput.value = styleScaleBarBackgroundFillOutput.value = scaleBarBack.attr("fill");
|
||||
styleScaleBarBackgroundStrokeInput.value = styleScaleBarBackgroundStrokeOutput.value =
|
||||
scaleBarBack.attr("stroke");
|
||||
styleScaleBarBackgroundStrokeWidth.value = scaleBarBack.attr("stroke-width");
|
||||
styleScaleBarBackgroundFilter.value = scaleBarBack.attr("filter");
|
||||
styleScaleBarBackgroundPaddingTop.value = scaleBarBack.attr("data-top");
|
||||
styleScaleBarBackgroundPaddingRight.value = scaleBarBack.attr("data-right");
|
||||
styleScaleBarBackgroundPaddingBottom.value = scaleBarBack.attr("data-bottom");
|
||||
styleScaleBarBackgroundPaddingLeft.value = scaleBarBack.attr("data-left");
|
||||
}
|
||||
}
|
||||
|
||||
if (styleElement === "vignette") {
|
||||
styleVignette.style.display = "block";
|
||||
|
||||
|
|
@ -473,7 +503,7 @@ styleGridScale.addEventListener("input", function () {
|
|||
|
||||
function calculateFriendlyGridSize() {
|
||||
const size = styleGridScale.value * 25;
|
||||
const friendly = `${rn(size * distanceScaleInput.value, 2)} ${distanceUnitInput.value}`;
|
||||
const friendly = `${rn(size * distanceScale, 2)} ${distanceUnitInput.value}`;
|
||||
styleGridSizeFriendly.value = friendly;
|
||||
}
|
||||
|
||||
|
|
@ -519,18 +549,16 @@ outlineLayers.addEventListener("change", function () {
|
|||
});
|
||||
|
||||
styleHeightmapScheme.addEventListener("change", function () {
|
||||
terrs.attr("scheme", this.value);
|
||||
getEl().attr("scheme", this.value);
|
||||
drawHeightmap();
|
||||
});
|
||||
|
||||
openCreateHeightmapSchemeButton.addEventListener("click", function () {
|
||||
// start with current scheme
|
||||
this.dataset.stops = terrs.attr("scheme").startsWith("#")
|
||||
? terrs.attr("scheme")
|
||||
: (function () {
|
||||
const scheme = heightmapColorSchemes[terrs.attr("scheme")];
|
||||
return [0, 0.25, 0.5, 0.75, 1].map(scheme).map(toHEX).join(",");
|
||||
})();
|
||||
const scheme = getEl().attr("scheme");
|
||||
this.dataset.stops = scheme.startsWith("#")
|
||||
? scheme
|
||||
: (() => [0, 0.25, 0.5, 0.75, 1].map(heightmapColorSchemes[scheme]).map(toHEX).join(","))();
|
||||
|
||||
// render dialog base structure
|
||||
alertMessage.innerHTML = /* html */ `<div>
|
||||
|
|
@ -622,7 +650,7 @@ openCreateHeightmapSchemeButton.addEventListener("click", function () {
|
|||
if (stops in heightmapColorSchemes) return tip("This scheme already exists", false, "error");
|
||||
|
||||
addCustomColorScheme(stops);
|
||||
terrs.attr("scheme", stops);
|
||||
getEl().attr("scheme", stops);
|
||||
drawHeightmap();
|
||||
|
||||
handleClose();
|
||||
|
|
@ -644,23 +672,28 @@ openCreateHeightmapSchemeButton.addEventListener("click", function () {
|
|||
});
|
||||
});
|
||||
|
||||
styleHeightmapRenderOcean.addEventListener("change", function () {
|
||||
getEl().attr("data-render", +this.checked);
|
||||
drawHeightmap();
|
||||
});
|
||||
|
||||
styleHeightmapTerracingInput.addEventListener("input", function () {
|
||||
terrs.attr("terracing", this.value);
|
||||
getEl().attr("terracing", this.value);
|
||||
drawHeightmap();
|
||||
});
|
||||
|
||||
styleHeightmapSkipInput.addEventListener("input", function () {
|
||||
terrs.attr("skip", this.value);
|
||||
getEl().attr("skip", this.value);
|
||||
drawHeightmap();
|
||||
});
|
||||
|
||||
styleHeightmapSimplificationInput.addEventListener("input", function () {
|
||||
terrs.attr("relax", this.value);
|
||||
getEl().attr("relax", this.value);
|
||||
drawHeightmap();
|
||||
});
|
||||
|
||||
styleHeightmapCurve.addEventListener("change", function () {
|
||||
terrs.attr("curve", this.value);
|
||||
getEl().attr("curve", this.value);
|
||||
drawHeightmap();
|
||||
});
|
||||
|
||||
|
|
@ -957,7 +990,7 @@ function textureProvideURL() {
|
|||
}
|
||||
|
||||
function fetchTextureURL(url) {
|
||||
INFO && console.log("Provided URL is", url);
|
||||
INFO && console.info("Provided URL is", url);
|
||||
const img = new Image();
|
||||
img.onload = function () {
|
||||
const canvas = byId("texturePreview");
|
||||
|
|
@ -1043,6 +1076,44 @@ styleVignetteBlur.addEventListener("input", function () {
|
|||
byId("vignette-rect")?.setAttribute("filter", `blur(${this.value}px)`);
|
||||
});
|
||||
|
||||
styleScaleBar.addEventListener("input", function (event) {
|
||||
const scaleBarBack = scaleBar.select("#scaleBarBack");
|
||||
if (!scaleBarBack.size()) return;
|
||||
|
||||
const {id, value} = event.target;
|
||||
|
||||
if (id === "styleScaleBarSize") scaleBar.attr("data-bar-size", value);
|
||||
else if (id === "styleScaleBarFontSize") scaleBar.attr("font-size", value);
|
||||
else if (id === "styleScaleBarPositionX") scaleBar.attr("data-x", value);
|
||||
else if (id === "styleScaleBarPositionY") scaleBar.attr("data-y", value);
|
||||
else if (id === "styleScaleBarLabel") scaleBar.attr("data-label", value);
|
||||
else if (id === "styleScaleBarBackgroundOpacityInput") scaleBarBack.attr("opacity", value);
|
||||
else if (id === "styleScaleBarBackgroundFillInput") scaleBarBack.attr("fill", value);
|
||||
else if (id === "styleScaleBarBackgroundStrokeInput") scaleBarBack.attr("stroke", value);
|
||||
else if (id === "styleScaleBarBackgroundStrokeWidth") scaleBarBack.attr("stroke-width", value);
|
||||
else if (id === "styleScaleBarBackgroundFilter") scaleBarBack.attr("filter", value);
|
||||
else if (id === "styleScaleBarBackgroundPaddingTop") scaleBarBack.attr("data-top", value);
|
||||
else if (id === "styleScaleBarBackgroundPaddingRight") scaleBarBack.attr("data-right", value);
|
||||
else if (id === "styleScaleBarBackgroundPaddingBottom") scaleBarBack.attr("data-bottom", value);
|
||||
else if (id === "styleScaleBarBackgroundPaddingLeft") scaleBarBack.attr("data-left", value);
|
||||
|
||||
if (
|
||||
[
|
||||
"styleScaleBarSize",
|
||||
"styleScaleBarPositionX",
|
||||
"styleScaleBarPositionY",
|
||||
"styleScaleBarLabel",
|
||||
"styleScaleBarBackgroundPaddingLeft",
|
||||
"styleScaleBarBackgroundPaddingTop",
|
||||
"styleScaleBarBackgroundPaddingRight",
|
||||
"styleScaleBarBackgroundPaddingBottom"
|
||||
].includes(id)
|
||||
) {
|
||||
drawScaleBar(scaleBar, scale);
|
||||
fitScaleBar(scaleBar, svgWidth, svgHeight);
|
||||
}
|
||||
});
|
||||
|
||||
function updateElements() {
|
||||
// burgIcons to desired size
|
||||
burgIcons.selectAll("g").each(function () {
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ const systemPresets = [
|
|||
"watercolor",
|
||||
"clean",
|
||||
"atlas",
|
||||
"darkSeas",
|
||||
"cyberpunk",
|
||||
"night",
|
||||
"monochrome"
|
||||
|
|
@ -63,7 +64,7 @@ async function getStylePreset(desiredPreset) {
|
|||
|
||||
async function fetchSystemPreset(preset) {
|
||||
try {
|
||||
const res = await fetch(`./styles/${preset}.json`);
|
||||
const res = await fetch(`./styles/${preset}.json?v=${version}`);
|
||||
return await res.json();
|
||||
} catch (err) {
|
||||
throw new Error("Cannot fetch style preset", preset);
|
||||
|
|
@ -140,6 +141,9 @@ function applyStyleWithUiRefresh(style) {
|
|||
|
||||
invokeActiveZooming();
|
||||
setPresetRemoveButtonVisibiliy();
|
||||
|
||||
drawScaleBar(scaleBar, scale);
|
||||
fitScaleBar(scaleBar, svgWidth, svgHeight);
|
||||
}
|
||||
|
||||
function addStylePreset() {
|
||||
|
|
@ -195,7 +199,7 @@ function addStylePreset() {
|
|||
"mask"
|
||||
],
|
||||
"#compass": ["opacity", "transform", "filter", "mask", "shape-rendering"],
|
||||
"#rose": ["transform"],
|
||||
"#compass > use": ["transform"],
|
||||
"#relig": ["opacity", "stroke", "stroke-width", "filter"],
|
||||
"#cults": ["opacity", "stroke", "stroke-width", "stroke-dasharray", "stroke-linecap", "filter"],
|
||||
"#landmass": ["opacity", "fill", "filter"],
|
||||
|
|
@ -239,7 +243,18 @@ function addStylePreset() {
|
|||
"#oceanLayers": ["filter", "layers"],
|
||||
"#oceanBase": ["fill"],
|
||||
"#oceanicPattern": ["href", "opacity"],
|
||||
"#terrs": ["opacity", "scheme", "terracing", "skip", "relax", "curve", "filter", "mask"],
|
||||
"#terrs #oceanHeights": [
|
||||
"data-render",
|
||||
"opacity",
|
||||
"scheme",
|
||||
"terracing",
|
||||
"skip",
|
||||
"relax",
|
||||
"curve",
|
||||
"filter",
|
||||
"mask"
|
||||
],
|
||||
"#terrs #landHeights": ["opacity", "scheme", "terracing", "skip", "relax", "curve", "filter", "mask"],
|
||||
"#legend": [
|
||||
"data-size",
|
||||
"font-size",
|
||||
|
|
@ -301,7 +316,19 @@ function addStylePreset() {
|
|||
],
|
||||
"#fogging": ["opacity", "fill", "filter"],
|
||||
"#vignette": ["opacity", "fill", "filter"],
|
||||
"#vignette-rect": ["x", "y", "width", "height", "rx", "ry", "filter"]
|
||||
"#vignette-rect": ["x", "y", "width", "height", "rx", "ry", "filter"],
|
||||
"#scaleBar": ["opacity", "fill", "font-size", "data-bar-size", "data-x", "data-y", "data-label"],
|
||||
"#scaleBarBack": [
|
||||
"opacity",
|
||||
"fill",
|
||||
"stroke",
|
||||
"stroke-width",
|
||||
"filter",
|
||||
"data-top",
|
||||
"data-right",
|
||||
"data-bottom",
|
||||
"data-left"
|
||||
]
|
||||
};
|
||||
|
||||
for (const selector in attributes) {
|
||||
|
|
|
|||
|
|
@ -258,11 +258,16 @@ window.UISubmap = (function () {
|
|||
byId("latitudeInput").value = latitudeOutput.value;
|
||||
|
||||
// fix scale
|
||||
distanceScaleInput.value = distanceScaleOutput.value = rn((distanceScale = distanceScaleOutput.value / scale), 2);
|
||||
distanceScale =
|
||||
distanceScaleInput.value =
|
||||
distanceScaleOutput.value =
|
||||
rn((distanceScale = distanceScaleOutput.value / scale), 2);
|
||||
|
||||
populationRateInput.value = populationRateOutput.value = rn(
|
||||
(populationRate = populationRateOutput.value / scale),
|
||||
2
|
||||
);
|
||||
|
||||
customization = 0;
|
||||
startResample(options);
|
||||
}, 1000);
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@ toolsContent.addEventListener("click", function (event) {
|
|||
else if (button === "editZonesButton") editZones();
|
||||
else if (button === "overviewChartsButton") overviewCharts();
|
||||
else if (button === "overviewBurgsButton") overviewBurgs();
|
||||
else if (button === "overviewRoutesButton") overviewRoutes();
|
||||
else if (button === "overviewRiversButton") overviewRivers();
|
||||
else if (button === "overviewMilitaryButton") overviewMilitary();
|
||||
else if (button === "overviewMarkersButton") overviewMarkers();
|
||||
|
|
@ -66,7 +67,7 @@ toolsContent.addEventListener("click", function (event) {
|
|||
if (button === "addLabel") toggleAddLabel();
|
||||
else if (button === "addBurgTool") toggleAddBurg();
|
||||
else if (button === "addRiver") toggleAddRiver();
|
||||
else if (button === "addRoute") toggleAddRoute();
|
||||
else if (button === "addRoute") createRoute();
|
||||
else if (button === "addMarker") toggleAddMarker();
|
||||
// click to create a new map buttons
|
||||
else if (button === "openSubmapMenu") UISubmap.openSubmapMenu();
|
||||
|
|
@ -79,7 +80,7 @@ function processFeatureRegeneration(event, button) {
|
|||
ReliefIcons();
|
||||
if (!layerIsOn("toggleRelief")) toggleRelief();
|
||||
} else if (button === "regenerateRoutes") {
|
||||
Routes.regenerate();
|
||||
regenerateRoutes();
|
||||
if (!layerIsOn("toggleRoutes")) toggleRoutes();
|
||||
} else if (button === "regenerateRivers") regenerateRivers();
|
||||
else if (button === "regeneratePopulation") recalculatePopulation();
|
||||
|
|
@ -115,6 +116,14 @@ async function openEmblemEditor() {
|
|||
editEmblem(type, id, el);
|
||||
}
|
||||
|
||||
function regenerateRoutes() {
|
||||
const locked = pack.routes.filter(route => route.lock).map((route, index) => ({...route, i: index}));
|
||||
Routes.generate(locked);
|
||||
|
||||
routes.selectAll("path").remove();
|
||||
if (layerIsOn("toggleRoutes")) drawRoutes();
|
||||
}
|
||||
|
||||
function regenerateRivers() {
|
||||
Rivers.generate();
|
||||
Lakes.defineGroup();
|
||||
|
|
@ -129,7 +138,7 @@ function recalculatePopulation() {
|
|||
if (!b.i || b.removed || b.lock) return;
|
||||
const i = b.cell;
|
||||
|
||||
b.population = rn(Math.max((pack.cells.s[i] + pack.cells.road[i] / 2) / 8 + b.i / 1000 + (i % 100) / 1000, 0.1), 3);
|
||||
b.population = rn(Math.max(pack.cells.s[i] / 8 + b.i / 1000 + (i % 100) / 1000, 0.1), 3);
|
||||
if (b.capital) b.population = b.population * 1.3; // increase capital population
|
||||
if (b.port) b.population = b.population * 1.3; // increase port population
|
||||
b.population = rn(b.population * gauss(2, 3, 0.6, 20, 3), 3);
|
||||
|
|
@ -247,13 +256,16 @@ function recreateStates() {
|
|||
capitalsTree.add([x, y]);
|
||||
|
||||
// update label id reference
|
||||
labels
|
||||
.select("#states")
|
||||
.select(`#stateLabel${state.i}`)
|
||||
.attr("id", `stateLabel${newId}`)
|
||||
.select("textPath")
|
||||
.attr("xlink:href", `#textPath_stateLabel${newId}`);
|
||||
defs.select("#textPaths").select(`#textPath_stateLabel${state.i}`).attr("id", `textPath_stateLabel${newId}`);
|
||||
byId(`textPath_stateLabel${state.i}`)?.setAttribute("id", `textPath_stateLabel${newId}`);
|
||||
const $label = byId(`stateLabel${state.i}`);
|
||||
if ($label) {
|
||||
$label.setAttribute("id", `stateLabel${newId}`);
|
||||
const $textPath = $label.querySelector("textPath");
|
||||
if ($textPath) {
|
||||
$textPath.removeAttribute("href");
|
||||
$textPath.setAttribute("href", `#textPath_stateLabel${newId}`);
|
||||
}
|
||||
}
|
||||
|
||||
// update emblem id reference
|
||||
byId(`stateCOA${state.i}`)?.setAttribute("id", `stateCOA${newId}`);
|
||||
|
|
@ -332,29 +344,44 @@ function regenerateProvinces() {
|
|||
}
|
||||
|
||||
function regenerateBurgs() {
|
||||
const {cells, states} = pack;
|
||||
const lockedburgs = pack.burgs.filter(b => b.i && !b.removed && b.lock);
|
||||
const {cells, features, burgs, states, provinces} = pack;
|
||||
|
||||
rankCells();
|
||||
|
||||
cells.burg = new Uint16Array(cells.i.length);
|
||||
const burgs = (pack.burgs = [0]); // clear burgs array
|
||||
states.filter(s => s.i).forEach(s => (s.capital = 0)); // clear state capitals
|
||||
pack.provinces.filter(p => p.i).forEach(p => (p.burg = 0)); // clear province capitals
|
||||
// remove notes for unlocked burgs
|
||||
notes = notes.filter(note => {
|
||||
if (note.id.startsWith("burg")) {
|
||||
const burgId = +note.id.slice(4);
|
||||
return burgs[burgId]?.lock;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
const newBurgs = [0]; // new burgs array
|
||||
const burgsTree = d3.quadtree();
|
||||
|
||||
// add locked burgs
|
||||
cells.burg = new Uint16Array(cells.i.length); // clear cells burg data
|
||||
states.filter(s => s.i).forEach(s => (s.capital = 0)); // clear state capitals
|
||||
provinces.filter(p => p.i).forEach(p => (p.burg = 0)); // clear province capitals
|
||||
|
||||
// readd locked burgs
|
||||
const lockedburgs = burgs.filter(burg => burg.i && !burg.removed && burg.lock);
|
||||
for (let j = 0; j < lockedburgs.length; j++) {
|
||||
const id = burgs.length;
|
||||
const lockedBurg = lockedburgs[j];
|
||||
lockedBurg.i = id;
|
||||
burgs.push(lockedBurg);
|
||||
const newId = newBurgs.length;
|
||||
|
||||
const noteIndex = notes.findIndex(note => note.id === `burg${lockedBurg.i}`);
|
||||
if (noteIndex !== -1) notes[noteIndex].id = `burg${newId}`;
|
||||
|
||||
lockedBurg.i = newId;
|
||||
newBurgs.push(lockedBurg);
|
||||
|
||||
burgsTree.add([lockedBurg.x, lockedBurg.y]);
|
||||
cells.burg[lockedBurg.cell] = id;
|
||||
cells.burg[lockedBurg.cell] = newId;
|
||||
|
||||
if (lockedBurg.capital) {
|
||||
const stateId = lockedBurg.state;
|
||||
states[stateId].capital = id;
|
||||
states[stateId].capital = newId;
|
||||
states[stateId].center = lockedBurg.cell;
|
||||
}
|
||||
}
|
||||
|
|
@ -367,8 +394,8 @@ function regenerateBurgs() {
|
|||
existingStatesCount;
|
||||
const spacing = (graphWidth + graphHeight) / 150 / (burgsCount ** 0.7 / 66); // base min distance between towns
|
||||
|
||||
for (let i = 0; i < sorted.length && burgs.length < burgsCount; i++) {
|
||||
const id = burgs.length;
|
||||
for (let i = 0; i < sorted.length && newBurgs.length < burgsCount; i++) {
|
||||
const id = newBurgs.length;
|
||||
const cell = sorted[i];
|
||||
const [x, y] = cells.p[cell];
|
||||
|
||||
|
|
@ -384,31 +411,34 @@ function regenerateBurgs() {
|
|||
|
||||
const culture = cells.culture[cell];
|
||||
const name = Names.getCulture(culture);
|
||||
burgs.push({cell, x, y, state: stateId, i: id, culture, name, capital, feature: cells.f[cell]});
|
||||
newBurgs.push({cell, x, y, state: stateId, i: id, culture, name, capital, feature: cells.f[cell]});
|
||||
burgsTree.add([x, y]);
|
||||
cells.burg[cell] = id;
|
||||
}
|
||||
|
||||
pack.burgs = newBurgs; // assign new burgs array
|
||||
|
||||
// add a capital at former place for states without added capitals
|
||||
states
|
||||
.filter(s => s.i && !s.removed && !s.capital)
|
||||
.forEach(s => {
|
||||
const burg = addBurg([cells.p[s.center][0], cells.p[s.center][1]]); // add new burg
|
||||
s.capital = burg;
|
||||
s.center = pack.burgs[burg].cell;
|
||||
pack.burgs[burg].capital = 1;
|
||||
pack.burgs[burg].state = s.i;
|
||||
moveBurgToGroup(burg, "cities");
|
||||
const [x, y] = cells.p[s.center];
|
||||
const burgId = addBurg([x, y]);
|
||||
s.capital = burgId;
|
||||
s.center = pack.burgs[burgId].cell;
|
||||
pack.burgs[burgId].capital = 1;
|
||||
pack.burgs[burgId].state = s.i;
|
||||
moveBurgToGroup(burgId, "cities");
|
||||
});
|
||||
|
||||
pack.features.forEach(f => {
|
||||
features.forEach(f => {
|
||||
if (f.port) f.port = 0; // reset features ports counter
|
||||
});
|
||||
|
||||
BurgsAndStates.specifyBurgs();
|
||||
BurgsAndStates.defineBurgFeatures();
|
||||
BurgsAndStates.drawBurgs();
|
||||
Routes.regenerate();
|
||||
regenerateRoutes();
|
||||
|
||||
// remove emblems
|
||||
document.querySelectorAll("[id^=burgCOA]").forEach(el => el.remove());
|
||||
|
|
@ -771,34 +801,6 @@ function addRiverOnClick() {
|
|||
}
|
||||
}
|
||||
|
||||
function toggleAddRoute() {
|
||||
const pressed = document.getElementById("addRoute").classList.contains("pressed");
|
||||
if (pressed) {
|
||||
unpressClickToAddButton();
|
||||
return;
|
||||
}
|
||||
|
||||
addFeature.querySelectorAll("button.pressed").forEach(b => b.classList.remove("pressed"));
|
||||
addRoute.classList.add("pressed");
|
||||
closeDialogs(".stable");
|
||||
viewbox.style("cursor", "crosshair").on("click", addRouteOnClick);
|
||||
tip("Click on map to add a first control point", true);
|
||||
if (!layerIsOn("toggleRoutes")) toggleRoutes();
|
||||
}
|
||||
|
||||
function addRouteOnClick() {
|
||||
unpressClickToAddButton();
|
||||
const point = d3.mouse(this);
|
||||
const id = getNextId("route");
|
||||
elSelected = routes
|
||||
.select("g")
|
||||
.append("path")
|
||||
.attr("id", id)
|
||||
.attr("data-new", 1)
|
||||
.attr("d", `M${point[0]},${point[1]}`);
|
||||
editRoute(true);
|
||||
}
|
||||
|
||||
function toggleAddMarker() {
|
||||
const pressed = document.getElementById("addMarker")?.classList.contains("pressed");
|
||||
if (pressed) {
|
||||
|
|
@ -939,6 +941,6 @@ function viewCellDetails() {
|
|||
}
|
||||
|
||||
async function overviewCharts() {
|
||||
const Overview = await import("../dynamic/overview/charts-overview.js?v=1.89.24");
|
||||
const Overview = await import("../dynamic/overview/charts-overview.js?v=1.99.00");
|
||||
Overview.open();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,13 +24,6 @@ function editUnits() {
|
|||
byId("heightExponentInput").addEventListener("input", changeHeightExponent);
|
||||
byId("heightExponentOutput").addEventListener("input", changeHeightExponent);
|
||||
byId("temperatureScale").addEventListener("change", changeTemperatureScale);
|
||||
byId("barSizeOutput").addEventListener("input", renderScaleBar);
|
||||
byId("barSizeInput").addEventListener("input", renderScaleBar);
|
||||
byId("barLabel").addEventListener("input", renderScaleBar);
|
||||
byId("barPosX").addEventListener("input", fitScaleBar);
|
||||
byId("barPosY").addEventListener("input", fitScaleBar);
|
||||
byId("barBackOpacity").addEventListener("input", changeScaleBarOpacity);
|
||||
byId("barBackColor").addEventListener("input", changeScaleBarColor);
|
||||
|
||||
byId("populationRateOutput").addEventListener("input", changePopulationRate);
|
||||
byId("populationRateInput").addEventListener("change", changePopulationRate);
|
||||
|
|
@ -62,6 +55,7 @@ function editUnits() {
|
|||
}
|
||||
|
||||
function changeDistanceScale() {
|
||||
distanceScale = +this.value;
|
||||
renderScaleBar();
|
||||
calculateFriendlyGridSize();
|
||||
}
|
||||
|
|
@ -84,14 +78,6 @@ function editUnits() {
|
|||
if (layerIsOn("toggleTemp")) drawTemp();
|
||||
}
|
||||
|
||||
function changeScaleBarOpacity() {
|
||||
scaleBar.select("rect").attr("opacity", this.value);
|
||||
}
|
||||
|
||||
function changeScaleBarColor() {
|
||||
scaleBar.select("rect").attr("fill", this.value);
|
||||
}
|
||||
|
||||
function changePopulationRate() {
|
||||
populationRate = +this.value;
|
||||
}
|
||||
|
|
@ -105,10 +91,9 @@ function editUnits() {
|
|||
}
|
||||
|
||||
function restoreDefaultUnits() {
|
||||
// distanceScale
|
||||
distanceScale = 3;
|
||||
byId("distanceScaleOutput").value = 3;
|
||||
byId("distanceScaleInput").value = 3;
|
||||
byId("distanceScaleOutput").value = distanceScale;
|
||||
byId("distanceScaleInput").value = distanceScale;
|
||||
unlock("distanceScale");
|
||||
|
||||
// units
|
||||
|
|
@ -129,19 +114,6 @@ function editUnits() {
|
|||
localStorage.removeItem("heightExponent");
|
||||
calculateTemperatures();
|
||||
|
||||
// scale bar
|
||||
barSizeOutput.value = barSizeInput.value = 2;
|
||||
barLabel.value = "";
|
||||
barBackOpacity.value = 0.2;
|
||||
barBackColor.value = "#ffffff";
|
||||
barPosX.value = barPosY.value = 99;
|
||||
|
||||
localStorage.removeItem("barSize");
|
||||
localStorage.removeItem("barLabel");
|
||||
localStorage.removeItem("barBackOpacity");
|
||||
localStorage.removeItem("barBackColor");
|
||||
localStorage.removeItem("barPosX");
|
||||
localStorage.removeItem("barPosY");
|
||||
renderScaleBar();
|
||||
|
||||
// population
|
||||
|
|
@ -207,13 +179,15 @@ function editUnits() {
|
|||
tip("Draw a curve along routes to measure length. Hold Shift to measure away from roads.", true);
|
||||
unitsBottom.querySelectorAll(".pressed").forEach(button => button.classList.remove("pressed"));
|
||||
this.classList.add("pressed");
|
||||
|
||||
viewbox.style("cursor", "crosshair").call(
|
||||
d3.drag().on("start", function () {
|
||||
const cells = pack.cells;
|
||||
const burgs = pack.burgs;
|
||||
const point = d3.mouse(this);
|
||||
const c = findCell(point[0], point[1]);
|
||||
if (cells.road[c] || d3.event.sourceEvent.shiftKey) {
|
||||
|
||||
if (Routes.isConnected(c) || d3.event.sourceEvent.shiftKey) {
|
||||
const b = cells.burg[c];
|
||||
const x = b ? burgs[b].x : cells.p[c][0];
|
||||
const y = b ? burgs[b].y : cells.p[c][1];
|
||||
|
|
@ -222,7 +196,7 @@ function editUnits() {
|
|||
d3.event.on("drag", function () {
|
||||
const point = d3.mouse(this);
|
||||
const c = findCell(point[0], point[1]);
|
||||
if (cells.road[c] || d3.event.sourceEvent.shiftKey) {
|
||||
if (Routes.isConnected(c) || d3.event.sourceEvent.shiftKey) {
|
||||
routeOpisometer.trackCell(c, true);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
|
|
@ -5,18 +5,17 @@ function editWorld() {
|
|||
title: "Configure World",
|
||||
resizable: false,
|
||||
width: "minmax(40em, 85vw)",
|
||||
buttons: {
|
||||
"Whole World": () => applyWorldPreset(100, 50),
|
||||
Northern: () => applyWorldPreset(33, 25),
|
||||
Tropical: () => applyWorldPreset(33, 50),
|
||||
Southern: () => applyWorldPreset(33, 75)
|
||||
},
|
||||
buttons: {"Update world": updateWorld},
|
||||
open: function () {
|
||||
const buttons = $(this).dialog("widget").find(".ui-dialog-buttonset > button");
|
||||
buttons[0].addEventListener("mousemove", () => tip("Click to set map size to cover the whole World"));
|
||||
buttons[1].addEventListener("mousemove", () => tip("Click to set map size to cover the Northern latitudes"));
|
||||
buttons[2].addEventListener("mousemove", () => tip("Click to set map size to cover the Tropical latitudes"));
|
||||
buttons[3].addEventListener("mousemove", () => tip("Click to set map size to cover the Southern latitudes"));
|
||||
const checkbox = /* html */ `<div class="dontAsk" data-tip="Automatically update world on input changes and button clicks">
|
||||
<input id="wcAutoChange" class="checkbox" type="checkbox" checked />
|
||||
<label for="wcAutoChange" class="checkbox-label"><i>auto-apply changes</i></label>
|
||||
</div>`;
|
||||
const pane = this.parentElement.querySelector(".ui-dialog-buttonpane");
|
||||
pane.insertAdjacentHTML("afterbegin", checkbox);
|
||||
|
||||
const button = this.parentElement.querySelector(".ui-dialog-buttonset > button");
|
||||
button.on("mousemove", () => tip("Apply curreny settings to the map"));
|
||||
},
|
||||
close: function () {
|
||||
$(this).dialog("destroy");
|
||||
|
|
@ -34,12 +33,17 @@ function editWorld() {
|
|||
if (modules.editWorld) return;
|
||||
modules.editWorld = true;
|
||||
|
||||
byId("worldControls").addEventListener("input", e => updateWorld(e.target));
|
||||
globe.select("#globeWindArrows").on("click", changeWind);
|
||||
globe.select("#globeGraticule").attr("d", round(path(d3.geoGraticule()()))); // globe graticule
|
||||
const graticule = d3.geoGraticule();
|
||||
globe.select("#globeWindArrows").on("click", handleWindChange);
|
||||
globe.select("#globeGraticule").attr("d", round(path(graticule()))); // globe graticule
|
||||
updateWindDirections();
|
||||
|
||||
byId("restoreWinds").addEventListener("click", restoreDefaultWinds);
|
||||
byId("worldControls").on("input", handleControlsChange);
|
||||
byId("restoreWinds").on("click", restoreDefaultWinds);
|
||||
byId("wcWholeWorld").on("click", () => applyWorldPreset(100, 50));
|
||||
byId("wcNorthern").on("click", () => applyWorldPreset(33, 25));
|
||||
byId("wcTropical").on("click", () => applyWorldPreset(33, 50));
|
||||
byId("wcSouthern").on("click", () => applyWorldPreset(33, 75));
|
||||
|
||||
function updateInputValues() {
|
||||
byId("temperatureEquatorInput").value = options.temperatureEquator;
|
||||
|
|
@ -55,27 +59,27 @@ function editWorld() {
|
|||
byId("temperatureSouthPoleF").innerText = convertTemperature(options.temperatureSouthPole, "°F");
|
||||
}
|
||||
|
||||
function updateWorld(el) {
|
||||
if (el?.dataset.stored) {
|
||||
const stored = el.dataset.stored;
|
||||
byId(stored + "Input").value = el.value;
|
||||
byId(stored + "Output").value = el.value;
|
||||
lock(el.dataset.stored);
|
||||
function handleControlsChange({target}) {
|
||||
const stored = target.dataset.stored;
|
||||
byId(stored + "Input").value = target.value;
|
||||
byId(stored + "Output").value = target.value;
|
||||
lock(stored);
|
||||
|
||||
if (stored === "temperatureEquator") {
|
||||
options.temperatureEquator = Number(el.value);
|
||||
byId("temperatureEquatorF").innerText = convertTemperature(options.temperatureEquator, "°F");
|
||||
}
|
||||
if (stored === "temperatureNorthPole") {
|
||||
options.temperatureNorthPole = Number(el.value);
|
||||
byId("temperatureNorthPoleF").innerText = convertTemperature(options.temperatureNorthPole, "°F");
|
||||
}
|
||||
if (stored === "temperatureSouthPole") {
|
||||
options.temperatureSouthPole = Number(el.value);
|
||||
byId("temperatureSouthPoleF").innerText = convertTemperature(options.temperatureSouthPole, "°F");
|
||||
}
|
||||
if (stored === "temperatureEquator") {
|
||||
options.temperatureEquator = Number(target.value);
|
||||
byId("temperatureEquatorF").innerText = convertTemperature(options.temperatureEquator, "°F");
|
||||
} else if (stored === "temperatureNorthPole") {
|
||||
options.temperatureNorthPole = Number(target.value);
|
||||
byId("temperatureNorthPoleF").innerText = convertTemperature(options.temperatureNorthPole, "°F");
|
||||
} else if (stored === "temperatureSouthPole") {
|
||||
options.temperatureSouthPole = Number(target.value);
|
||||
byId("temperatureSouthPoleF").innerText = convertTemperature(options.temperatureSouthPole, "°F");
|
||||
}
|
||||
|
||||
if (byId("wcAutoChange").checked) updateWorld();
|
||||
}
|
||||
|
||||
function updateWorld() {
|
||||
updateGlobeTemperature();
|
||||
updateGlobePosition();
|
||||
calculateTemperatures();
|
||||
|
|
@ -101,21 +105,22 @@ function editWorld() {
|
|||
|
||||
calculateMapCoordinates();
|
||||
const mc = mapCoordinates;
|
||||
const scale = +distanceScaleInput.value;
|
||||
const unit = distanceUnitInput.value;
|
||||
const meridian = toKilometer(eqD * 2 * scale);
|
||||
const meridian = toKilometer(eqD * 2 * distanceScale);
|
||||
byId("mapSize").innerHTML = `${graphWidth}x${graphHeight}`;
|
||||
byId("mapSizeFriendly").innerHTML = `${rn(graphWidth * scale)}x${rn(graphHeight * scale)} ${unit}`;
|
||||
byId("mapSizeFriendly").innerHTML = `${rn(graphWidth * distanceScale)}x${rn(graphHeight * distanceScale)} ${unit}`;
|
||||
byId("meridianLength").innerHTML = rn(eqD * 2);
|
||||
byId("meridianLengthFriendly").innerHTML = `${rn(eqD * 2 * scale)} ${unit}`;
|
||||
byId("meridianLengthFriendly").innerHTML = `${rn(eqD * 2 * distanceScale)} ${unit}`;
|
||||
byId("meridianLengthEarth").innerHTML = meridian ? " = " + rn(meridian / 200) + "%🌏" : "";
|
||||
byId("mapCoordinates").innerHTML = `${lat(mc.latN)} ${Math.abs(rn(mc.lonW))}°W; ${lat(mc.latS)} ${rn(mc.lonE)}°E`;
|
||||
|
||||
function toKilometer(v) {
|
||||
if (unit === "km") return v;
|
||||
else if (unit === "mi") return v * 1.60934;
|
||||
else if (unit === "lg") return v * 5.556;
|
||||
else if (unit === "vr") return v * 1.0668;
|
||||
if (unit === "mi") return v * 1.60934;
|
||||
if (unit === "lg") return v * 4.828;
|
||||
if (unit === "vr") return v * 1.0668;
|
||||
if (unit === "nmi") return v * 1.852;
|
||||
if (unit === "nlg") return v * 5.556;
|
||||
return 0; // 0 if distanceUnitInput is a custom unit
|
||||
}
|
||||
|
||||
|
|
@ -128,6 +133,7 @@ function editWorld() {
|
|||
[mc.lonW, mc.latN],
|
||||
[mc.lonE, mc.latS]
|
||||
]);
|
||||
|
||||
globe.select("#globeArea").attr("d", round(path(area.outline()))); // map area
|
||||
}
|
||||
|
||||
|
|
@ -161,21 +167,22 @@ function editWorld() {
|
|||
});
|
||||
}
|
||||
|
||||
function changeWind() {
|
||||
function handleWindChange() {
|
||||
const arrow = d3.event.target.nextElementSibling;
|
||||
const tier = +arrow.dataset.tier;
|
||||
options.winds[tier] = (options.winds[tier] + 45) % 360;
|
||||
const tr = parseTransform(arrow.getAttribute("transform"));
|
||||
arrow.setAttribute("transform", `rotate(${options.winds[tier]} ${tr[1]} ${tr[2]})`);
|
||||
localStorage.setItem("winds", options.winds);
|
||||
|
||||
const mapTiers = d3.range(mapCoordinates.latN, mapCoordinates.latS, -30).map(c => ((90 - c) / 30) | 0);
|
||||
if (mapTiers.includes(tier)) updateWorld();
|
||||
if (byId("wcAutoChange").checked && mapTiers.includes(tier)) updateWorld();
|
||||
}
|
||||
|
||||
function restoreDefaultWinds() {
|
||||
const defaultWinds = [225, 45, 225, 315, 135, 315];
|
||||
const mapTiers = d3.range(mapCoordinates.latN, mapCoordinates.latS, -30).map(c => ((90 - c) / 30) | 0);
|
||||
const update = mapTiers.some(t => options.winds[t] != defaultWinds[t]);
|
||||
const update = byId("wcAutoChange").checked && mapTiers.some(t => options.winds[t] != defaultWinds[t]);
|
||||
options.winds = defaultWinds;
|
||||
updateWindDirections();
|
||||
if (update) updateWorld();
|
||||
|
|
@ -186,6 +193,6 @@ function editWorld() {
|
|||
byId("latitudeInput").value = byId("latitudeOutput").value = lat;
|
||||
lock("mapSize");
|
||||
lock("latitude");
|
||||
updateWorld();
|
||||
if (byId("wcAutoChange").checked) updateWorld();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
function editZones() {
|
||||
closeDialogs();
|
||||
if (!layerIsOn("toggleZones")) toggleZones();
|
||||
const body = document.getElementById("zonesBodySection");
|
||||
const body = byId("zonesBodySection");
|
||||
|
||||
updateFilters();
|
||||
zonesEditorAddLines();
|
||||
|
|
@ -20,20 +20,20 @@ function editZones() {
|
|||
});
|
||||
|
||||
// add listeners
|
||||
document.getElementById("zonesFilterType").addEventListener("click", updateFilters);
|
||||
document.getElementById("zonesFilterType").addEventListener("change", filterZonesByType);
|
||||
document.getElementById("zonesEditorRefresh").addEventListener("click", zonesEditorAddLines);
|
||||
document.getElementById("zonesEditStyle").addEventListener("click", () => editStyle("zones"));
|
||||
document.getElementById("zonesLegend").addEventListener("click", toggleLegend);
|
||||
document.getElementById("zonesPercentage").addEventListener("click", togglePercentageMode);
|
||||
document.getElementById("zonesManually").addEventListener("click", enterZonesManualAssignent);
|
||||
document.getElementById("zonesManuallyApply").addEventListener("click", applyZonesManualAssignent);
|
||||
document.getElementById("zonesManuallyCancel").addEventListener("click", cancelZonesManualAssignent);
|
||||
document.getElementById("zonesAdd").addEventListener("click", addZonesLayer);
|
||||
document.getElementById("zonesExport").addEventListener("click", downloadZonesData);
|
||||
document.getElementById("zonesRemove").addEventListener("click", toggleEraseMode);
|
||||
byId("zonesFilterType").on("click", updateFilters);
|
||||
byId("zonesFilterType").on("change", filterZonesByType);
|
||||
byId("zonesEditorRefresh").on("click", zonesEditorAddLines);
|
||||
byId("zonesEditStyle").on("click", () => editStyle("zones"));
|
||||
byId("zonesLegend").on("click", toggleLegend);
|
||||
byId("zonesPercentage").on("click", togglePercentageMode);
|
||||
byId("zonesManually").on("click", enterZonesManualAssignent);
|
||||
byId("zonesManuallyApply").on("click", applyZonesManualAssignent);
|
||||
byId("zonesManuallyCancel").on("click", cancelZonesManualAssignent);
|
||||
byId("zonesAdd").on("click", addZonesLayer);
|
||||
byId("zonesExport").on("click", downloadZonesData);
|
||||
byId("zonesRemove").on("click", toggleEraseMode);
|
||||
|
||||
body.addEventListener("click", function (ev) {
|
||||
body.on("click", function (ev) {
|
||||
const el = ev.target,
|
||||
cl = el.classList,
|
||||
zone = el.parentNode.dataset.id;
|
||||
|
|
@ -45,7 +45,7 @@ function editZones() {
|
|||
if (customization) selectZone(el);
|
||||
});
|
||||
|
||||
body.addEventListener("input", function (ev) {
|
||||
body.on("input", function (ev) {
|
||||
const el = ev.target;
|
||||
const zone = zones.select("#" + el.parentNode.dataset.id);
|
||||
|
||||
|
|
@ -58,10 +58,11 @@ function editZones() {
|
|||
const zones = Array.from(document.querySelectorAll("#zones > g"));
|
||||
const types = unique(zones.map(zone => zone.dataset.type));
|
||||
|
||||
const filterSelect = document.getElementById("zonesFilterType");
|
||||
const filterSelect = byId("zonesFilterType");
|
||||
const typeToFilterBy = types.includes(zonesFilterType.value) ? zonesFilterType.value : "all";
|
||||
|
||||
filterSelect.innerHTML = "<option value='all'>all</option>" + types.map(type => `<option value="${type}">${type}</option>`).join("");
|
||||
filterSelect.innerHTML =
|
||||
"<option value='all'>all</option>" + types.map(type => `<option value="${type}">${type}</option>`).join("");
|
||||
filterSelect.value = typeToFilterBy;
|
||||
}
|
||||
|
||||
|
|
@ -69,7 +70,7 @@ function editZones() {
|
|||
function zonesEditorAddLines() {
|
||||
const unit = " " + getAreaUnit();
|
||||
|
||||
const typeToFilterBy = document.getElementById("zonesFilterType").value;
|
||||
const typeToFilterBy = byId("zonesFilterType").value;
|
||||
const zones = Array.from(document.querySelectorAll("#zones > g"));
|
||||
const filteredZones = typeToFilterBy === "all" ? zones : zones.filter(zone => zone.dataset.type === typeToFilterBy);
|
||||
|
||||
|
|
@ -80,9 +81,12 @@ function editZones() {
|
|||
const fill = zoneEl.getAttribute("fill");
|
||||
const area = getArea(d3.sum(c.map(i => pack.cells.area[i])));
|
||||
const rural = d3.sum(c.map(i => pack.cells.pop[i])) * populationRate;
|
||||
const urban = d3.sum(c.map(i => pack.cells.burg[i]).map(b => pack.burgs[b].population)) * populationRate * urbanization;
|
||||
const urban =
|
||||
d3.sum(c.map(i => pack.cells.burg[i]).map(b => pack.burgs[b].population)) * populationRate * urbanization;
|
||||
const population = rural + urban;
|
||||
const populationTip = `Total population: ${si(population)}; Rural population: ${si(rural)}; Urban population: ${si(urban)}. Click to change`;
|
||||
const populationTip = `Total population: ${si(population)}; Rural population: ${si(
|
||||
rural
|
||||
)}; Urban population: ${si(urban)}. Click to change`;
|
||||
const inactive = zoneEl.style.display === "none";
|
||||
const focused = defs.select("#fog #focus" + zoneEl.id).size();
|
||||
|
||||
|
|
@ -98,8 +102,12 @@ function editZones() {
|
|||
<span data-tip="${populationTip}" class="icon-male hide"></span>
|
||||
<div data-tip="${populationTip}" class="culturePopulation hide">${si(population)}</div>
|
||||
<span data-tip="Drag to raise or lower the zone" class="icon-resize-vertical hide"></span>
|
||||
<span data-tip="Toggle zone focus" class="icon-pin ${focused ? "" : " inactive"} hide ${c.length ? "" : " placeholder"}"></span>
|
||||
<span data-tip="Toggle zone visibility" class="icon-eye ${inactive ? " inactive" : ""} hide ${c.length ? "" : " placeholder"}"></span>
|
||||
<span data-tip="Toggle zone focus" class="icon-pin ${focused ? "" : " inactive"} hide ${
|
||||
c.length ? "" : " placeholder"
|
||||
}"></span>
|
||||
<span data-tip="Toggle zone visibility" class="icon-eye ${inactive ? " inactive" : ""} hide ${
|
||||
c.length ? "" : " placeholder"
|
||||
}"></span>
|
||||
<span data-tip="Remove zone" class="icon-trash-empty hide"></span>
|
||||
</div>`;
|
||||
});
|
||||
|
|
@ -109,7 +117,9 @@ function editZones() {
|
|||
// update footer
|
||||
const totalArea = getArea(graphWidth * graphHeight);
|
||||
zonesFooterArea.dataset.area = totalArea;
|
||||
const totalPop = (d3.sum(pack.cells.pop) + d3.sum(pack.burgs.filter(b => !b.removed).map(b => b.population)) * urbanization) * populationRate;
|
||||
const totalPop =
|
||||
(d3.sum(pack.cells.pop) + d3.sum(pack.burgs.filter(b => !b.removed).map(b => b.population)) * urbanization) *
|
||||
populationRate;
|
||||
zonesFooterPopulation.dataset.population = totalPop;
|
||||
zonesFooterNumber.innerHTML = /* html */ `${filteredZones.length} of ${zones.length}`;
|
||||
zonesFooterCells.innerHTML = pack.cells.i.length;
|
||||
|
|
@ -117,8 +127,8 @@ function editZones() {
|
|||
zonesFooterPopulation.innerHTML = si(totalPop);
|
||||
|
||||
// add listeners
|
||||
body.querySelectorAll("div.states").forEach(el => el.addEventListener("mouseenter", ev => zoneHighlightOn(ev)));
|
||||
body.querySelectorAll("div.states").forEach(el => el.addEventListener("mouseleave", ev => zoneHighlightOff(ev)));
|
||||
body.querySelectorAll("div.states").forEach(el => el.on("mouseenter", ev => zoneHighlightOn(ev)));
|
||||
body.querySelectorAll("div.states").forEach(el => el.on("mouseleave", ev => zoneHighlightOff(ev)));
|
||||
|
||||
if (body.dataset.type === "percentage") {
|
||||
body.dataset.type = "absolute";
|
||||
|
|
@ -150,7 +160,13 @@ function editZones() {
|
|||
zonesEditorAddLines();
|
||||
}
|
||||
|
||||
$(body).sortable({items: "div.states", handle: ".icon-resize-vertical", containment: "parent", axis: "y", update: movezone});
|
||||
$(body).sortable({
|
||||
items: "div.states",
|
||||
handle: ".icon-resize-vertical",
|
||||
containment: "parent",
|
||||
axis: "y",
|
||||
update: movezone
|
||||
});
|
||||
function movezone(ev, ui) {
|
||||
const zone = $("#" + ui.item.attr("data-id"));
|
||||
const prev = $("#" + ui.item.prev().attr("data-id"));
|
||||
|
|
@ -166,7 +182,7 @@ function editZones() {
|
|||
if (!layerIsOn("toggleZones")) toggleZones();
|
||||
customization = 10;
|
||||
document.querySelectorAll("#zonesBottom > *").forEach(el => (el.style.display = "none"));
|
||||
document.getElementById("zonesManuallyButtons").style.display = "inline-block";
|
||||
byId("zonesManuallyButtons").style.display = "inline-block";
|
||||
|
||||
zonesEditor.querySelectorAll(".hide").forEach(el => el.classList.add("hidden"));
|
||||
zonesFooter.style.display = "none";
|
||||
|
|
@ -174,7 +190,11 @@ function editZones() {
|
|||
$("#zonesEditor").dialog({position: {my: "right top", at: "right-10 top+10", of: "svg", collision: "fit"}});
|
||||
|
||||
tip("Click to select a zone, drag to paint a zone", true);
|
||||
viewbox.style("cursor", "crosshair").on("click", selectZoneOnMapClick).call(d3.drag().on("start", dragZoneBrush)).on("touchmove mousemove", moveZoneBrush);
|
||||
viewbox
|
||||
.style("cursor", "crosshair")
|
||||
.on("click", selectZoneOnMapClick)
|
||||
.call(d3.drag().on("start", dragZoneBrush))
|
||||
.on("touchmove mousemove", moveZoneBrush);
|
||||
|
||||
body.querySelector("div").classList.add("selected");
|
||||
zones.selectAll("g").each(function () {
|
||||
|
|
@ -195,24 +215,27 @@ function editZones() {
|
|||
}
|
||||
|
||||
function dragZoneBrush() {
|
||||
const r = +zonesBrush.value;
|
||||
const radius = +byId("zonesBrush").value;
|
||||
const eraseMode = byId("zonesRemove").classList.contains("pressed");
|
||||
const landOnly = byId("zonesBrushLandOnly").checked;
|
||||
|
||||
const selected = body.querySelector("div.selected");
|
||||
const zone = zones.select("#" + selected.dataset.id);
|
||||
const base = zone.attr("id") + "_"; // id generic part
|
||||
|
||||
d3.event.on("drag", () => {
|
||||
if (!d3.event.dx && !d3.event.dy) return;
|
||||
const p = d3.mouse(this);
|
||||
moveCircle(p[0], p[1], r);
|
||||
const [x, y] = d3.mouse(this);
|
||||
moveCircle(x, y, radius);
|
||||
|
||||
const selection = r > 5 ? findAll(p[0], p[1], r) : [findCell(p[0], p[1], r)];
|
||||
let selection = radius > 5 ? findAll(x, y, radius) : [findCell(x, y, radius)];
|
||||
if (landOnly) selection = selection.filter(i => pack.cells.h[i] >= 20);
|
||||
if (!selection) return;
|
||||
|
||||
const selected = body.querySelector("div.selected");
|
||||
const zone = zones.select("#" + selected.dataset.id);
|
||||
const base = zone.attr("id") + "_"; // id generic part
|
||||
const dataCells = zone.attr("data-cells");
|
||||
let cells = dataCells ? dataCells.split(",").map(i => +i) : [];
|
||||
|
||||
const erase = document.getElementById("zonesRemove").classList.contains("pressed");
|
||||
if (erase) {
|
||||
if (eraseMode) {
|
||||
// remove
|
||||
selection.forEach(i => {
|
||||
const index = cells.indexOf(i);
|
||||
|
|
@ -280,12 +303,13 @@ function editZones() {
|
|||
customization = 0;
|
||||
removeCircle();
|
||||
document.querySelectorAll("#zonesBottom > *").forEach(el => (el.style.display = "inline-block"));
|
||||
document.getElementById("zonesManuallyButtons").style.display = "none";
|
||||
byId("zonesManuallyButtons").style.display = "none";
|
||||
|
||||
zonesEditor.querySelectorAll(".hide:not(.show)").forEach(el => el.classList.remove("hidden"));
|
||||
zonesFooter.style.display = "block";
|
||||
body.querySelectorAll("div > input, select, svg").forEach(e => (e.style.pointerEvents = "all"));
|
||||
if (!close) $("#zonesEditor").dialog({position: {my: "right top", at: "right-10 top+10", of: "svg", collision: "fit"}});
|
||||
if (!close)
|
||||
$("#zonesEditor").dialog({position: {my: "right top", at: "right-10 top+10", of: "svg", collision: "fit"}});
|
||||
|
||||
restoreDefaultEvents();
|
||||
clearMainTip();
|
||||
|
|
@ -300,7 +324,7 @@ function editZones() {
|
|||
const fill = el.getAttribute("fill");
|
||||
const callback = newFill => {
|
||||
el.fill = newFill;
|
||||
document.getElementById(el.parentNode.dataset.id).setAttribute("fill", newFill);
|
||||
byId(el.parentNode.dataset.id).setAttribute("fill", newFill);
|
||||
};
|
||||
|
||||
openPicker(fill, callback);
|
||||
|
|
@ -356,7 +380,8 @@ function editZones() {
|
|||
body.querySelectorAll(":scope > div").forEach(function (el) {
|
||||
el.querySelector(".stateCells").innerHTML = rn((+el.dataset.cells / totalCells) * 100, 2) + "%";
|
||||
el.querySelector(".biomeArea").innerHTML = rn((+el.dataset.area / totalArea) * 100, 2) + "%";
|
||||
el.querySelector(".culturePopulation").innerHTML = rn((+el.dataset.population / totalPopulation) * 100, 2) + "%";
|
||||
el.querySelector(".culturePopulation").innerHTML =
|
||||
rn((+el.dataset.population / totalPopulation) * 100, 2) + "%";
|
||||
});
|
||||
} else {
|
||||
body.dataset.type = "absolute";
|
||||
|
|
@ -369,7 +394,13 @@ function editZones() {
|
|||
const description = "Unknown zone";
|
||||
const type = "Unknown";
|
||||
const fill = "url(#hatch" + (id.slice(4) % 42) + ")";
|
||||
zones.append("g").attr("id", id).attr("data-description", description).attr("data-type", type).attr("data-cells", "").attr("fill", fill);
|
||||
zones
|
||||
.append("g")
|
||||
.attr("id", id)
|
||||
.attr("data-description", description)
|
||||
.attr("data-type", type)
|
||||
.attr("data-cells", "")
|
||||
.attr("fill", fill);
|
||||
|
||||
zonesEditorAddLines();
|
||||
}
|
||||
|
|
@ -411,13 +442,19 @@ function editZones() {
|
|||
const burgs = pack.burgs.filter(b => !b.removed && cells.includes(b.cell));
|
||||
|
||||
const rural = rn(d3.sum(cells.map(i => pack.cells.pop[i])) * populationRate);
|
||||
const urban = rn(d3.sum(cells.map(i => pack.cells.burg[i]).map(b => pack.burgs[b].population)) * populationRate * urbanization);
|
||||
const urban = rn(
|
||||
d3.sum(cells.map(i => pack.cells.burg[i]).map(b => pack.burgs[b].population)) * populationRate * urbanization
|
||||
);
|
||||
const total = rural + urban;
|
||||
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:
|
||||
<input type="number" min="0" step="1" id="urbanPop" value=${urban} style="width:6em" ${burgs.length ? "" : "disabled"} />
|
||||
<p>Total population: ${l(total)} ⇒ <span id="totalPop">${l(total)}</span> (<span id="totalPopPerc">100</span>%)</p>`;
|
||||
<input type="number" min="0" step="1" id="urbanPop" value=${urban} style="width:6em" ${
|
||||
burgs.length ? "" : "disabled"
|
||||
} />
|
||||
<p>Total population: ${l(total)} ⇒ <span id="totalPop">${l(
|
||||
total
|
||||
)}</span> (<span id="totalPopPerc">100</span>%)</p>`;
|
||||
|
||||
const update = function () {
|
||||
const totalNew = ruralPop.valueAsNumber + urbanPop.valueAsNumber;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue