use border tiles to cut patchwork precisely

This commit is contained in:
vcoppe committed 2026-11-29 15:06:35 +01:00
1 parent 657cf8786c
commit 4d4804203f
10 files changed
+282 -273

No files matched your search

@@ -1,7 +1,25 @@
// Which imagery each tile of the open satellite basemap is made of.
// Which imagery each tile of the open satellite basemap is made of, from saved tiles of the
// tileset of the countries.
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { describe, it } from 'node:test';
import { planTile } from './open-satellite';
import { planTile, type CountryTiles } from './open-satellite';
const fixtures = new URL('../../../test/fixtures/satellite-countries/', import.meta.url);
/** The saved tiles, none where there is no file, and the ones that were asked for. */
function savedTiles() {
const asked: string[] = [];
const tiles: CountryTiles = async (z, x, y) => {
asked.push(`${z}/${x}/${y}`);
try {
return new Uint8Array(readFileSync(new URL(`${z}-${x}-${y}.mvt`, fixtures))).buffer;
} catch {
return null;
}
};
return { asked, tiles };
}
function tile(lon: number, lat: number, z: number): [number, number, number] {
const n = 2 ** z;
@@ -13,46 +31,68 @@ function tile(lon: number, lat: number, z: number): [number, number, number] {
];
}
async function plan(lon: number, lat: number, z: number) {
const { parts, fallback } = await planTile(...tile(lon, lat, z));
return { parts: parts.map((p) => `${p.source.id}:${p.relation}`), fallback };
async function plan([z, x, y]: [number, number, number], tiles: CountryTiles) {
const { parts, fallback } = await planTile(z, x, y, tiles);
return { parts: parts.map((p) => `${p.source.id}:${p.relation}`).sort(), fallback };
}
describe('planTile', () => {
it('takes a tile inside a country from its agency alone', async () => {
assert.deepEqual(await plan(2.35, 48.85, 15), { parts: ['fr:full'], fallback: false });
assert.deepEqual(await plan(6.63, 46.52, 15), { parts: ['ch:full'], fallback: false });
assert.deepEqual(await plan(4.35, 50.85, 16), { parts: ['be:full'], fallback: false });
assert.deepEqual(await plan(21.01, 52.23, 16), { parts: ['pl:full'], fallback: false });
});
it('takes every tile up to zoom 12 from the imagery of the whole world', async () => {
assert.deepEqual(await plan(2.35, 48.85, 12), { parts: [], fallback: true });
assert.deepEqual(await plan(7.589, 47.5895, 12), { parts: [], fallback: true });
const { asked, tiles } = savedTiles();
assert.deepEqual(await plan(tile(2.35, 48.85, 12), tiles), { parts: [], fallback: true });
assert.deepEqual(asked, []);
});
it('takes a tile outside every country from the fallback', async () => {
assert.deepEqual(await plan(-0.12, 51.5, 14), { parts: [], fallback: true });
// Germany, which is not in the patchwork
assert.deepEqual(await plan(9.73, 52.37, 14), { parts: [], fallback: true });
assert.deepEqual(await plan(-30, 40, 13), { parts: [], fallback: true });
it('takes a tile far from every country from the fallback, without asking for countries', async () => {
const { asked, tiles } = savedTiles();
// London, and the Atlantic
assert.deepEqual(await plan(tile(-0.12, 51.5, 14), tiles), { parts: [], fallback: true });
assert.deepEqual(await plan(tile(-30, 40, 13), tiles), { parts: [], fallback: true });
assert.deepEqual(asked, []);
});
it('puts the countries of a border tile together, over the fallback where none is', async () => {
// Menton: France and Italy, which is not in the patchwork
assert.deepEqual(await plan(7.5, 43.78, 13), {
parts: ['fr:partial'],
fallback: true,
});
// Basel: Switzerland, France and Germany
assert.deepEqual(await plan(7.589, 47.5895, 14), {
parts: ['ch:partial', 'fr:partial'],
fallback: true,
});
// Somport: France and Spain, between them the whole tile
assert.deepEqual(await plan(-0.52, 42.8, 13), {
parts: ['fr:partial', 'es:partial'],
it('takes a tile inside a country from its agency alone', async () => {
const { tiles } = savedTiles();
assert.deepEqual(await plan(tile(2.35, 48.85, 15), tiles), {
parts: ['FR:full'],
fallback: false,
});
});
it('puts the countries of a border tile together, over the fallback where none is', async () => {
const { tiles } = savedTiles();
// Basel: France, Switzerland and Germany, which is not in the patchwork
assert.deepEqual(await plan([13, 4268, 2861], tiles), {
parts: ['CH:partial', 'FR:partial'],
fallback: true,
});
// only Germany
assert.deepEqual(await plan([13, 4269, 2860], tiles), { parts: [], fallback: true });
});
it('needs no fallback where the countries cover the tile between them', async () => {
const { tiles } = savedTiles();
// Wattrelos: France and Belgium
assert.deepEqual(await plan([13, 4166, 2750], tiles), {
parts: ['BE:partial', 'FR:partial'],
fallback: false,
});
// Baarle, with its enclaves of Belgium and the Netherlands
assert.deepEqual(await plan([13, 4208, 2726], tiles), {
parts: ['BE:partial', 'NL:partial'],
fallback: false,
});
});
it('asks for a tile of the countries once for all the tiles of imagery inside it', async () => {
const { asked, tiles } = savedTiles();
// around Lausanne, which no other test asks for
const [, x, y] = tile(6.63, 46.52, 12);
for (let dx = 0; dx < 4; dx++) {
for (let dy = 0; dy < 4; dy++) {
await planTile(14, x * 4 + dx, y * 4 + dy, tiles);
}
}
assert.deepEqual(asked, [`12/${x}/${y}`]);
});
});
+180 -199
View File
@@ -1,4 +1,6 @@
import * as maplibregl from 'maplibre-gl';
import { VectorTile } from '@mapbox/vector-tile';
import { PbfReader } from 'pbf';
/**
* A satellite basemap made of the open imagery of national mapping agencies, drawn through a
@@ -12,7 +14,7 @@ export const OPEN_SATELLITE_PROTOCOL = 'opensat';
type TileUrl = (z: number, x: number, y: number) => string;
type ImagerySource = {
/** Key of the coverage in satellite-coverage.json */
/** ISO code of the country, in the tileset of the countries */
id: string;
url: TileUrl;
/** Above it, the tile of this zoom level is scaled up. */
@@ -37,61 +39,61 @@ const world: ImagerySource = { id: 'world', url: ignOrthophotos, maxzoom: 12 };
/** In order of priority, the first one covering a point is used. */
const sources: ImagerySource[] = [
{
id: 'ch',
id: 'CH',
url: xyz(
'https://wmts.geo.admin.ch/1.0.0/ch.swisstopo.swissimage/default/current/3857/{z}/{x}/{y}.jpeg'
),
maxzoom: 20,
},
{
id: 'fr',
id: 'FR',
url: ignOrthophotos,
maxzoom: 19,
},
{
id: 'es',
id: 'ES',
url: xyz(
'https://www.ign.es/wmts/pnoa-ma?layer=OI.OrthoimageCoverage&style=default&tilematrixset=GoogleMapsCompatible&Service=WMTS&Request=GetTile&Version=1.0.0&Format=image/jpeg&TileMatrix={z}&TileCol={x}&TileRow={y}'
),
maxzoom: 19,
},
{
id: 'at',
id: 'AT',
url: xyz(
'https://mapsneu.wien.gv.at/basemap/bmaporthofoto30cm/normal/google3857/{z}/{y}/{x}.jpeg'
),
maxzoom: 19,
},
{
id: 'nl',
id: 'NL',
url: xyz(
'https://service.pdok.nl/hwh/luchtfotorgb/wmts/v1_0/Actueel_orthoHR/EPSG:3857/{z}/{x}/{y}.jpeg'
),
maxzoom: 19,
},
{
id: 'lu',
id: 'LU',
url: xyz(
'https://wmts1.geoportail.lu/opendata/wmts/ortho_latest/GLOBAL_WEBMERCATOR_4_V3/{z}/{x}/{y}.jpeg'
),
maxzoom: 19,
},
{
id: 'cz',
id: 'CZ',
url: xyz(
'https://ags.cuzk.gov.cz/arcgis1/rest/services/ORTOFOTO_WM/MapServer/tile/{z}/{y}/{x}'
),
maxzoom: 19,
},
{
id: 'be',
id: 'BE',
url: xyz(
'https://wmts.ngi.be/inspire/ortho/1.0.0/orthoimage_coverage/default/3857/latest/{z}/{y}/{x}.png'
),
maxzoom: 19,
},
{
id: 'pl',
id: 'PL',
url: xyz(
'https://mapy.geoportal.gov.pl/wss/service/PZGIK/ORTO/WMTS/StandardResolution?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=ORTOFOTOMAPA&STYLE=default&FORMAT=image/jpeg&TILEMATRIXSET=EPSG:3857&TILEMATRIX=EPSG:3857:{z}&TILEROW={y}&TILECOL={x}'
),
@@ -112,157 +114,135 @@ export const openSatelliteAttribution = [
'<a href="https://www.maptiler.com/copyright/" target="_blank">© MapTiler</a>',
].join(', ');
// Geometry, in Web Mercator coordinates between 0 and 1
// Countries, from the tileset of their polygons, built from the borders of OpenStreetMap
type Ring = Float64Array; // x0, y0, x1, y1, ...
type Polygon = { rings: Ring[]; bbox: [number, number, number, number] };
type Coverage = { polygons: Polygon[]; bbox: [number, number, number, number] };
type Rect = [number, number, number, number]; // minX, minY, maxX, maxY
const COUNTRIES_URL = xyz('https://tiles.gpx.studio/satellite-countries/{z}/{x}/{y}.mvt');
/** The only zoom level of the tileset. */
const COUNTRIES_ZOOM = 12;
function mercatorX(lon: number) {
return (lon + 180) / 360;
}
const sourceByCountry = new Map(sources.map((source) => [source.id, source]));
function mercatorY(lat: number) {
const sin = Math.sin((Math.max(-85.0511, Math.min(85.0511, lat)) * Math.PI) / 180);
return 0.5 - Math.log((1 + sin) / (1 - sin)) / (4 * Math.PI);
}
/** The tiles of the countries, from their tileset: null where there is none. */
export type CountryTiles = (z: number, x: number, y: number) => Promise<ArrayBuffer | null>;
function emptyBBox(): [number, number, number, number] {
return [Infinity, Infinity, -Infinity, -Infinity];
}
function extend(bbox: [number, number, number, number], other: Rect) {
bbox[0] = Math.min(bbox[0], other[0]);
bbox[1] = Math.min(bbox[1], other[1]);
bbox[2] = Math.max(bbox[2], other[2]);
bbox[3] = Math.max(bbox[3], other[3]);
}
function intersects(a: Rect, b: Rect) {
return a[0] <= b[2] && b[0] <= a[2] && a[1] <= b[3] && b[1] <= a[3];
}
function projectCoverage(polygons: number[][][][]): Coverage {
const coverage: Coverage = { polygons: [], bbox: emptyBBox() };
for (const polygon of polygons) {
const projected: Polygon = { rings: [], bbox: emptyBBox() };
for (const ring of polygon) {
const array = new Float64Array(ring.length * 2);
ring.forEach(([lon, lat], i) => {
array[2 * i] = mercatorX(lon);
array[2 * i + 1] = mercatorY(lat);
extend(projected.bbox, [
array[2 * i],
array[2 * i + 1],
array[2 * i],
array[2 * i + 1],
]);
});
projected.rings.push(array);
}
coverage.polygons.push(projected);
extend(coverage.bbox, projected.bbox);
async function fetchCountryTile(z: number, x: number, y: number): Promise<ArrayBuffer | null> {
try {
const response = await fetch(COUNTRIES_URL(z, x, y));
if (!response.ok) return null;
const bytes = await response.arrayBuffer();
return bytes.byteLength > 0 ? bytes : null;
} catch {
return null;
}
return coverage;
}
function pointInPolygon(x: number, y: number, polygon: Polygon) {
let inside = false;
for (const ring of polygon.rings) {
for (let i = 0, j = ring.length - 2; i < ring.length; j = i, i += 2) {
const xi = ring[i],
yi = ring[i + 1],
xj = ring[j],
yj = ring[j + 1];
if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) {
inside = !inside;
}
}
/** A tile of the countries is shared by the 4^(z - 12) tiles of imagery inside it. */
const countryTiles = new Map<string, Promise<ArrayBuffer | null>>();
function getCountryTile(x: number, y: number, tiles: CountryTiles) {
const key = `${x}/${y}`;
let tile = countryTiles.get(key);
if (tile) {
// the last used, at the end of the map
countryTiles.delete(key);
} else {
tile = tiles(COUNTRIES_ZOOM, x, y);
if (countryTiles.size >= 256) countryTiles.delete(countryTiles.keys().next().value!);
}
return inside;
countryTiles.set(key, tile);
return tile;
}
/** Whether the segment touches the rectangle (Liang–Barsky). */
function segmentIntersectsRect(
x0: number,
y0: number,
x1: number,
y1: number,
[minX, minY, maxX, maxY]: Rect
) {
let t0 = 0,
t1 = 1;
const dx = x1 - x0,
dy = y1 - y0;
const p = [-dx, dx, -dy, dy];
const q = [x0 - minX, maxX - x0, y0 - minY, maxY - y0];
for (let i = 0; i < 4; i++) {
if (p[i] === 0) {
if (q[i] < 0) return false;
} else {
const t = q[i] / p[i];
if (p[i] < 0) {
if (t > t1) return false;
t0 = Math.max(t0, t);
} else {
if (t < t0) return false;
t1 = Math.min(t1, t);
}
}
}
return true;
/** The tiles of zoom `zoom` where there is a country, as y * 2^zoom + x. */
let areas: Promise<{ zoom: number; tiles: Set<number> }> | null = null;
function getAreas() {
areas ??= import('$lib/data/satellite-countries.json').then((module) => ({
zoom: module.default.zoom,
tiles: new Set(module.default.tiles),
}));
return areas;
}
type CoverageRelation = { relation: 'full' | 'partial' | 'none'; polygons: Polygon[] };
function relate(coverage: Coverage, rect: Rect): CoverageRelation {
if (!intersects(coverage.bbox, rect)) return { relation: 'none', polygons: [] };
const touching: Polygon[] = [];
let crossed = false;
for (const polygon of coverage.polygons) {
if (!intersects(polygon.bbox, rect)) continue;
let polygonCrossed = false;
for (const ring of polygon.rings) {
for (let i = 2; i < ring.length && !polygonCrossed; i += 2) {
if (segmentIntersectsRect(ring[i - 2], ring[i - 1], ring[i], ring[i + 1], rect)) {
polygonCrossed = true;
}
}
if (polygonCrossed) break;
}
if (polygonCrossed) {
crossed = true;
touching.push(polygon);
} else if (pointInPolygon((rect[0] + rect[2]) / 2, (rect[1] + rect[3]) / 2, polygon)) {
// No border inside the tile, and its center is inside: the whole tile is
return { relation: 'full', polygons: [polygon] };
}
}
return crossed
? { relation: 'partial', polygons: touching }
: { relation: 'none', polygons: [] };
}
// Coverage, loaded with the first tile
let coverages: Promise<Map<string, Coverage>> | null = null;
function getCoverages() {
coverages ??= import('$lib/data/satellite-coverage.json').then((module) => {
const data = module.default as unknown as Record<string, number[][][][]>;
const result = new Map<string, Coverage>();
for (const source of sources) {
result.set(source.id, projectCoverage(data[source.id] ?? []));
}
return result;
});
return coverages;
}
// Tiles
// Geometry, in pixels of the tile of imagery
const TILE_SIZE = 256;
const TILE_AREA = TILE_SIZE * TILE_SIZE;
type Ring = [number, number][];
/** The ring cut to the tile (Sutherland–Hodgman), which keeps its orientation. */
function clipRing(ring: Ring): Ring {
let points = ring;
const edges: [(p: [number, number]) => number, number][] = [
[(p) => p[0], 0],
[(p) => -p[0], -TILE_SIZE],
[(p) => p[1], 0],
[(p) => -p[1], -TILE_SIZE],
];
for (const [value, min] of edges) {
if (points.length === 0) break;
const clipped: Ring = [];
for (let i = 0; i < points.length; i++) {
const current = points[i];
const previous = points[(i + points.length - 1) % points.length];
const inCurrent = value(current) >= min;
const inPrevious = value(previous) >= min;
if (inCurrent !== inPrevious) {
const t = (min - value(previous)) / (value(current) - value(previous));
clipped.push([
previous[0] + t * (current[0] - previous[0]),
previous[1] + t * (current[1] - previous[1]),
]);
}
if (inCurrent) clipped.push(current);
}
points = clipped;
}
return points;
}
/** Positive for an outer ring of a vector tile, negative for a hole. */
function signedArea(ring: Ring) {
let area = 0;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
area += ring[j][0] * ring[i][1] - ring[i][0] * ring[j][1];
}
return area / 2;
}
/** The polygons of the countries with imagery in the tile, cut to it, with their area. */
function countriesInTile(
bytes: ArrayBuffer,
z: number,
x: number,
y: number
): { source: ImagerySource; rings: Ring[]; area: number }[] {
const layer = new VectorTile(new PbfReader(bytes)).layers.countries;
if (!layer) return [];
const d = z - COUNTRIES_ZOOM;
const scale = (TILE_SIZE * 2 ** d) / layer.extent;
const offsetX = (x - ((x >> d) << d)) * TILE_SIZE;
const offsetY = (y - ((y >> d) << d)) * TILE_SIZE;
const countries = [];
for (let i = 0; i < layer.length; i++) {
const feature = layer.feature(i);
const source = sourceByCountry.get(String(feature.properties.country));
if (!source) continue;
const rings = feature
.loadGeometry()
.map((ring) =>
clipRing(ring.map((p) => [p.x * scale - offsetX, p.y * scale - offsetY]))
)
.filter((ring) => ring.length >= 3);
const area = rings.reduce((sum, ring) => sum + signedArea(ring), 0);
// less than a pixel: a polygon of the tile of the countries outside this one
if (area >= 1) countries.push({ source, rings, area });
}
return countries;
}
// Imagery
async function fetchBytes(url: string, signal: AbortSignal): Promise<ArrayBuffer | null> {
try {
@@ -270,13 +250,39 @@ async function fetchBytes(url: string, signal: AbortSignal): Promise<ArrayBuffer
if (!response.ok) return null;
const contentType = response.headers.get('content-type') ?? '';
if (!contentType.startsWith('image/')) return null;
return await response.arrayBuffer();
const bytes = await response.arrayBuffer();
return (await isBlank(bytes)) ? null : bytes;
} catch (e) {
if (signal.aborted) throw e;
return null;
}
}
/**
* Whether the image is all white or transparent: what some agencies give where they have no
* imagery, such as IGN on the French part of Lake Geneva. Such an image is small, the others
* are not even decoded.
*/
async function isBlank(bytes: ArrayBuffer) {
if (bytes.byteLength > 4096) return false;
try {
const image = await createImageBitmap(new Blob([bytes]));
const canvas = new OffscreenCanvas(16, 16);
const context = canvas.getContext('2d')!;
context.drawImage(image, 0, 0, 16, 16);
image.close();
const pixels = context.getImageData(0, 0, 16, 16).data;
for (let i = 0; i < pixels.length; i += 4) {
const transparent = pixels[i + 3] < 8;
const white = pixels[i] >= 250 && pixels[i + 1] >= 250 && pixels[i + 2] >= 250;
if (!transparent && !white) return false;
}
return true;
} catch {
return false;
}
}
/** The image of the tile, or of the part of its ancestor at the max zoom of the source. */
async function fetchImage(
url: TileUrl,
@@ -303,47 +309,16 @@ async function fetchImage(
}
}
function clipTo(
context: OffscreenCanvasRenderingContext2D,
polygons: Polygon[],
z: number,
x: number,
y: number
) {
const scale = 2 ** z * TILE_SIZE;
function clipTo(context: OffscreenCanvasRenderingContext2D, rings: Ring[]) {
context.beginPath();
for (const polygon of polygons) {
for (const ring of polygon.rings) {
for (let i = 0; i < ring.length; i += 2) {
const px = ring[i] * scale - x * TILE_SIZE;
const py = ring[i + 1] * scale - y * TILE_SIZE;
if (i === 0) context.moveTo(px, py);
else context.lineTo(px, py);
}
context.closePath();
}
for (const ring of rings) {
ring.forEach(([px, py], i) => (i === 0 ? context.moveTo(px, py) : context.lineTo(px, py)));
context.closePath();
}
context.clip('evenodd');
}
/** Whether every point of a grid over the tile is in one of the partial coverages. */
function coveredBy(partials: CoverageRelation[], rect: Rect) {
const steps = 6;
for (let i = 0; i < steps; i++) {
for (let j = 0; j < steps; j++) {
const px = rect[0] + ((i + 0.5) / steps) * (rect[2] - rect[0]);
const py = rect[1] + ((j + 0.5) / steps) * (rect[3] - rect[1]);
if (
!partials.some((p) => p.polygons.some((polygon) => pointInPolygon(px, py, polygon)))
) {
return false;
}
}
}
return true;
}
type TilePart = CoverageRelation & { source: ImagerySource };
type TilePart = { source: ImagerySource; relation: 'full' | 'partial'; rings: Ring[] };
/**
* The sources of the tile, in drawing order: the one covering the whole tile, or those
@@ -352,22 +327,28 @@ type TilePart = CoverageRelation & { source: ImagerySource };
export async function planTile(
z: number,
x: number,
y: number
y: number,
tiles: CountryTiles = fetchCountryTile
): Promise<{ parts: TilePart[]; fallback: boolean }> {
if (z <= world.maxzoom) return { parts: [], fallback: true };
const n = 2 ** z;
const rect: Rect = [x / n, y / n, (x + 1) / n, (y + 1) / n];
const coverageBySource = await getCoverages();
const parts: TilePart[] = [];
for (const source of sources) {
const relation = relate(coverageBySource.get(source.id)!, rect);
if (relation.relation === 'full') {
return { parts: [{ ...relation, source }], fallback: false };
} else if (relation.relation === 'partial') {
parts.push({ ...relation, source });
}
const none = { parts: [], fallback: true };
if (z <= world.maxzoom) return none;
const { zoom, tiles: withCountries } = await getAreas();
const d = z - zoom;
if (!withCountries.has((y >> d) * 2 ** zoom + (x >> d))) return none;
const bytes = await getCountryTile(x >> (z - COUNTRIES_ZOOM), y >> (z - COUNTRIES_ZOOM), tiles);
if (!bytes) return none;
const countries = countriesInTile(bytes, z, x, y);
// a pixel of margin, for the rounding of the coordinates of the tiles
const whole = countries.find((country) => country.area >= TILE_AREA - TILE_SIZE);
if (whole) {
return { parts: [{ source: whole.source, relation: 'full', rings: [] }], fallback: false };
}
return { parts, fallback: parts.length === 0 || !coveredBy(parts, rect) };
const covered = countries.reduce((sum, country) => sum + country.area, 0);
return {
parts: countries.map(({ source, rings }) => ({ source, relation: 'partial', rings })),
fallback: covered < TILE_AREA - TILE_SIZE,
};
}
export function maptilerSource(maptilerKey: string): ImagerySource {
@@ -421,7 +402,7 @@ export async function loadTile(
const result = images[i];
if (!result) return;
context.save();
if (p.relation === 'partial') clipTo(context, p.polygons, z, x, y);
if (p.relation === 'partial') clipTo(context, p.rings);
const { image, sx, sy, size } = result;
context.drawImage(image, sx, sy, size, size, 0, 0, TILE_SIZE, TILE_SIZE);
context.restore();