Fantasy-Map-Generator/procedural/src/engine/modules/heightmap-generator.js
2025-08-05 13:12:07 -04:00

554 lines
16 KiB
JavaScript

"use strict";
export function fromTemplate(grid, templateId, config, utils) {
const { heightmapTemplates, aleaPRNG } = utils;
const templateString = heightmapTemplates[templateId]?.template || "";
const steps = templateString.split("\n");
if (!steps.length) throw new Error(`Heightmap template: no steps. Template: ${templateId}. Steps: ${steps}`);
const { cellsDesired, cells, points } = grid;
let heights = cells.h ? Uint8Array.from(cells.h) : createTypedArray({ maxValue: 100, length: points.length });
const blobPower = getBlobPower(cellsDesired);
const linePower = getLinePower(cellsDesired);
// Set up PRNG if seed is provided
if (config.seed !== undefined) {
Math.random = aleaPRNG(config.seed);
}
for (const step of steps) {
const elements = step.trim().split(" ");
if (elements.length < 2) throw new Error(`Heightmap template: steps < 2. Template: ${templateId}. Step: ${elements}`);
heights = addStep(heights, grid, blobPower, linePower, utils, ...elements);
}
return heights;
}
export async function fromPrecreated(grid, imageId, config, utils) {
// This function requires browser-specific Canvas API and Image loading
// It should be handled by the viewer layer, not the headless engine
throw new Error("fromPrecreated requires browser environment - should be handled by viewer layer");
}
export async function generate(grid, config, utils) {
const { TIME, aleaPRNG } = utils;
TIME && console.time("defineHeightmap");
const templateId = config.heightmap.templateId;
// Set up PRNG if seed is provided
if (config.seed !== undefined) {
Math.random = aleaPRNG(config.seed);
}
const { heightmapTemplates } = utils;
const isTemplate = templateId in heightmapTemplates;
if (!isTemplate) {
throw new Error(`Template "${templateId}" not found. Available templates: ${Object.keys(heightmapTemplates).join(', ')}`);
}
const heights = fromTemplate(grid, templateId, config, utils);
TIME && console.timeEnd("defineHeightmap");
return heights;
}
function addStep(heights, grid, blobPower, linePower, utils, tool, a2, a3, a4, a5) {
if (tool === "Hill") return addHill(heights, grid, blobPower, utils, a2, a3, a4, a5);
if (tool === "Pit") return addPit(heights, grid, blobPower, utils, a2, a3, a4, a5);
if (tool === "Range") return addRange(heights, grid, linePower, utils, a2, a3, a4, a5);
if (tool === "Trough") return addTrough(heights, grid, linePower, utils, a2, a3, a4, a5);
if (tool === "Strait") return addStrait(heights, grid, utils, a2, a3);
if (tool === "Mask") return mask(heights, grid, a2);
if (tool === "Invert") return invert(heights, grid, a2, a3);
if (tool === "Add") return modify(heights, a3, +a2, 1);
if (tool === "Multiply") return modify(heights, a3, 0, +a2);
if (tool === "Smooth") return smooth(heights, grid, utils, a2);
return heights;
}
function getBlobPower(cells) {
const blobPowerMap = {
1000: 0.93,
2000: 0.95,
5000: 0.97,
10000: 0.98,
20000: 0.99,
30000: 0.991,
40000: 0.993,
50000: 0.994,
60000: 0.995,
70000: 0.9955,
80000: 0.996,
90000: 0.9964,
100000: 0.9973
};
return blobPowerMap[cells] || 0.98;
}
function getLinePower(cells) {
const linePowerMap = {
1000: 0.75,
2000: 0.77,
5000: 0.79,
10000: 0.81,
20000: 0.82,
30000: 0.83,
40000: 0.84,
50000: 0.86,
60000: 0.87,
70000: 0.88,
80000: 0.91,
90000: 0.92,
100000: 0.93
};
return linePowerMap[cells] || 0.81;
}
function addHill(heights, grid, blobPower, utils, count, height, rangeX, rangeY) {
const { getNumberInRange, findGridCell, lim } = utils;
const graphWidth = grid.cellsX;
const graphHeight = grid.cellsY;
count = getNumberInRange(count);
let newHeights = new Uint8Array(heights);
while (count > 0) {
addOneHill();
count--;
}
function addOneHill() {
const change = new Uint8Array(heights.length);
let limit = 0;
let start;
let h = lim(getNumberInRange(height));
do {
const x = getPointInRange(rangeX, graphWidth, utils);
const y = getPointInRange(rangeY, graphHeight, utils);
start = findGridCell(x, y, grid);
limit++;
} while (newHeights[start] + h > 90 && limit < 50);
change[start] = h;
const queue = [start];
while (queue.length) {
const q = queue.shift();
for (const c of grid.cells.c[q]) {
if (change[c]) continue;
change[c] = change[q] ** blobPower * (Math.random() * 0.2 + 0.9);
if (change[c] > 1) queue.push(c);
}
}
newHeights = newHeights.map((h, i) => lim(h + change[i]));
}
return newHeights;
}
function addPit(heights, grid, blobPower, utils, count, height, rangeX, rangeY) {
const { getNumberInRange, findGridCell, lim } = utils;
const graphWidth = grid.cellsX;
const graphHeight = grid.cellsY;
count = getNumberInRange(count);
let newHeights = new Uint8Array(heights);
while (count > 0) {
addOnePit();
count--;
}
function addOnePit() {
const used = new Uint8Array(heights.length);
let limit = 0, start;
let h = lim(getNumberInRange(height));
do {
const x = getPointInRange(rangeX, graphWidth, utils);
const y = getPointInRange(rangeY, graphHeight, utils);
start = findGridCell(x, y, grid);
limit++;
} while (newHeights[start] < 20 && limit < 50);
const queue = [start];
while (queue.length) {
const q = queue.shift();
h = h ** blobPower * (Math.random() * 0.2 + 0.9);
if (h < 1) return;
grid.cells.c[q].forEach(function (c, i) {
if (used[c]) return;
newHeights[c] = lim(newHeights[c] - h * (Math.random() * 0.2 + 0.9));
used[c] = 1;
queue.push(c);
});
}
}
return newHeights;
}
// fromCell, toCell are options cell ids
function addRange(heights, grid, linePower, utils, count, height, rangeX, rangeY, startCell, endCell) {
const { getNumberInRange, findGridCell, lim, d3 } = utils;
const graphWidth = grid.cellsX;
const graphHeight = grid.cellsY;
count = getNumberInRange(count);
let newHeights = new Uint8Array(heights);
while (count > 0) {
addOneRange();
count--;
}
function addOneRange() {
const used = new Uint8Array(heights.length);
let h = lim(getNumberInRange(height));
if (rangeX && rangeY) {
// find start and end points
const startX = getPointInRange(rangeX, graphWidth, utils);
const startY = getPointInRange(rangeY, graphHeight, utils);
let dist = 0, limit = 0, endX, endY;
do {
endX = Math.random() * graphWidth * 0.8 + graphWidth * 0.1;
endY = Math.random() * graphHeight * 0.7 + graphHeight * 0.15;
dist = Math.abs(endY - startY) + Math.abs(endX - startX);
limit++;
} while ((dist < graphWidth / 8 || dist > graphWidth / 3) && limit < 50);
startCell = findGridCell(startX, startY, grid);
endCell = findGridCell(endX, endY, grid);
}
let range = getRange(startCell, endCell);
// get main ridge
function getRange(cur, end) {
const range = [cur];
const p = grid.points;
used[cur] = 1;
while (cur !== end) {
let min = Infinity;
grid.cells.c[cur].forEach(function (e) {
if (used[e]) return;
let diff = (p[end][0] - p[e][0]) ** 2 + (p[end][1] - p[e][1]) ** 2;
if (Math.random() > 0.85) diff = diff / 2;
if (diff < min) {
min = diff;
cur = e;
}
});
if (min === Infinity) return range;
range.push(cur);
used[cur] = 1;
}
return range;
}
// add height to ridge and cells around
let queue = range.slice(), i = 0;
while (queue.length) {
const frontier = queue.slice();
(queue = []), i++;
frontier.forEach(i => {
newHeights[i] = lim(newHeights[i] + h * (Math.random() * 0.3 + 0.85));
});
h = h ** linePower - 1;
if (h < 2) break;
frontier.forEach(f => {
grid.cells.c[f].forEach(i => {
if (!used[i]) {
queue.push(i);
used[i] = 1;
}
});
});
}
// generate prominences
range.forEach((cur, d) => {
if (d % 6 !== 0) return;
for (const l of d3.range(i)) {
const min = grid.cells.c[cur][d3.scan(grid.cells.c[cur], (a, b) => newHeights[a] - newHeights[b])]; // downhill cell
newHeights[min] = (newHeights[cur] * 2 + newHeights[min]) / 3;
cur = min;
}
});
}
return newHeights;
}
function addTrough(heights, grid, linePower, utils, count, height, rangeX, rangeY, startCell, endCell) {
const { getNumberInRange, findGridCell, lim, d3 } = utils;
const graphWidth = grid.cellsX;
const graphHeight = grid.cellsY;
count = getNumberInRange(count);
let newHeights = new Uint8Array(heights);
while (count > 0) {
addOneTrough();
count--;
}
function addOneTrough() {
const used = new Uint8Array(heights.length);
let h = lim(getNumberInRange(height));
if (rangeX && rangeY) {
// find start and end points
let limit = 0, startX, startY, dist = 0, endX, endY;
do {
startX = getPointInRange(rangeX, graphWidth, utils);
startY = getPointInRange(rangeY, graphHeight, utils);
startCell = findGridCell(startX, startY, grid);
limit++;
} while (newHeights[startCell] < 20 && limit < 50);
limit = 0;
do {
endX = Math.random() * graphWidth * 0.8 + graphWidth * 0.1;
endY = Math.random() * graphHeight * 0.7 + graphHeight * 0.15;
dist = Math.abs(endY - startY) + Math.abs(endX - startX);
limit++;
} while ((dist < graphWidth / 8 || dist > graphWidth / 2) && limit < 50);
endCell = findGridCell(endX, endY, grid);
}
let range = getRange(startCell, endCell);
// get main ridge
function getRange(cur, end) {
const range = [cur];
const p = grid.points;
used[cur] = 1;
while (cur !== end) {
let min = Infinity;
grid.cells.c[cur].forEach(function (e) {
if (used[e]) return;
let diff = (p[end][0] - p[e][0]) ** 2 + (p[end][1] - p[e][1]) ** 2;
if (Math.random() > 0.8) diff = diff / 2;
if (diff < min) {
min = diff;
cur = e;
}
});
if (min === Infinity) return range;
range.push(cur);
used[cur] = 1;
}
return range;
}
// add height to ridge and cells around
let queue = range.slice(), i = 0;
while (queue.length) {
const frontier = queue.slice();
(queue = []), i++;
frontier.forEach(i => {
newHeights[i] = lim(newHeights[i] - h * (Math.random() * 0.3 + 0.85));
});
h = h ** linePower - 1;
if (h < 2) break;
frontier.forEach(f => {
grid.cells.c[f].forEach(i => {
if (!used[i]) {
queue.push(i);
used[i] = 1;
}
});
});
}
// generate prominences
range.forEach((cur, d) => {
if (d % 6 !== 0) return;
for (const l of d3.range(i)) {
const min = grid.cells.c[cur][d3.scan(grid.cells.c[cur], (a, b) => newHeights[a] - newHeights[b])]; // downhill cell
newHeights[min] = (newHeights[cur] * 2 + newHeights[min]) / 3;
cur = min;
}
});
}
return newHeights;
}
function addStrait(heights, grid, utils, width, direction = "vertical") {
const { getNumberInRange, findGridCell, P } = utils;
const graphWidth = grid.cellsX;
const graphHeight = grid.cellsY;
width = Math.min(getNumberInRange(width), grid.cellsX / 3);
if (width < 1 && P(width)) return heights;
let newHeights = new Uint8Array(heights);
const used = new Uint8Array(heights.length);
const vert = direction === "vertical";
const startX = vert ? Math.floor(Math.random() * graphWidth * 0.4 + graphWidth * 0.3) : 5;
const startY = vert ? 5 : Math.floor(Math.random() * graphHeight * 0.4 + graphHeight * 0.3);
const endX = vert
? Math.floor(graphWidth - startX - graphWidth * 0.1 + Math.random() * graphWidth * 0.2)
: graphWidth - 5;
const endY = vert
? graphHeight - 5
: Math.floor(graphHeight - startY - graphHeight * 0.1 + Math.random() * graphHeight * 0.2);
const start = findGridCell(startX, startY, grid);
const end = findGridCell(endX, endY, grid);
let range = getRange(start, end);
const query = [];
function getRange(cur, end) {
const range = [];
const p = grid.points;
while (cur !== end) {
let min = Infinity;
grid.cells.c[cur].forEach(function (e) {
let diff = (p[end][0] - p[e][0]) ** 2 + (p[end][1] - p[e][1]) ** 2;
if (Math.random() > 0.8) diff = diff / 2;
if (diff < min) {
min = diff;
cur = e;
}
});
range.push(cur);
}
return range;
}
const step = 0.1 / width;
while (width > 0) {
const exp = 0.9 - step * width;
range.forEach(function (r) {
grid.cells.c[r].forEach(function (e) {
if (used[e]) return;
used[e] = 1;
query.push(e);
newHeights[e] **= exp;
if (newHeights[e] > 100) newHeights[e] = 5;
});
});
range = query.slice();
width--;
}
return newHeights;
}
function modify(heights, range, add, mult, power) {
const { lim } = { lim: val => Math.max(0, Math.min(100, val)) };
const min = range === "land" ? 20 : range === "all" ? 0 : +range.split("-")[0];
const max = range === "land" || range === "all" ? 100 : +range.split("-")[1];
const isLand = min === 20;
return heights.map(h => {
if (h < min || h > max) return h;
if (add) h = isLand ? Math.max(h + add, 20) : h + add;
if (mult !== 1) h = isLand ? (h - 20) * mult + 20 : h * mult;
if (power) h = isLand ? (h - 20) ** power + 20 : h ** power;
return lim(h);
});
}
function smooth(heights, grid, utils, fr = 2, add = 0) {
const { d3, lim } = utils;
return heights.map((h, i) => {
const a = [h];
grid.cells.c[i].forEach(c => a.push(heights[c]));
if (fr === 1) return d3.mean(a) + add;
return lim((h * (fr - 1) + d3.mean(a) + add) / fr);
});
}
function mask(heights, grid, power = 1) {
const { lim } = { lim: val => Math.max(0, Math.min(100, val)) };
const graphWidth = grid.cellsX;
const graphHeight = grid.cellsY;
const fr = power ? Math.abs(power) : 1;
return heights.map((h, i) => {
const [x, y] = grid.points[i];
const nx = (2 * x) / graphWidth - 1; // [-1, 1], 0 is center
const ny = (2 * y) / graphHeight - 1; // [-1, 1], 0 is center
let distance = (1 - nx ** 2) * (1 - ny ** 2); // 1 is center, 0 is edge
if (power < 0) distance = 1 - distance; // inverted, 0 is center, 1 is edge
const masked = h * distance;
return lim((h * (fr - 1) + masked) / fr);
});
}
function invert(heights, grid, count, axes) {
const { P } = { P: probability => Math.random() < probability };
if (!P(count)) return heights;
const invertX = axes !== "y";
const invertY = axes !== "x";
const { cellsX, cellsY } = grid;
const inverted = heights.map((h, i) => {
const x = i % cellsX;
const y = Math.floor(i / cellsX);
const nx = invertX ? cellsX - x - 1 : x;
const ny = invertY ? cellsY - y - 1 : y;
const invertedI = nx + ny * cellsX;
return heights[invertedI];
});
return inverted;
}
function getPointInRange(range, length, utils) {
const { ERROR, rand } = utils;
if (typeof range !== "string") {
ERROR && console.error("Range should be a string");
return;
}
const min = range.split("-")[0] / 100 || 0;
const max = range.split("-")[1] / 100 || min;
return rand(min * length, max * length);
}
function createTypedArray({ maxValue, length }) {
return new Uint8Array(length);
}
// Export utility functions for standalone use
export {
addHill,
addPit,
addRange,
addTrough,
addStrait,
smooth,
modify,
mask,
invert
};