Files
tidefront/apps/web/src/map/terrain-raster.ts
T

218 lines
11 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Karte 2: Rasterteil des Geländes – nur noch weiche, niederfrequente Flächen (Tiefentönung des Meeres, Relief und
// Farbe des Landes), die beim Vergrößern nicht pixelig wirken. Alles Scharfe (Küste, Tiefenlinien, Inseln) zeichnet
// terrain.ts als Vektor darüber. Meer und Land sind getrennte Bilder, jedes über die Küste hinaus fortgesetzt; das
// Landbild wird mit der Vektor-Landfläche maskiert (scharfe Kante bei jedem Zoom).
import { COLS, HEX_SIZE_KM, HEX_W, KM_PER_DEG_LAT, KM_PER_DEG_LON, LAT1, LON0, ROWS, ROW_H } from "@tidefront/world";
import { coastGeometry, type XY } from "./coastline.ts";
import { contourLines, simplify, smoothOpen } from "./contours.ts";
import { mapColors, pixi } from "../lib/theme-map.ts";
import type { Theme } from "../lib/theme.ts";
/** Rasterauflösung: Kilometer je Pixel (weiche Flächen; Kanten kommen aus Vektoren). */
export const KM_PX = 5;
export const X0 = -HEX_W;
export const Y0 = -HEX_SIZE_KM * 1.2;
export const W = Math.ceil((HEX_W * (COLS + 1.5)) / KM_PX);
export const H = Math.ceil((ROW_H * (ROWS - 1) + HEX_SIZE_KM * 2.4) / KM_PX);
/** Gebirge als Höhenbuckel: Länge, Breite, Radius in km, Höhe (0..1). */
const RIDGES: [number, number, number, number][] = [
[10, 46.5, 260, 1], [7, 45.5, 160, 0.8], [13.5, 47, 200, 0.8], [0.5, 42.7, 170, 0.75], [-4, 40.5, 280, 0.3], [-3.2, 37.1, 120, 0.5],
[13, 42.5, 180, 0.55], [16, 40, 130, 0.4], [20, 42.3, 260, 0.6], [22.5, 39.5, 180, 0.5], [25, 42, 200, 0.45], [33, 38.5, 380, 0.6],
[37, 37.5, 200, 0.55], [-5, 31.5, 380, 0.85], [2, 34.5, 260, 0.45], [9, 61.5, 330, 0.75], [15, 66, 320, 0.7], [18.5, 68.5, 260, 0.6],
[-4.5, 57, 150, 0.45], [-3.8, 52.6, 110, 0.35], [-18.5, 64.8, 160, 0.6], [-80, 37, 320, 0.45], [-77, 40.5, 260, 0.35],
[-72.5, 44, 220, 0.35], [-64, 54, 420, 0.35], [-66, 58.5, 260, 0.4], [-42, 67, 520, 0.9], [-46, 63, 420, 0.8], [-38, 71, 420, 0.95],
[24, 47, 260, 0.45], [36, 33.5, 140, 0.4], [4.5, 50, 180, 0.2], [9, 50.5, 220, 0.25], [42, 43, 250, 0.9], [8.9, 40.1, 70, 0.4],
[9.1, 42.2, 60, 0.5], [14.6, 37.7, 70, 0.45], [24.8, 35.2, 60, 0.45], [33, 34.9, 50, 0.4],
];
function hash(x: number, y: number): number {
let h = (x * 374761393 + y * 668265263) | 0;
h = Math.imul(h ^ (h >>> 13), 1274126177);
h ^= h >>> 16;
return (h >>> 0) / 4294967296;
}
function valueNoise(x: number, y: number): number {
const xi = Math.floor(x), yi = Math.floor(y);
const fx = x - xi, fy = y - yi;
const sx = fx * fx * (3 - 2 * fx), sy = fy * fy * (3 - 2 * fy);
const a = hash(xi, yi), b = hash(xi + 1, yi), c = hash(xi, yi + 1), d = hash(xi + 1, yi + 1);
return a + (b - a) * sx + (c - a) * sy + (a - b - c + d) * sx * sy;
}
function fbm(x: number, y: number): number {
let v = 0, amp = 0.5, f = 1;
for (let o = 0; o < 4; o++) { v += amp * valueNoise(x * f, y * f); f *= 2.03; amp *= 0.5; }
return v / 0.9375;
}
function canvas(w: number, h: number): [HTMLCanvasElement, CanvasRenderingContext2D] {
const c = document.createElement("canvas");
c.width = w;
c.height = h;
return [c, c.getContext("2d", { willReadFrequently: true })!];
}
const px = (p: XY) => [(p.x - X0) / KM_PX, (p.y - Y0) / KM_PX] as const;
function path(ctx: CanvasRenderingContext2D, ring: XY[]): void {
ring.forEach((p, i) => { const [x, y] = px(p); if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); });
ctx.closePath();
}
/** Landanteil der Umgebung (0..1) durch Verkleinern und weiches Vergrößern der Maske. */
function proximity(mask: HTMLCanvasElement, factor: number): Float32Array {
const [small, sctx] = canvas(Math.max(2, Math.ceil(W / factor)), Math.max(2, Math.ceil(H / factor)));
sctx.imageSmoothingEnabled = true;
sctx.imageSmoothingQuality = "high";
sctx.drawImage(mask, 0, 0, small.width, small.height);
const [, bctx] = canvas(W, H);
bctx.imageSmoothingEnabled = true;
bctx.imageSmoothingQuality = "high";
bctx.drawImage(small, 0, 0, W, H);
const d = bctx.getImageData(0, 0, W, H).data;
const out = new Float32Array(W * H);
for (let i = 0; i < W * H; i++) out[i] = d[i * 4 + 3] / 255;
return out;
}
type RGB = [number, number, number];
const rgb = (c: number): RGB => [(c >> 16) & 255, (c >> 8) & 255, c & 255];
const lerp = (a: RGB, b: RGB, t: number): RGB => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];
const clamp01 = (v: number) => (v < 0 ? 0 : v > 1 ? 1 : v);
const smooth = (a: number, b: number, v: number) => { const t = clamp01((v - a) / (b - a)); return t * t * (3 - 2 * t); };
const mix = (a: number, b: number, t: number) => { const x = lerp(rgb(a), rgb(b), t); return (Math.round(x[0]) << 16) | (Math.round(x[1]) << 8) | Math.round(x[2]); };
/**
* Geländefarben aus dem Farbsatz „Seekarte 2.0“ (lib/theme-map.ts, hell/dunkel): Meer mit leicht zum Flachwasser
* getönten Stufen an der Küste, Land mit zarter Schummerung, Küste, Raster.
*/
function terrainColors(theme: Theme) {
const c = mapColors(theme);
const sea = pixi(c.sea), shallow = pixi(c.shallow), land = pixi(c.land), coast = pixi(c.coast);
const dark = theme === "dark";
return {
sea, sea1: mix(sea, shallow, 0.12), sea2: mix(sea, shallow, 0.24), sea3: mix(sea, shallow, 0.38), isobath: mix(shallow, coast, 0.35),
shallow, land, land2: mix(land, coast, 0.1), shade: mix(land, dark ? 0x000000 : 0x5a4a2a, 0.5), ink: coast,
light: mix(land, dark ? 0x8a8f94 : 0xffffff, 0.6), ice: mix(land, dark ? 0x9aa6b0 : 0xffffff, 0.45), lowland: mix(land, sea, 0.12),
coast, grid: pixi(c.grid),
};
}
/** Aktuelle Geländefarben (setTerrainTheme vor dem Aufbau). */
export let COLORS = terrainColors("light");
let theme: Theme = "light";
export function setTerrainTheme(t: Theme): void { theme = t; COLORS = terrainColors(t); }
export interface TerrainRaster {
sea: HTMLCanvasElement;
land: HTMLCanvasElement;
/** Tiefenlinien in Weltkoordinaten: nah (flach), mittel, fern (Schelfkante, gestrichelt). */
isobaths: { near: XY[][]; mid: XY[][]; far: XY[][] };
}
const cached = new Map<Theme, Promise<TerrainRaster>>();
/** Kurz an den Browser abgeben, damit das Rechnen den Hauptthread nicht blockiert (Eingaben, Zeichnen). */
const yieldMain = () => new Promise<void>((r) => setTimeout(r, 0));
/** Zeilen je Rechenschritt (~20–40 ms auf einem Handy). */
const ROWS_PER_STEP = 64;
/**
* Rechnet Meer- und Landbild und die Tiefenlinien (einmal je Sitzung), in kleinen Schritten mit Pausen für den
* Hauptthread (Karte 2: erstes Zeichnen ohne lange Blockade; die Karte zeigt solange flache Farben).
*/
export function terrainRaster(): Promise<TerrainRaster> {
let r = cached.get(theme);
if (!r) { r = compute(COLORS); cached.set(theme, r); }
return r;
}
async function compute(colors: typeof COLORS): Promise<TerrainRaster> {
const C = Object.fromEntries(Object.entries(colors).map(([k, v]) => [k, rgb(v)])) as Record<keyof typeof COLORS, RGB>;
const SEA = [C.sea, C.sea1, C.sea2, C.sea3];
const geo = coastGeometry();
const [mask, mctx] = canvas(W, H);
mctx.fillStyle = "#fff";
mctx.beginPath();
for (const r of geo.land) path(mctx, r);
mctx.fill("nonzero");
mctx.globalCompositeOperation = "destination-out";
mctx.beginPath();
for (const r of geo.holes) path(mctx, r);
mctx.fill("nonzero");
mctx.globalCompositeOperation = "source-over";
for (const s of geo.islets) { const [x, y] = px(s); mctx.beginPath(); mctx.arc(x, y, s.r / KM_PX, 0, Math.PI * 2); mctx.fill(); }
const m = mctx.getImageData(0, 0, W, H).data;
await yieldMain();
const near = proximity(mask, 6); // ~30 km
const far = proximity(mask, 28); // ~140 km
await yieldMain();
// Meer: stetige Tönung (keine Stufenkanten im Raster – die Tiefenlinien sind Vektoren)
const [seaC, sctx] = canvas(W, H);
const si = sctx.createImageData(W, H);
// Land: Höhe, Schummerung (Licht von Nordwest), Küstensaum; über die Küste hinaus fortgesetzt
const [landC, lctx] = canvas(W, H);
const li = lctx.createImageData(W, H);
const elev = new Float32Array(W * H);
const ridgePx = RIDGES.map(([lon, lat, r, h]) => { const [x, y] = px({ x: (lon - LON0) * KM_PER_DEG_LON, y: (LAT1 - lat) * KM_PER_DEG_LAT }); return [x, y, r / KM_PX, h] as const; });
for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) {
if (x === 0 && y % ROWS_PER_STEP === 0) await yieldMain();
const i = y * W + x;
const n = fbm(x / 30, y / 30);
let e = 0.12 + far[i] * 0.28 + (n - 0.5) * 0.35;
if (near[i] < 0.02) { elev[i] = e; continue; } // offene See: kein Relief nötig
for (const [rx, ry, rr, rh] of ridgePx) {
const dx = x - rx, dy = y - ry;
const d2 = (dx * dx + dy * dy) / (rr * rr);
if (d2 < 4) e += rh * Math.exp(-d2 * 1.6) * (0.65 + n * 0.7);
}
elev[i] = e;
}
for (let y = 0; y < H; y++) {
if (y % (ROWS_PER_STEP / 2) === 0) await yieldMain();
const lat = LAT1 - (Y0 + y * KM_PX) / KM_PER_DEG_LAT;
for (let x = 0; x < W; x++) {
const i = y * W + x;
const lon = LON0 + (X0 + x * KM_PX) / KM_PER_DEG_LON;
// Meer
const b = near[i] >= 0.12 ? 2 + clamp01((near[i] - 0.12) / 0.3) : far[i] >= 0.16 ? 1 + clamp01(near[i] / 0.12) : clamp01(far[i] / 0.16);
const k = Math.min(2, Math.floor(b));
let c = lerp(SEA[k], SEA[k + 1], smooth(0, 1, b - k));
const g = 1 + (valueNoise(x / 6, y / 6) - 0.5) * 0.025; // Papierkorn (günstiger als fbm)
const o = i * 4;
si.data[o] = c[0] * g; si.data[o + 1] = c[1] * g; si.data[o + 2] = c[2] * g; si.data[o + 3] = 255;
// Land
const e = elev[i];
const ex = elev[Math.min(W * H - 1, i + 1)] - elev[Math.max(0, i - 1)];
const ey = elev[Math.min(W * H - 1, i + W)] - elev[Math.max(0, i - W)];
const lit = clamp01(0.5 - (ex + ey) * 6); // Nordwestlicht
c = lerp(C.land, C.land2, clamp01(fbm(x / 9, y / 9) * 0.8 - 0.15));
c = lerp(c, C.lowland, smooth(0.35, 0.12, e) * 0.5);
const hill = smooth(0.45, 1.05, e);
c = lerp(c, C.shade, hill * (1 - lit) * 0.55);
c = lerp(c, C.light, hill * lit * 0.25);
const greenland = lon < -20 && lon > -62 && lat > 59.5;
if (greenland || (lon < -62 && lat > 66)) c = lerp(c, C.ice, smooth(0.25, 0.5, e));
c = lerp(c, C.ink, smooth(0.99, 0.7, near[i]) * 0.05 * (m[i * 4 + 3] > 127 ? 1 : 0)); // zarter Küstensaum innen
li.data[o] = c[0]; li.data[o + 1] = c[1]; li.data[o + 2] = c[2]; li.data[o + 3] = 255;
}
}
sctx.putImageData(si, 0, 0);
lctx.putImageData(li, 0, 0);
const toWorld = (polys: { x: number; y: number }[][], minLen: number) => polys
.map((p) => smoothOpen(simplify(p, 0.6)).map((q) => ({ x: X0 + q.x * KM_PX, y: Y0 + q.y * KM_PX })))
.filter((p) => p.length >= minLen);
await yieldMain();
const isoNear = toWorld(contourLines(near, W, H, 0.42), 4);
await yieldMain();
const isoMid = toWorld(contourLines(near, W, H, 0.12), 4);
await yieldMain();
const isoFar = toWorld(contourLines(far, W, H, 0.16), 6);
return { sea: seaC, land: landC, isobaths: { near: isoNear, mid: isoMid, far: isoFar } };
}