build(atlas): build the globe geometry from the bundled boundaries

scripts/build-atlas-mesh.mjs turns the admin-0 and admin-1 GeoJSON the
server already ships into TopoJSON at three levels of detail per world and
two per country's regions, smoothed, quantized and Brotli-packed under
content-hashed names, plus a manifest with every country's anchor, box and
region index. It runs at build time (npm run build, npm run dev when the
sources changed, and the Docker server stage); the output is not committed.

/api/addons/atlas/mesh serves the manifest and the files as they are
(immutable, a year), decompressing as a stream for a client without br.
This commit is contained in:
Maurice
2026-11-28 22:34:40 +01:00
parent 5989ba5f1f
commit 8510d4a729
7 changed files with 525 additions and 2 deletions
+338
View File
@@ -0,0 +1,338 @@
#!/usr/bin/env node
/**
* Builds the Atlas globe geometry from the committed boundary files.
*
* Input: server/assets/atlas/admin0.geojson.gz and admin1/<A2>.geojson.gz
* Output: server/assets/atlas-mesh/manifest.json, world-<lod>.<hash>.json.br,
* regions/<A2>-<lod>.<hash>.json.br
*
* Runs in the Docker build (server-builder stage), from `npm run build` and from
* `npm run dev`. With --if-stale it does nothing when the inputs and this script
* are unchanged since the last run (a hash in atlas-mesh/.source-hash); the
* output is not committed.
*
* Every level of detail is a TopoJSON topology simplified on its shared arcs, so
* neighbours keep identical borders and no slivers open between them. Small
* detached islands are dropped from the coarse levels. The browser decodes,
* triangulates and tessellates in a worker. Reads local files only, so the
* output is deterministic and the file names carry a content hash.
*/
import { createHash } from 'node:crypto';
import { readFileSync, writeFileSync, mkdirSync, readdirSync, rmSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { gunzipSync, brotliCompressSync, constants as zc } from 'node:zlib';
import polylabel from 'polylabel';
import { quantize } from 'topojson-client';
import { topology } from 'topojson-server';
import { presimplify, simplify, quantile, filter, filterAttachedWeight, planarRingArea } from 'topojson-simplify';
const HERE = dirname(fileURLToPath(import.meta.url));
const SRC = join(HERE, '..', 'assets', 'atlas');
const OUT = join(HERE, '..', 'assets', 'atlas-mesh');
/**
* keep: share of points kept (topojson-simplify quantile).
* island: detached rings below this planar area (square degrees) are dropped.
* q: quantization grid of the output.
*/
// keep is measured after smoothing, which quadruples the points of every arc.
const WORLD_LODS = [
{ id: 'l0', keep: 0.003, island: 0.05, q: 1e4 },
{ id: 'l1', keep: 0.0125, island: 0.004, q: 3e4 },
{ id: 'l2', keep: 0.055, island: 0, q: 1e5 },
];
const REGION_LODS = [
{ id: 'r0', keep: 0.015, island: 0.002, q: 1e4 },
{ id: 'r1', keep: 0.07, island: 0, q: 4e4 },
];
// Regions that can be marked but are not part of the "x of n" total.
const COUNT_EXCLUDE = { US: ['US-DC', 'US-PR', 'US-AS', 'US-GU', 'US-MP', 'US-VI', 'US-UM'] };
const readGz = (p) => JSON.parse(gunzipSync(readFileSync(p)).toString('utf8'));
function polygonsOf(geom) {
if (!geom) return [];
if (geom.type === 'Polygon') return [geom.coordinates];
if (geom.type === 'MultiPolygon') return geom.coordinates;
return [];
}
function ringArea(r) {
let a = 0;
for (let i = 0, n = r.length - 1; i < n; i++) a += r[i][0] * r[i + 1][1] - r[i + 1][0] * r[i][1];
return Math.abs(a / 2);
}
/** Planar centroid of a ring in a space where longitude is scaled by kx. */
function ringCentroid(ring, kx) {
let a = 0;
let cx = 0;
let cy = 0;
for (let i = 0, n = ring.length - 1; i < n; i++) {
const x0 = ring[i][0] * kx,
y0 = ring[i][1];
const x1 = ring[i + 1][0] * kx,
y1 = ring[i + 1][1];
const f = x0 * y1 - x1 * y0;
a += f;
cx += (x0 + x1) * f;
cy += (y0 + y1) * f;
}
if (Math.abs(a) < 1e-12) return null;
return [cx / (3 * a) / kx, cy / (3 * a)];
}
function pointInPolygon(pt, poly) {
let inside = false;
for (const ring of poly) {
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
const [xi, yi] = ring[i];
const [xj, yj] = ring[j];
if (yi > pt[1] !== yj > pt[1] && pt[0] < ((xj - xi) * (pt[1] - yi)) / (yj - yi) + xi) inside = !inside;
}
}
return inside;
}
/**
* Label anchor: the visual centre of the largest polygon, measured with
* longitude shrunk by the cosine of its latitude as on screen. The centroid where
* it falls inside the shape (most countries), else the pole of inaccessibility
* in the same space (crescents such as Croatia or Chile).
*/
function anchorOf(f) {
let best = null;
let bestA = -1;
for (const poly of polygonsOf(f.geometry)) {
const a = ringArea(poly[0]);
if (a > bestA) {
bestA = a;
best = poly;
}
}
if (!best) return null;
let lat0 = 0;
for (const p of best[0]) lat0 += p[1];
lat0 /= best[0].length;
const kx = Math.max(0.2, Math.cos((lat0 * Math.PI) / 180));
const c = ringCentroid(best[0], kx);
if (c && pointInPolygon(c, best)) return [round3(c[0]), round3(c[1])];
const scaled = best.map((ring) => ring.map(([x, y]) => [x * kx, y]));
const p = polylabel(scaled, 0.02);
return [round3(p[0] / kx), round3(p[1])];
}
const round3 = (v) => Math.round(v * 1000) / 1000;
const round2 = (v) => Math.round(v * 100) / 100;
function totalArea(f) {
let a = 0;
for (const poly of polygonsOf(f.geometry)) a += ringArea(poly[0]);
return a;
}
function bboxOf(features) {
let w = 180;
let s = 90;
let e = -180;
let n = -90;
for (const f of features)
for (const poly of polygonsOf(f.geometry))
for (const p of poly[0] ?? []) {
if (p[0] < w) w = p[0];
if (p[0] > e) e = p[0];
if (p[1] < s) s = p[1];
if (p[1] > n) n = p[1];
}
return [w, s, e, n];
}
/**
* Snaps a ring onto a grid of `step` degrees and drops repeated points. Borders
* that nearly coincide in the source then share their vertices, so the topology
* finds them as one arc instead of thousands of two-point pieces.
*/
function snapRing(ring, step) {
const out = [];
for (const [x, y] of ring) {
const p = [Math.round(x / step) * step, Math.round(y / step) * step];
const last = out[out.length - 1];
if (!last || last[0] !== p[0] || last[1] !== p[1]) out.push(p);
}
if (out.length > 1) {
const a = out[0],
b = out[out.length - 1];
if (a[0] !== b[0] || a[1] !== b[1]) out.push([a[0], a[1]]);
}
return out.length >= 4 ? out : null;
}
/** Keeps only the snapped geometry and a numeric id, so the topology carries no names. */
function slim(features, step) {
return features.map((f, i) => {
const polys = [];
for (const poly of polygonsOf(f.geometry)) {
const outer = snapRing(poly[0], step);
if (!outer) continue;
polys.push([
outer,
...poly
.slice(1)
.map((r) => snapRing(r, step))
.filter(Boolean),
]);
}
return { type: 'Feature', id: i, properties: null, geometry: { type: 'MultiPolygon', coordinates: polys } };
});
}
/**
* Two rounds of Chaikin corner cutting on one arc, ends kept. The sources sit on
* a 0.01 degree grid, which shows as stair steps when zoomed in; smoothing the
* shared arcs (not the rings) keeps neighbours on one identical border.
*/
function smoothArc(arc) {
let pts = arc;
for (let round = 0; round < 2; round++) {
if (pts.length < 3) return pts;
const out = [pts[0]];
for (let i = 0; i < pts.length - 1; i++) {
const [x0, y0] = pts[i];
const [x1, y1] = pts[i + 1];
out.push([x0 * 0.75 + x1 * 0.25, y0 * 0.75 + y1 * 0.25], [x0 * 0.25 + x1 * 0.75, y0 * 0.25 + y1 * 0.75]);
}
out.push(pts[pts.length - 1]);
pts = out;
}
return pts;
}
function buildTopo(features, name, lod) {
const step = Math.max(0.01, 360 / lod.q);
const topo = topology({ [name]: { type: 'FeatureCollection', features: slim(features, step) } });
topo.arcs = topo.arcs.map(smoothArc);
const pre = presimplify(topo);
let simp = simplify(pre, quantile(pre, lod.keep));
if (lod.island > 0) simp = filter(simp, filterAttachedWeight(simp, lod.island, planarRingArea));
for (const arc of simp.arcs) for (const p of arc) p.length = 2;
const q = quantize(simp, lod.q);
delete q.bbox;
return Buffer.from(JSON.stringify(q));
}
function write(rel, buf, files) {
const h = createHash('sha256').update(buf).digest('hex').slice(0, 12);
const name = rel.replace(/\.json$/, `.${h}.json`);
mkdirSync(dirname(join(OUT, name)), { recursive: true });
const br = brotliCompressSync(buf, { params: { [zc.BROTLI_PARAM_QUALITY]: 11 } });
writeFileSync(join(OUT, name + '.br'), br);
files[rel] = name;
return { name, raw: buf.length, br: br.length };
}
// ---------------------------------------------------------------- main
/** Hash of everything the output depends on: the boundary files and this script. */
function sourceHash() {
const h = createHash('sha256');
h.update(readFileSync(fileURLToPath(import.meta.url)));
h.update(readFileSync(join(SRC, 'admin0.geojson.gz')));
for (const name of readdirSync(join(SRC, 'admin1')).sort())
h.update(name).update(readFileSync(join(SRC, 'admin1', name)));
return h.digest('hex');
}
const SOURCE = sourceHash();
const STAMP = join(OUT, '.source-hash');
if (process.argv.includes('--if-stale')) {
let have = '';
try {
have = readFileSync(STAMP, 'utf8').trim();
} catch {
have = '';
}
if (have === SOURCE) {
console.log('[atlas-mesh] up to date');
process.exit(0);
}
}
rmSync(OUT, { recursive: true, force: true });
mkdirSync(OUT, { recursive: true });
const files = {};
const admin0 = readGz(join(SRC, 'admin0.geojson.gz')).features;
const countries = admin0.map((f) => ({
a2: f.properties.ISO_A2 ?? null,
a3: f.properties.ADM0_A3,
name: f.properties.NAME,
anchor: anchorOf(f),
bbox: bboxOf([f]).map(round2),
area: Math.round(totalArea(f) * 10) / 10,
}));
for (const lod of WORLD_LODS) {
const r = write(`world-${lod.id}.json`, buildTopo(admin0, 'countries', lod), files);
console.log(`world ${lod.id}: ${r.raw} B raw, ${r.br} B br`);
}
const regions = {};
let regionBytes = 0;
for (const file of readdirSync(join(SRC, 'admin1')).filter((n) => n.endsWith('.geojson.gz'))) {
const a2 = file.slice(0, 2);
const feats = readGz(join(SRC, 'admin1', file)).features;
if (!feats.length) continue;
const exclude = new Set(COUNT_EXCLUDE[a2] ?? []);
const entry = {
bbox: bboxOf(feats).map(round2),
counted: feats.filter((f) => !exclude.has(f.properties.iso_3166_2)).length,
features: feats.map((f) => ({
code: f.properties.iso_3166_2 ?? null,
name: f.properties.name ?? null,
nameEn: f.properties.name_en ?? null,
anchor: anchorOf(f),
counted: !exclude.has(f.properties.iso_3166_2),
})),
files: {},
};
for (const lod of REGION_LODS) {
const r = write(`regions/${a2}-${lod.id}.json`, buildTopo(feats, 'regions', lod), files);
entry.files[lod.id] = r.name;
regionBytes += r.br;
}
regions[a2] = entry;
}
// The world manifest stays small; each country's region index ships as its own file.
const regionIndex = {};
for (const [a2, entry] of Object.entries(regions)) {
const r = write(`regions/${a2}-index.json`, Buffer.from(JSON.stringify(entry)), files);
regionIndex[a2] = { bbox: entry.bbox, counted: entry.counted, total: entry.features.length, index: r.name };
}
// One small file to search every region by name without loading 198 indexes.
const searchRows = [];
for (const [a2, entry] of Object.entries(regions)) {
for (const f of entry.features) {
if (!f.anchor) continue;
searchRows.push([a2, f.code, f.name, f.nameEn && f.nameEn !== f.name ? f.nameEn : null, f.anchor[0], f.anchor[1]]);
}
}
const search = write('regions/search.json', Buffer.from(JSON.stringify(searchRows)), files);
console.log(`region search ${search.raw} B raw, ${search.br} B br`);
const manifest = {
version: 1,
lods: WORLD_LODS.map((l) => l.id),
regionLods: REGION_LODS.map((l) => l.id),
world: Object.fromEntries(WORLD_LODS.map((l) => [l.id, files[`world-${l.id}.json`]])),
countries,
regions: regionIndex,
regionSearch: search.name,
attribution: ['geoBoundaries (CC BY 4.0)', 'CGAZ / LSIB', 'Tailte Éireann (CC BY 4.0)'],
};
const mjson = Buffer.from(JSON.stringify(manifest));
writeFileSync(join(OUT, 'manifest.json'), mjson);
const mbr = brotliCompressSync(mjson).length;
console.log(
`manifest ${mjson.length} B raw, ${mbr} B br; regions ${regionBytes} B br over ${Object.keys(regions).length} countries`,
);
writeFileSync(STAMP, SOURCE);