#!/usr/bin/env node /** * The finer country outlines for TREK Studio's vector map, one file per * country, built from the boundaries the server already bundles for Atlas. * * node scripts/build-country-detail.mjs * * Writes `public/country-detail/.json`. Run it when * `server/assets/atlas/admin0.geojson.gz` changes; the output is committed, so * a normal build never runs this. * * ── Why a second set beside countryShapes.ts ────────────────────────────── * * The bundled silhouettes (`src/components/Studio/countryShapes.ts`, from * build-country-shapes.mjs) are cut for a country drawn at postage-stamp size: * islands below 1.2% of the mainland are dropped and every outline keeps at * most 190 points. That is right for a whole country and wrong for a map of * part of one. Hawaii is a tenth of a percent of the United States, so a trip * there was drawn as a route over empty sea (#3056), and a week on the Greek * islands showed half of them. * * These keep every ring above a few square kilometres and a far larger point * budget. They are static files rather than code: a map that needs one loads * it when it is drawn (countryDetail.ts), the app bundle and the offline * precache stay as they were, and the coarse set stays the fallback whenever a * file has not arrived. * * Same projection, same antimeridian handling and the same 0..100 box as the * coarse set, with two decimals instead of one, so `countryWorldPath` and * `countryParts` read both alike. */ import fs from 'node:fs'; import path from 'node:path'; import url from 'node:url'; import zlib from 'node:zlib'; const HERE = path.dirname(url.fileURLToPath(import.meta.url)); const SRC = path.join(HERE, '..', '..', 'server', 'assets', 'atlas', 'admin0.geojson.gz'); const OUT = path.join(HERE, '..', 'public', 'country-detail'); /** Rings below this projected area (square degrees, about 5 km² at the equator) are specks at any map size. */ const MIN_RING_AREA = 0.0004; /** Never more than this many rings for one country. */ const MAX_RINGS = 240; /** Point budget per country, across every ring it keeps. */ const MAX_POINTS = 1600; /** Web Mercator, unscaled. y is flipped so it grows downwards like SVG's. */ function project([lng, lat]) { const clamped = Math.max(-85.05, Math.min(85.05, lat)); const rad = (clamped * Math.PI) / 180; return [lng, -(Math.log(Math.tan(Math.PI / 4 + rad / 2)) * 180) / Math.PI]; } function ringArea(ring) { let a = 0; for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) { a += ring[j][0] * ring[i][1] - ring[i][0] * ring[j][1]; } return Math.abs(a / 2); } /** Perpendicular distance from p to the segment ab, squared. */ function segDistSq(p, a, b) { let x = a[0], y = a[1]; let dx = b[0] - x, dy = b[1] - y; if (dx !== 0 || dy !== 0) { const t = ((p[0] - x) * dx + (p[1] - y) * dy) / (dx * dx + dy * dy); if (t > 1) { x = b[0]; y = b[1]; } else if (t > 0) { x += dx * t; y += dy * t; } } dx = p[0] - x; dy = p[1] - y; return dx * dx + dy * dy; } /** Douglas-Peucker, iterative so a long coastline cannot blow the stack. */ function simplify(points, tolerance) { if (points.length < 3) return points; const tolSq = tolerance * tolerance; const keep = new Uint8Array(points.length); keep[0] = 1; keep[points.length - 1] = 1; const stack = [[0, points.length - 1]]; while (stack.length) { const [first, last] = stack.pop(); let maxSq = 0; let index = 0; for (let i = first + 1; i < last; i++) { const d = segDistSq(points[i], points[first], points[last]); if (d > maxSq) { maxSq = d; index = i; } } if (maxSq > tolSq) { keep[index] = 1; stack.push([first, index], [index, last]); } } return points.filter((_, i) => keep[i]); } function outerRings(geometry) { if (!geometry) return []; if (geometry.type === 'Polygon') return geometry.coordinates.slice(0, 1); if (geometry.type === 'MultiPolygon') return geometry.coordinates.map((poly) => poly[0]); return []; } /** A ring across the antimeridian, lifted into one continuous longitude range (as build-country-shapes.mjs does). */ function unwrap(ring) { let min = Infinity; let max = -Infinity; for (const [lng] of ring) { if (lng < min) min = lng; if (lng > max) max = lng; } if (max - min <= 180) return ring; return ring.map(([lng, lat]) => [lng < 0 ? lng + 360 : lng, lat]); } const round = (n) => Math.round(n * 100) / 100; function build(feature) { const rings = outerRings(feature.geometry) .map(unwrap) .map((ring) => ring.map(project)) .map((ring) => ({ ring, area: ringArea(ring) })) .sort((a, b) => b.area - a.area); if (!rings.length) return null; const biggest = rings[0].area; // The mainland always, however small the country; every other ring above the speck size. const kept = rings .filter((r, i) => i === 0 || r.area >= Math.min(MIN_RING_AREA, biggest)) .slice(0, MAX_RINGS) .map((r) => r.ring); let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; for (const ring of kept) { for (const [x, y] of ring) { if (x < minX) minX = x; if (x > maxX) maxX = x; if (y < minY) minY = y; if (y > maxY) maxY = y; } } const spanX = maxX - minX; const spanY = maxY - minY; if (!(spanX > 0) || !(spanY > 0)) return null; const scale = 100 / Math.max(spanX, spanY); const normalised = kept.map((ring) => ring.map(([x, y]) => [(x - minX) * scale, (y - minY) * scale])); let tolerance = 0.012; let simplified = normalised.map((r) => simplify(r, tolerance)); let guard = 0; while (simplified.reduce((n, r) => n + r.length, 0) > MAX_POINTS && guard++ < 60) { tolerance *= 1.25; simplified = normalised.map((r) => simplify(r, tolerance)); } const d = simplified .map((ring) => { // Two decimals can fold neighbours onto one point; a ring left with fewer than three is not a shape. const pts = ring.map(([x, y]) => `${round(x)} ${round(y)}`).filter((p, i, all) => i === 0 || p !== all[i - 1]); return pts.length >= 3 ? `M${pts.join('L')}Z` : ''; }) .join(''); if (!d) return null; return { d, w: Math.round(spanX * scale * 10) / 10, h: Math.round(spanY * scale * 10) / 10, b: [minX, minY, maxX, maxY].map((v) => Math.round(v * 100) / 100), }; } const collection = JSON.parse(zlib.gunzipSync(fs.readFileSync(SRC)).toString('utf8')); const shapes = new Map(); for (const feature of collection.features) { const code = String(feature.properties?.ISO_A2 || '').toUpperCase(); if (!/^[A-Z]{2}$/.test(code)) continue; const built = build(feature); if (!built) continue; // Two features for one code: the one with more outline is the country rather than a dependency. const prev = shapes.get(code); if (!prev || built.d.length > prev.d.length) shapes.set(code, built); } fs.rmSync(OUT, { recursive: true, force: true }); fs.mkdirSync(OUT, { recursive: true }); let bytes = 0; for (const code of [...shapes.keys()].sort()) { const body = `${JSON.stringify(shapes.get(code))}\n`; bytes += Buffer.byteLength(body); fs.writeFileSync(path.join(OUT, `${code}.json`), body, 'utf8'); } console.log( `[country-detail] ${shapes.size} countries, ${Math.round(bytes / 1024)} kB → ${path.relative(process.cwd(), OUT)}` );