Draw vectorBase: a MapLibre style's vector tiles painted as imagery

src/render/vectorBase/ is a Cesium-free painter: loadVectorStyle loads
a style and its TileJSON sources and compiles its layers (skipping, with a
reason, what it does not draw), and paintVectorTile paints a Web Mercator
tile on a canvas: background, fill, line and circle layers with filters in
both syntaxes, legacy functions and a listed subset of expressions, and
symbol text labels placed clear of each other inside the tile. Sources are
decoded with pbf and @mapbox/vector-tile, already dependencies. The Cesium
port loads the style before changing the base, draws it as Web Mercator
imagery under the base's other imagery, credits its sources, and claims
vectorBase; the stub loads the style. globe.base.vector serves a style and
tile from data URLs and reads the drawn fill.
This commit is contained in:
Sameh Khamis committed 2026-11-11 18:24:49 -08:00
1 parent d9ad7da9d5
commit 5fae3cf485
17 files changed
+2032 -15

No files matched your search

+65
View File
@@ -282,6 +282,71 @@ and each capability member present without its capability.
`contract.test.mjs` type-checks the contract under strict TypeScript, and
fails when `PORTS` and the types disagree on a single member.
### The vector base painter
`vectorBase` (`BaseSpec.vector = { styleUrl }`) draws a MapLibre style
document's vector tiles as the globe's base. They are painted in shared,
Cesium-free code, `src/render/vectorBase/`, which the renderer draws as
draws imagery draws the same pixels:
- `loadVectorStyle(styleUrl, fetch)` fetches the style and the TileJSON its
vector sources name (a source's `url`; inline `tiles` are used as given,
resolved against the style), compiles every layer, and returns the
sources (tile templates, `minzoom`, `maxzoom`, `xyz` or `tms`), the layers
it draws, the background, the sources' attributions, and `skipped`: each
layer it does not draw, with why.
- `paintVectorTile(style, z, x, y, { size, fetch, signal, canvas })` paints
one Web Mercator tile on a canvas at style zoom `z + log2(size / 512)` (at
least 0). A source past its `maxzoom` is drawn from its deepest tile,
overzoomed; below its `minzoom` it draws nothing. Decoded source tiles
(gzipped ones inflated) are kept per style, the last 128.
What it draws of the style specification:
- Layers: `background` (`background-color`, `background-opacity`); `fill`
(`fill-color`, `fill-opacity`, `fill-outline-color`); `line`
(`line-color`, `line-width`, `line-opacity`, `line-dasharray`,
`line-cap`, `line-join`, and `line-gap-width` drawn as one line the full
cased width); `circle` (`circle-radius`, `circle-color`,
`circle-opacity`, `circle-stroke-width`, `circle-stroke-color`,
`circle-stroke-opacity`); `symbol` text only (`text-field` as an
expression or with `{name}` tokens, `text-size`, `text-font` as the
system's sans-serif or serif in bold or italic as its name says,
`text-color`, `text-opacity`, `text-halo-color`, `text-halo-width`,
`text-transform`, `text-anchor`, `text-offset`, `text-max-width`).
Layer `minzoom`, `maxzoom`, `filter` and `visibility` hold.
- Labels are painted into the tiles: top layer first, each clear of those
placed before it and wholly inside its tile (one across a tile edge is
left out). A point labels at itself, a line halfway along it (level, not
along the line), a polygon at its outer ring's bounding-box centre.
- Filters in both syntaxes (legacy, with `$type` and `$id`, and
expressions). Legacy `{stops, base, property, type}` functions
(exponential, interval, categorical, identity; not zoom-and-property).
- Expressions: `literal`, `get`, `has`, `id`, `geometry-type`, `zoom`,
`properties`, `!`, `all`, `any`, `==`, `!=`, `<`, `<=`, `>`, `>=`, `in`,
`case`, `match`, `coalesce`, `step`, `interpolate` (`linear` and
`exponential`; `-hcl` and `-lab` blend in RGB), `to-string`,
`to-number`, `to-boolean`, `to-color`, `number`, `string`, `boolean`,
`rgb`, `rgba`, `concat`, `format` (its text), `upcase`, `downcase`,
`length`, `at`, and arithmetic (`+ - * / % ^`, `min`, `max`, `abs`,
`floor`, `ceil`, `round`, `sqrt`, `ln`, `log10`, `log2`).
- Skipped whole: `fill-extrusion`, `raster`, `hillshade`, `heatmap` and
`sky` layers; layers on raster sources; layers setting a pattern
(`fill-pattern`, `line-pattern`, `background-pattern`), `line-offset`,
`line-gradient` or a translation; layers whose values use an expression
not listed (or are malformed). A feature whose values cannot be evaluated
(a type that does not fit) is left out. Nothing unsupported throws.
- Ignored: icons (`icon-image`, sprites: a symbol layer draws its text
alone), text along lines (drawn level), `glyphs` (system fonts), and any
other paint or layout property not listed above.
The Cesium port loads the style before the base changes (a style that fails
leaves the base as it was), draws it as Web Mercator imagery under the
base's other imagery (`src/render/cesium/vectorBase.js`, 256 px tiles to
level 20), and credits each source's attribution as plain text. The stub
loads the style and paints nothing. The check `globe.base.vector` serves a
style and a tile from data URLs and reads the drawn fill.
### What a renderer does, by role
A renderer is more than a drawing surface: it is a whole globe engine. The
+60 -13
View File
@@ -1500,9 +1500,21 @@
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/maps/keylessTerrain.js"
"src/maps/keylessTerrain.js",
"src/render/cesium/vectorBase.js",
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js"
],
"external": ["cesium", "vue", "pinia", "vue-i18n"]
"external": [
"cesium",
"vue",
"pinia",
"vue-i18n",
"pbf",
"@mapbox/vector-tile"
]
},
"ui-styles": {
"exports": ["./ui/styles"],
@@ -2192,9 +2204,14 @@
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/maps/keylessTerrain.js"
"src/maps/keylessTerrain.js",
"src/render/cesium/vectorBase.js",
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js"
],
"external": ["cesium"]
"external": ["cesium", "pbf", "@mapbox/vector-tile"]
},
"earthquakes": {
"exports": ["./layers/earthquakes"],
@@ -2851,7 +2868,12 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/render/cesium/vectorBase.js",
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js"
],
"external": ["cesium", "pbf", "@mapbox/vector-tile"]
},
@@ -3033,9 +3055,14 @@
"src/render/cesium/zoomOutGuard.js",
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js"
"src/data/detectionOcclusion.js",
"src/render/cesium/vectorBase.js",
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js"
],
"external": ["hls.js", "cesium"]
"external": ["hls.js", "cesium", "pbf", "@mapbox/vector-tile"]
},
"street-level-layer": {
"exports": [
@@ -3559,9 +3586,14 @@
"src/render/cesium/sceneOcclusionProbe.js",
"src/render/occlusion/depthProbe.js",
"src/data/detectionOcclusion.js",
"src/maps/keylessTerrain.js"
"src/maps/keylessTerrain.js",
"src/render/cesium/vectorBase.js",
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js"
],
"external": ["cesium"]
"external": ["cesium", "pbf", "@mapbox/vector-tile"]
},
"voice-connection": {
"exports": [
@@ -4861,7 +4893,12 @@
"src/render/cesium/viewers.js",
"src/ui/creditsView.js",
"src/data/planespottersPhoto.js",
"src/maps/keylessTerrain.js"
"src/maps/keylessTerrain.js",
"src/render/cesium/vectorBase.js",
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js"
],
"external": [
"hls.js",
@@ -5639,7 +5676,12 @@
"src/maps/engine.js",
"src/data/planespottersPhoto.js",
"src/render/cesium/zoomOutGuard.js",
"src/maps/keylessTerrain.js"
"src/maps/keylessTerrain.js",
"src/render/cesium/vectorBase.js",
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js"
],
"external": [
"hls.js",
@@ -7352,9 +7394,14 @@
"src/render/stub/viewRectangle.js",
"src/render/input/router.js",
"src/render/conformance/goldens/camera.json",
"src/render/conformance/checks/camera.js"
"src/render/conformance/checks/camera.js",
"src/render/vectorBase/index.js",
"src/render/vectorBase/style.js",
"src/render/vectorBase/paint.js",
"src/render/vectorBase/expressions.js",
"src/render/vectorBase/encode.js"
],
"external": []
"external": ["pbf", "@mapbox/vector-tile"]
},
"wildlife-sightings": {
"exports": ["./layers/wildlife-sightings"],
+20 -1
View File
@@ -20,6 +20,8 @@ import { provideUnboundGlobe } from '../rendererOf.js';
import { isBaseTileset, markBaseTileset } from '../baseTilesets.js';
import { listenerList, uncaught } from './common.js';
import { createCesiumImagery } from './imagery.js';
import { attributionText } from './vectorBase.js';
import { loadVectorStyle } from '../vectorBase/index.js';
import { createTerrainRetryPolicy } from '../../maps/terrainRetry.js';
// The base marks live outside the adapter, so code that is not Cesium's can
@@ -134,6 +136,8 @@ export function createCesiumGlobe(
let photorealGen = 0;
let terrainGen = 0;
let baseCredit = null;
// The vector base's sources' credits.
const vectorCredits = [];
/** Every 3D tileset the scene holds. */
function tilesets() {
@@ -234,10 +238,24 @@ export function createCesiumGlobe(
}
async function setBase(base) {
if (base.vector) throw new TypeError('This renderer draws no vector base');
if (base.vector && !can('vectorBase'))
throw new TypeError('This renderer draws no vector base');
// The style loads before the base changes: one that fails changes
// nothing.
const style = base.vector
? await loadVectorStyle(base.vector.styleUrl)
: null;
for (const handle of imagery.list()) handle.remove();
baseCredit?.();
baseCredit = base.credit && credits ? credits.addStatic(base.credit) : null;
for (const off of vectorCredits.splice(0)) off();
if (style) {
// Under any imagery the base also gives.
imagery.add({ kind: 'vectorStyle', style }, undefined, { base: true });
if (credits)
for (const text of style.attribution.map(attributionText))
if (text) vectorCredits.push(credits.addStatic({ text }));
}
const loads = [];
if (base.photoreal !== undefined) loads.push(setPhotoreal(base.photoreal));
if (base.terrain !== undefined) loads.push(setTerrain(base.terrain));
@@ -569,6 +587,7 @@ export function createCesiumGlobe(
imagery.dispose();
baseCredit?.();
baseCredit = null;
for (const off of vectorCredits.splice(0)) off();
},
};
}
+1
View File
@@ -90,6 +90,7 @@ export const CESIUM_CHECKS = new Set([
'frame.renderOnce',
'frame.suspend',
'frame.time',
'globe.base.vector',
'globe.imagery',
'globe.imagery.frames',
'globe.imagery.video',
+4
View File
@@ -20,6 +20,7 @@
* imagery (`imageryFrames.js`).
*/
import * as Cesium from 'cesium';
import { vectorBaseProvider } from './vectorBase.js';
import { creditMarkup } from './credits.js';
import { listenerList } from './common.js';
import {
@@ -146,6 +147,9 @@ export function providerFor(spec, { worldDataToken } = {}) {
{ accessToken },
);
}
// The app's own: the vector base's tiles, painted from its style.
case 'vectorStyle':
return vectorBaseProvider(spec.style);
case 'canvas':
if (typeof spec.drawTile !== 'function')
throw new TypeError('Canvas imagery needs drawTile');
+3 -1
View File
@@ -50,6 +50,8 @@ const GLOBE_CAPABILITIES = [
'imageryFrames',
'surfaceIdentity',
'surfaceShading',
// A MapLibre style's vector tiles, painted as imagery (`vectorBase.js`).
'vectorBase',
'globeVisibility',
];
@@ -83,7 +85,7 @@ export function cesiumCapabilities(scene, only) {
? ['keepEarthFramed']
: []),
...GPU_ICON_CAPABILITIES,
// Icon sets on billboards cluster on screen (`draw.js`).
// Icon sets cluster on screen, on billboards and the GPU (`draw.js`).
'cluster',
'styles',
'bloom',
+1
View File
@@ -30,6 +30,7 @@ test('capabilities follow what the scene supports', () => {
'imageryFrames',
'surfaceIdentity',
'surfaceShading',
'vectorBase',
];
const globe = { show: true };
const draw = ['models', 'modelAtmosphere', 'quads', 'meshes', 'fields'];
+49
View File
@@ -0,0 +1,49 @@
/**
* @module render/cesium/vectorBase
* @description `vectorBase` on Cesium: an imagery provider over the vector
* base painter (`src/render/vectorBase/`), each Web Mercator tile painted
* from the style at 256 px.
*/
import * as Cesium from 'cesium';
import { paintVectorTile } from '../vectorBase/index.js';
/** The tile size vector base tiles are painted at, pixels. */
export const VECTOR_TILE_PX = 256;
/** The deepest level painted; deeper, Cesium draws this level's tiles. */
export const VECTOR_MAX_LEVEL = 20;
/**
* A Cesium imagery provider painting a loaded style's tiles.
* @param {Awaited<ReturnType<typeof import('../vectorBase/index.js').loadVectorStyle>>} style
*/
export function vectorBaseProvider(style) {
const tilingScheme = new Cesium.WebMercatorTilingScheme();
return {
tilingScheme,
tileWidth: VECTOR_TILE_PX,
tileHeight: VECTOR_TILE_PX,
minimumLevel: 0,
maximumLevel: VECTOR_MAX_LEVEL,
rectangle: tilingScheme.rectangle,
credit: undefined,
errorEvent: new Cesium.Event(),
hasAlphaChannel: false,
tileDiscardPolicy: undefined,
proxy: undefined,
getTileCredits: () => undefined,
pickFeatures: () => undefined,
requestImage: (x, y, level) =>
paintVectorTile(style, level, x, y, { size: VECTOR_TILE_PX }),
};
}
/** A TileJSON attribution (markup) as plain text. */
export function attributionText(html) {
return String(html)
.replace(/<[^>]*>/g, ' ')
.replace(/&copy;/gi, '©')
.replace(/&amp;/gi, '&')
.replace(/\s+/g, ' ')
.trim();
}
+34
View File
@@ -0,0 +1,34 @@
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import test from 'node:test';
import {
attributionText,
VECTOR_TILE_PX,
vectorBaseProvider,
} from './vectorBase.js';
import { cesiumCapabilities } from './ports.js';
test('the vector base is Web Mercator imagery painted from its style', () => {
const provider = vectorBaseProvider({
layers: [],
sources: {},
tiles: new Map(),
});
assert.ok(provider.tilingScheme instanceof Cesium.WebMercatorTilingScheme);
assert.equal(provider.tileWidth, VECTOR_TILE_PX);
assert.equal(provider.hasAlphaChannel, false);
assert.equal(typeof provider.requestImage, 'function');
});
test('a source’s attribution is credited as plain text', () => {
assert.equal(
attributionText(
'<a href="https://x.test">&copy; OpenMapTiles</a> <a href="y">Data &amp; more</a>',
),
'© OpenMapTiles Data & more',
);
});
test('a Cesium globe claims vectorBase', () => {
assert.ok(cesiumCapabilities({}).includes('vectorBase'));
});
+104
View File
@@ -13,6 +13,7 @@ import {
import { AUSTIN, SCRIPT_VIEWPORT } from '../cameraScripts.js';
import { deepEqual, equal, near, nearVec, ok, throws } from '../expect.js';
import { iconPosition } from '../../motion/iconMotion.js';
import { encodeVectorTile } from '../../vectorBase/encode.js';
/** 1 × 1 PNGs (red, green, blue), so imagery checks load nothing from the network. */
const PIXEL_PNGS = [
@@ -4032,6 +4033,109 @@ export function portChecks() {
deepEqual(ours(), [], 'both removed');
},
),
check(
'globe.base.vector',
'a vector base draws its style: the fills its filters keep, over its background; a style that fails to load changes nothing',
async (h, r) => {
await overAustin(h, r, 20000);
// One tile for every tile: the whole of it sea, and a road.
const whole = [
[
[-64, -64],
[4160, -64],
[4160, 4160],
[-64, 4160],
[-64, -64],
],
];
const tile = encodeVectorTile({
water: [
{ type: 'Polygon', geometry: whole, properties: { class: 'sea' } },
],
});
let binary = '';
for (const byte of tile) binary += String.fromCharCode(byte);
const style = {
version: 8,
sources: {
base: {
type: 'vector',
tiles: [`data:application/x-protobuf;base64,${btoa(binary)}`],
maxzoom: 14,
attribution: '<a href="https://example.test">Test tiles</a>',
},
},
layers: [
{
id: 'bg',
type: 'background',
paint: { 'background-color': '#ff0000' },
},
{
id: 'sea',
type: 'fill',
source: 'base',
'source-layer': 'water',
filter: ['==', ['get', 'class'], 'sea'],
paint: { 'fill-color': '#00c8ff' },
},
{
id: 'lake',
type: 'fill',
source: 'base',
'source-layer': 'water',
filter: ['==', 'class', 'lake'],
paint: { 'fill-color': '#ffff00' },
},
],
};
const styleUrl = `data:application/json,${encodeURIComponent(JSON.stringify(style))}`;
const status = await r.globe.setBase({ vector: { styleUrl } });
ok(status && Array.isArray(status.imagery), 'the base is set');
const below = r.query.project(h.toEcef({ ...AUSTIN, height: 0 }));
const middle = async () => {
await settled(r);
r.frame.renderNow();
const { data } = r.readPixels({
crop: {
x: Math.round(below.x) - 4,
y: Math.round(below.y) - 4,
width: 9,
height: 9,
},
});
const mean = [0, 0, 0];
for (let i = 0; i < data.length; i += 4)
for (let c = 0; c < 3; c++)
mean[c] += data[i + c] / (data.length / 4);
return mean;
};
if (h.pixels !== false) {
const [red, green, blue] = await middle();
ok(
blue > 170 && green > 120 && red < 90,
`the sea is drawn, not its background or the filtered lake (${[red, green, blue].map(Math.round)})`,
);
}
let failed = false;
try {
await r.globe.setBase({
vector: { styleUrl: 'data:application/json,%7B%7D' },
});
} catch {
failed = true;
}
ok(failed, 'a document that is no style is refused');
if (h.pixels !== false) {
const [red, green, blue] = await middle();
ok(
blue > 170 && red < 90,
`the base is as it was (${[red, green, blue].map(Math.round)})`,
);
}
},
{ capability: 'vectorBase' },
),
check(
'globe.imagery.frames',
'timed frames follow scene time, or setFrameTime on their own clock',
+6
View File
@@ -18,6 +18,7 @@ import { CAPABILITIES, CONTRACT_VERSION } from '../contract/index.js';
import { createStubCamera } from './camera.js';
import { motionPosition } from '../motion/iconMotion.js';
import { computeViewRectangle } from './viewRectangle.js';
import { loadVectorStyle } from '../vectorBase/index.js';
import {
add,
dot,
@@ -1420,6 +1421,11 @@ export function createStubRenderer(options = {}) {
const globe = {
async setBase(base) {
log('globe', 'setBase', [base]);
if (base.vector && !capabilities.has('vectorBase'))
throw new TypeError('This renderer draws no vector base');
// The style is loaded, as a renderer drawing it loads it, so one that
// fails changes nothing; the stub paints none of it.
if (base.vector) await loadVectorStyle(base.vector.styleUrl);
for (const layer of imageryLayers.slice()) layer.remove();
if (base.photoreal !== undefined)
await globe.setPhotoreal(base.photoreal);
+89
View File
@@ -0,0 +1,89 @@
/**
* @module render/vectorBase/encode
* @description A small Mapbox Vector Tile encoder, for fixtures: the tests
* and conformance checks build the tiles the painter reads with it.
*/
import { PbfWriter } from 'pbf';
const TYPES = { Point: 1, LineString: 2, Polygon: 3 };
const zigzag = (n) => (n << 1) ^ (n >> 31);
const command = (id, count) => (id & 7) | (count << 3);
/** A feature's geometry as MVT commands. */
function geometryOf(type, parts) {
const out = [];
let cx = 0;
let cy = 0;
const move = ([x, y]) => {
out.push(zigzag(x - cx), zigzag(y - cy));
cx = x;
cy = y;
};
if (type === 'Point') {
const points = parts.flat();
out.push(command(1, points.length));
points.forEach(move);
return out;
}
for (const part of parts) {
// A ring's closing point is the close command.
const points = type === 'Polygon' ? part.slice(0, -1) : part;
out.push(command(1, 1));
move(points[0]);
out.push(command(2, points.length - 1));
points.slice(1).forEach(move);
if (type === 'Polygon') out.push(command(7, 1));
}
return out;
}
/**
* Encode layers of features as a vector tile.
* @param {Record<string, Array<{type: 'Point'|'LineString'|'Polygon',
* geometry: number[][][], properties?: Record<string, string|number|boolean>,
* id?: number}>>} layers Geometry in tile units (`extent` 4096), polygon
* rings closed.
* @param {number} [extent]
* @returns {Uint8Array}
*/
export function encodeVectorTile(layers, extent = 4096) {
const pbf = new PbfWriter();
for (const [name, features] of Object.entries(layers)) {
const keys = [];
const values = [];
const index = (list, v) => {
let i = list.indexOf(v);
if (i < 0) i = list.push(v) - 1;
return i;
};
const encoded = features.map((f) => ({
...f,
tags: Object.entries(f.properties ?? {}).flatMap(([k, v]) => [
index(keys, k),
index(values, v),
]),
}));
pbf.writeMessage(3, (_, p) => {
p.writeVarintField(15, 2);
p.writeStringField(1, name);
for (const f of encoded)
p.writeMessage(2, (__, q) => {
if (f.id !== undefined) q.writeVarintField(1, f.id);
q.writePackedVarint(2, f.tags);
q.writeVarintField(3, TYPES[f.type]);
q.writePackedVarint(4, geometryOf(f.type, f.geometry));
});
for (const k of keys) p.writeStringField(3, k);
for (const v of values)
p.writeMessage(4, (__, q) => {
if (typeof v === 'string') q.writeStringField(1, v);
else if (typeof v === 'boolean') q.writeBooleanField(7, v);
else if (Number.isInteger(v)) q.writeSVarintField(6, v);
else q.writeDoubleField(3, v);
});
p.writeVarintField(5, extent);
});
}
return pbf.finish();
}
+618
View File
@@ -0,0 +1,618 @@
/**
* @module render/vectorBase/expressions
* @description The part of the MapLibre style specification's expressions,
* filters and legacy functions that the vector base painter evaluates. A
* value is compiled once into a function of `{zoom, properties, type, id}`
* (`type` is `'Point'`, `'LineString'` or `'Polygon'`). Compiling throws an
* {@link Unsupported} for what is not covered, so the caller skips the layer;
* a compiled function that meets a value it cannot handle throws one too, so
* the caller skips the feature. Nothing here guesses.
*/
/** What the painter does not evaluate: the layer or feature is skipped. */
export class Unsupported extends Error {}
const unsupported = (what) => {
throw new Unsupported(what);
};
/** A feature with no properties, at a zoom: what a zoom-only value sees. */
const constant = (value) => () => value;
const COMPARE = {
'==': (a, b) => a === b,
'!=': (a, b) => a !== b,
'<': (a, b) => a < b,
'<=': (a, b) => a <= b,
'>': (a, b) => a > b,
'>=': (a, b) => a >= b,
};
const ARITHMETIC = {
'+': (args) => args.reduce((a, b) => a + b, 0),
'*': (args) => args.reduce((a, b) => a * b, 1),
'-': (args) => (args.length === 1 ? -args[0] : args[0] - args[1]),
'/': (args) => args[0] / args[1],
'%': (args) => args[0] % args[1],
'^': (args) => args[0] ** args[1],
min: (args) => Math.min(...args),
max: (args) => Math.max(...args),
abs: (args) => Math.abs(args[0]),
floor: (args) => Math.floor(args[0]),
ceil: (args) => Math.ceil(args[0]),
round: (args) => Math.round(args[0]),
sqrt: (args) => Math.sqrt(args[0]),
ln: (args) => Math.log(args[0]),
log10: (args) => Math.log10(args[0]),
log2: (args) => Math.log2(args[0]),
};
const NAMED_COLORS = {
black: [0, 0, 0, 1],
white: [255, 255, 255, 1],
red: [255, 0, 0, 1],
green: [0, 128, 0, 1],
blue: [0, 0, 255, 1],
yellow: [255, 255, 0, 1],
gray: [128, 128, 128, 1],
grey: [128, 128, 128, 1],
transparent: [0, 0, 0, 0],
};
/**
* A CSS colour as `[r, g, b, a]` (0..255, alpha 0..1): hex, `rgb()`,
* `rgba()`, `hsl()`, `hsla()` and a few names; null for anything else.
* @param {unknown} text
*/
export function parseColor(text) {
if (Array.isArray(text) && text.length === 4) return text;
if (typeof text !== 'string') return null;
const s = text.trim().toLowerCase();
if (NAMED_COLORS[s]) return NAMED_COLORS[s].slice();
let m = /^#([0-9a-f]{3,8})$/.exec(s);
if (m) {
const h = m[1];
if (h.length === 3 || h.length === 4) {
const [r, g, b, a = 'f'] = h;
return [
parseInt(r + r, 16),
parseInt(g + g, 16),
parseInt(b + b, 16),
parseInt(a + a, 16) / 255,
];
}
if (h.length === 6 || h.length === 8)
return [
parseInt(h.slice(0, 2), 16),
parseInt(h.slice(2, 4), 16),
parseInt(h.slice(4, 6), 16),
h.length === 8 ? parseInt(h.slice(6, 8), 16) / 255 : 1,
];
return null;
}
m = /^(rgba?|hsla?)\(([^)]*)\)$/.exec(s);
if (!m) return null;
const parts = m[2].split(/[\s,/]+/).filter(Boolean);
if (parts.length < 3) return null;
const num = (p, scale) =>
p.endsWith('%') ? (parseFloat(p) / 100) * scale : parseFloat(p);
const alpha = parts[3] === undefined ? 1 : num(parts[3], 1);
if (m[1].startsWith('rgb')) {
const rgb = parts.slice(0, 3).map((p) => num(p, 255));
return rgb.concat(alpha).some((v) => !Number.isFinite(v))
? null
: [...rgb, alpha];
}
const hue = (((parseFloat(parts[0]) % 360) + 360) % 360) / 360;
const sat = parseFloat(parts[1]) / 100;
const light = parseFloat(parts[2]) / 100;
if (![hue, sat, light, alpha].every(Number.isFinite)) return null;
const q = light < 0.5 ? light * (1 + sat) : light + sat - light * sat;
const p = 2 * light - q;
const channel = (t) => {
t = (t + 1) % 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
};
return [
channel(hue + 1 / 3) * 255,
channel(hue) * 255,
channel(hue - 1 / 3) * 255,
alpha,
];
}
/** `[r, g, b, a]` as a CSS colour. */
export function cssOf(color) {
const [r, g, b, a] = color;
return `rgba(${Math.round(r)},${Math.round(g)},${Math.round(b)},${a})`;
}
/** Between `a` and `b` (numbers, colours, or arrays of numbers) at `t`. */
function mix(a, b, t) {
if (typeof a === 'number' && typeof b === 'number') return a + (b - a) * t;
if (Array.isArray(a) && Array.isArray(b) && a.length === b.length)
return a.map((v, i) => mix(v, b[i], t));
const ca = parseColor(a);
const cb = parseColor(b);
if (ca && cb) return cssOf(ca.map((v, i) => v + (cb[i] - v) * t));
return unsupported(`interpolate between ${a} and ${b}`);
}
/** How far `x` is from `lower` to `upper`, at an exponential `base`. */
function factor(x, base, lower, upper) {
const range = upper - lower;
if (range === 0) return 0;
const progress = x - lower;
if (base === 1) return progress / range;
return (base ** progress - 1) / (base ** range - 1);
}
/** The value of `stops` (`[input, output]`, rising) at `x`. */
function interpolateStops(stops, x, base, interpolate = true) {
if (x <= stops[0][0]) return stops[0][1];
const last = stops[stops.length - 1];
if (x >= last[0]) return last[1];
let i = 0;
while (i < stops.length - 1 && x >= stops[i + 1][0]) i++;
if (!interpolate) return stops[i][1];
const [x0, y0] = stops[i];
const [x1, y1] = stops[i + 1];
return mix(y0, y1, factor(x, base, x0, x1));
}
/** Whether a value is an expression (an array naming an operator). */
const isExpression = (value) =>
Array.isArray(value) && typeof value[0] === 'string';
/**
* Whether a filter is in the expression syntax rather than the legacy one,
* as the style specification tells them apart.
*/
export function isExpressionFilter(filter) {
if (filter === true || filter === false) return true;
if (!Array.isArray(filter) || filter.length === 0) return false;
switch (filter[0]) {
case 'has':
return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type';
case 'in':
return (
filter.length >= 3 &&
(typeof filter[1] !== 'string' || Array.isArray(filter[2]))
);
case '!in':
case '!has':
case 'none':
return false;
case '==':
case '!=':
case '>':
case '>=':
case '<':
case '<=':
return (
filter.length !== 3 ||
Array.isArray(filter[1]) ||
Array.isArray(filter[2])
);
case 'any':
case 'all':
return filter
.slice(1)
.every((f) => typeof f === 'boolean' || isExpressionFilter(f));
default:
return true;
}
}
/** A legacy filter's key on a feature: `$type`, `$id` or a property. */
const legacyKey = (key) => {
if (key === '$type') return (f) => f.type;
if (key === '$id') return (f) => f.id;
return (f) => f.properties[key];
};
/** A legacy filter, compiled. */
function compileLegacyFilter(filter) {
if (!Array.isArray(filter)) return unsupported(`filter ${filter}`);
const [op, ...args] = filter;
switch (op) {
case 'all':
case 'any':
case 'none': {
const parts = args.map(compileLegacyFilter);
if (op === 'all') return (f) => parts.every((p) => p(f));
if (op === 'any') return (f) => parts.some((p) => p(f));
return (f) => !parts.some((p) => p(f));
}
case 'has':
case '!has': {
const has = (f) =>
args[0] === '$type' || args[0] === '$id'
? legacyKey(args[0])(f) !== undefined
: args[0] in f.properties;
return op === 'has' ? has : (f) => !has(f);
}
case 'in':
case '!in': {
const get = legacyKey(args[0]);
const values = new Set(args.slice(1));
return op === 'in'
? (f) => values.has(get(f))
: (f) => !values.has(get(f));
}
default: {
const compare = COMPARE[op];
if (!compare || args.length !== 2) return unsupported(`filter ${op}`);
const get = legacyKey(args[0]);
const value = args[1];
if (op === '==') return (f) => get(f) === value;
if (op === '!=') return (f) => get(f) !== value;
// Ordered comparisons hold only between values of one type.
return (f) => {
const v = get(f);
return typeof v === typeof value && compare(v, value);
};
}
}
}
/**
* A layer's `filter`, compiled to `(feature) => boolean` (none: every
* feature).
* @param {unknown} filter
*/
export function compileFilter(filter) {
if (filter === undefined || filter === null) return () => true;
if (!isExpressionFilter(filter)) return compileLegacyFilter(filter);
const fn = compileExpression(filter);
return (f) => fn(f) === true;
}
/** A legacy `{stops, base, property, type, default}` function, compiled. */
function compileFunction(fn) {
const stops = fn.stops;
const base = fn.base ?? 1;
const type =
fn.type ??
(fn.property !== undefined && typeof stops?.[0]?.[1] === 'string'
? 'categorical'
: 'exponential');
if (type === 'identity') {
if (fn.property === undefined) return unsupported('identity of zoom');
return (f) => f.properties[fn.property] ?? fn.default;
}
if (!Array.isArray(stops) || stops.length === 0)
return unsupported('a function without stops');
// Zoom-and-property stops: `[{zoom, value}, output]`.
if (typeof stops[0][0] === 'object') return unsupported('zoom and property');
const input =
fn.property === undefined
? (f) => f.zoom
: (f) => f.properties[fn.property];
if (type === 'categorical') {
const map = new Map(stops.map(([k, v]) => [k, v]));
return (f) => {
const v = input(f);
return map.has(v) ? map.get(v) : fn.default;
};
}
if (type !== 'exponential' && type !== 'interval')
return unsupported(`function type ${type}`);
return (f) => {
const x = input(f);
if (typeof x !== 'number') return fn.default;
return interpolateStops(stops, x, base, type === 'exponential');
};
}
/**
* A layout or paint value, compiled: a constant, a legacy function, or an
* expression.
* @param {unknown} value
* @returns {(feature: object) => unknown}
*/
export function compileValue(value, { array = false } = {}) {
// An array property's own value (`text-font`, `line-dasharray`): a
// literal unless it names an operator.
if (
array &&
Array.isArray(value) &&
value.every((v) => !Array.isArray(v)) &&
!OPERATORS.has(value[0])
)
return constant(value);
if (isExpression(value)) return compileExpression(value);
if (value && typeof value === 'object' && !Array.isArray(value))
return compileFunction(value);
return constant(value);
}
/** The operators {@link compileExpression} evaluates. */
export const OPERATORS = new Set([
'literal',
'zoom',
'geometry-type',
'id',
'properties',
'get',
'has',
'!',
'all',
'any',
'==',
'!=',
'<',
'<=',
'>',
'>=',
'in',
'case',
'match',
'coalesce',
'step',
'interpolate',
'interpolate-hcl',
'interpolate-lab',
'to-string',
'to-number',
'to-boolean',
'number',
'string',
'boolean',
'to-color',
'rgb',
'rgba',
'concat',
'format',
'upcase',
'downcase',
'length',
'at',
...Object.keys(ARITHMETIC),
]);
/**
* An expression, compiled.
* @param {unknown} expr
* @returns {(feature: object) => unknown}
*/
export function compileExpression(expr) {
if (!Array.isArray(expr)) return constant(expr);
if (!isExpression(expr)) return unsupported('an array that is not literal');
const [op, ...raw] = expr;
const args = () => raw.map(compileExpression);
switch (op) {
case 'literal':
return constant(raw[0]);
case 'zoom':
return (f) => f.zoom;
case 'geometry-type':
return (f) => f.type;
case 'id':
return (f) => f.id ?? null;
case 'properties':
return (f) => f.properties;
case 'get': {
if (raw.length !== 1) return unsupported('get from an object');
const [key] = args();
return (f) => f.properties[key(f)] ?? null;
}
case 'has': {
if (raw.length !== 1) return unsupported('has in an object');
const [key] = args();
return (f) => key(f) in f.properties;
}
case '!': {
const [a] = args();
return (f) => !a(f);
}
case 'all': {
const parts = args();
return (f) => parts.every((p) => p(f) === true);
}
case 'any': {
const parts = args();
return (f) => parts.some((p) => p(f) === true);
}
case '==':
case '!=':
case '<':
case '<=':
case '>':
case '>=': {
if (raw.length !== 2) return unsupported(`${op} with a collator`);
const [a, b] = args();
const compare = COMPARE[op];
if (op === '==' || op === '!=')
return (f) => compare(a(f) ?? null, b(f) ?? null);
return (f) => {
const x = a(f);
const y = b(f);
return typeof x === typeof y && x !== null && compare(x, y);
};
}
case 'in': {
const [needle, haystack] = args();
return (f) => {
const h = haystack(f);
const n = needle(f);
if (typeof h === 'string') return h.includes(n);
if (Array.isArray(h)) return h.includes(n);
return unsupported('in over this value');
};
}
case 'case': {
const parts = args();
const fallback = parts.pop();
return (f) => {
for (let i = 0; i < parts.length; i += 2)
if (parts[i](f) === true) return parts[i + 1](f);
return fallback(f);
};
}
case 'match': {
const input = compileExpression(raw[0]);
const fallback = compileExpression(raw[raw.length - 1]);
const arms = [];
for (let i = 1; i < raw.length - 1; i += 2)
arms.push([new Set([raw[i]].flat()), compileExpression(raw[i + 1])]);
return (f) => {
const v = input(f);
for (const [labels, out] of arms) if (labels.has(v)) return out(f);
return fallback(f);
};
}
case 'coalesce': {
const parts = args();
return (f) => {
for (const p of parts) {
const v = p(f);
if (v !== null && v !== undefined) return v;
}
return null;
};
}
case 'step': {
const input = compileExpression(raw[0]);
const first = compileExpression(raw[1]);
const steps = [];
for (let i = 2; i < raw.length; i += 2)
steps.push([raw[i], compileExpression(raw[i + 1])]);
return (f) => {
const x = input(f);
let out = first;
for (const [at, value] of steps) if (x >= at) out = value;
return out(f);
};
}
case 'interpolate':
case 'interpolate-hcl':
case 'interpolate-lab': {
const [kind, base = 1] = raw[0];
if (kind !== 'linear' && kind !== 'exponential')
return unsupported(`interpolate ${kind}`);
const b = kind === 'linear' ? 1 : base;
const input = compileExpression(raw[1]);
const stops = [];
for (let i = 2; i < raw.length; i += 2)
stops.push([raw[i], compileExpression(raw[i + 1])]);
return (f) => {
const x = input(f);
if (typeof x !== 'number')
return unsupported('interpolate a non-number');
return interpolateStops(
stops.map(([at, value]) => [at, value(f)]),
x,
b,
);
};
}
case 'to-string': {
const [a] = args();
return (f) => {
const v = a(f);
return v === null || v === undefined ? '' : String(v);
};
}
case 'to-number': {
const parts = args();
return (f) => {
for (const p of parts) {
const v = Number(p(f));
if (Number.isFinite(v)) return v;
}
return unsupported('to-number of a non-number');
};
}
case 'to-boolean': {
const [a] = args();
return (f) => Boolean(a(f));
}
case 'number':
case 'string':
case 'boolean': {
const parts = args();
return (f) => {
for (const p of parts) {
const v = p(f);
if (typeof v === op) return v;
}
return unsupported(`${op} assertion failed`);
};
}
case 'to-color': {
const parts = args();
return (f) => {
for (const p of parts) {
const v = p(f);
if (parseColor(v)) return v;
}
return unsupported('to-color of a non-colour');
};
}
case 'rgb':
case 'rgba': {
const parts = args();
return (f) => {
const [r, g, b, a = 1] = parts.map((p) => p(f));
return cssOf([r, g, b, a]);
};
}
case 'concat': {
const parts = args();
return (f) => parts.map((p) => textOf(p(f))).join('');
}
case 'format': {
// Text and its per-section options: the text alone.
const parts = [];
for (const item of raw)
if (!(item && typeof item === 'object' && !Array.isArray(item)))
parts.push(compileExpression(item));
return (f) => parts.map((p) => textOf(p(f))).join('');
}
case 'upcase':
case 'downcase': {
const [a] = args();
return (f) =>
op === 'upcase'
? textOf(a(f)).toUpperCase()
: textOf(a(f)).toLowerCase();
}
case 'length': {
const [a] = args();
return (f) => a(f)?.length ?? 0;
}
case 'at': {
const [i, a] = args();
return (f) => a(f)?.[i(f)] ?? null;
}
default: {
const arithmetic = ARITHMETIC[op];
if (!arithmetic) return unsupported(`expression ${op}`);
const parts = args();
return (f) => {
const values = parts.map((p) => p(f));
if (!values.every((v) => typeof v === 'number'))
return unsupported(`${op} of a non-number`);
return arithmetic(values);
};
}
}
}
/** A value as label text. */
function textOf(v) {
if (v === null || v === undefined) return '';
return String(v);
}
/**
* A legacy `text-field` string's `{property}` tokens, filled from the
* feature.
*/
export function fillTokens(text, properties) {
return text.replace(/{([^{}]+)}/g, (_, key) => textOf(properties[key]));
}
+15
View File
@@ -0,0 +1,15 @@
/**
* @module render/vectorBase
* @description The vector base painter: a MapLibre style document's vector
* tiles painted as Web Mercator raster tiles, Cesium-free. The renderer
* draws `vectorBase` as imagery over `paintVectorTile`.
*/
export { loadVectorStyle, PAINTED_TYPES } from './style.js';
export { paintVectorTile, STYLE_TILE_SIZE } from './paint.js';
export {
compileExpression,
compileFilter,
compileValue,
parseColor,
Unsupported,
} from './expressions.js';
+410
View File
@@ -0,0 +1,410 @@
/**
* @module render/vectorBase/paint
* @description Paints one Web Mercator tile of a vector base on a canvas from
* a loaded style ({@link module:render/vectorBase/style}): its background,
* fill, line and circle layers in style order, then its symbol layers' text
* labels. Cesium-free: the renderer hands the canvas to its own imagery.
*
* A tile `size` pixels wide at tile zoom `z` is painted at style zoom
* `z + log2(size / 512)` (at least 0), as a 512 px style tile at that zoom shows the
* same ground; sizes in the style are pixels of the painted tile. A source
* past its `maxzoom` is drawn from its deepest tile over this one (over-
* zoomed); below its `minzoom` it draws nothing. A feature whose filter or
* values cannot be evaluated is left out.
*
* Labels are placed top layer first, each kept clear of those placed
* before it and wholly inside its tile (a label across a tile edge is left
* out, never cut); a point labels at itself, a line at the point halfway
* along it, a polygon at its outer ring's bounding-box centre. Text wraps at
* `text-max-width`; fonts are the system's sans-serif (serif for a
* `text-font` naming one), bold or italic as the font name says.
*/
import { PbfReader } from 'pbf';
import { VectorTile } from '@mapbox/vector-tile';
import { fillTokens } from './expressions.js';
/** The tile size style zooms are given for, pixels. */
export const STYLE_TILE_SIZE = 512;
/** Decoded source tiles kept for a style. */
const KEPT_TILES = 128;
const TYPES = { 1: 'Point', 2: 'LineString', 3: 'Polygon' };
/** A canvas of `size` square: in a page, else offscreen. */
function createCanvas(size) {
if (typeof document !== 'undefined' && document.createElement) {
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
return canvas;
}
if (typeof OffscreenCanvas !== 'undefined')
return new OffscreenCanvas(size, size);
throw new TypeError('no canvas to paint a vector tile on');
}
/** Bytes, gunzipped when they are gzip. */
async function inflate(bytes) {
if (bytes[0] !== 0x1f || bytes[1] !== 0x8b) return bytes;
if (typeof DecompressionStream === 'undefined')
throw new Error('a gzipped vector tile, and no DecompressionStream');
const stream = new Blob([bytes])
.stream()
.pipeThrough(new DecompressionStream('gzip'));
return new Uint8Array(await new Response(stream).arrayBuffer());
}
/** A source tile's URL. */
function tileUrl(source, z, x, y) {
const template = source.tiles[(x + y) % source.tiles.length];
const ty = source.scheme === 'tms' ? 2 ** z - 1 - y : y;
return template
.replace(/{z}/g, z)
.replace(/{x}/g, x)
.replace(/{y}/g, ty)
.replace(/{-y}/g, 2 ** z - 1 - y);
}
/** A source tile, decoded once per style; null where there is none. */
function sourceTile(style, url, fetchImpl) {
let tile = style.tiles.get(url);
if (tile) {
// Most recently used last.
style.tiles.delete(url);
style.tiles.set(url, tile);
return tile;
}
tile = (async () => {
const response = await fetchImpl(url);
// No tile there (an empty answer or none): nothing to draw.
if (response.status === 204 || response.status === 404) return null;
if (!response.ok)
throw new Error(`${url} answered ${response.status ?? 'an error'}`);
const bytes = await inflate(new Uint8Array(await response.arrayBuffer()));
return bytes.length ? new VectorTile(new PbfReader(bytes)) : null;
})();
// A failed fetch is tried again by the next tile that needs it.
tile.catch(() => style.tiles.delete(url));
style.tiles.set(url, tile);
while (style.tiles.size > KEPT_TILES)
style.tiles.delete(style.tiles.keys().next().value);
return tile;
}
/** A value of a layer for a feature; throws where it cannot be evaluated. */
const valueOf = (layer, key, f) => layer.values[key]?.(f);
/** Paths a feature's rings or lines in tile pixels. */
function tracePath(ctx, rings, at) {
ctx.beginPath();
for (const ring of rings)
for (let i = 0; i < ring.length; i++) {
const [px, py] = at(ring[i]);
if (i === 0) ctx.moveTo(px, py);
else ctx.lineTo(px, py);
}
}
/** The point halfway along a line, in tile pixels. */
function halfway(line, at) {
const points = line.map(at);
let length = 0;
for (let i = 1; i < points.length; i++)
length += Math.hypot(
points[i][0] - points[i - 1][0],
points[i][1] - points[i - 1][1],
);
let left = length / 2;
for (let i = 1; i < points.length; i++) {
const [x0, y0] = points[i - 1];
const [x1, y1] = points[i];
const step = Math.hypot(x1 - x0, y1 - y0);
if (step >= left && step > 0) {
const t = left / step;
return [x0 + (x1 - x0) * t, y0 + (y1 - y0) * t];
}
left -= step;
}
return points[0];
}
/** A CSS font for a `text-font` stack at `px`. */
function fontOf(stack, px) {
const name = String([stack].flat()[0] ?? '');
const bold = /bold|black|heavy|semibold/i.test(name) ? 'bold ' : '';
const italic = /italic|oblique/i.test(name) ? 'italic ' : '';
const family =
/serif/i.test(name) && !/sans/i.test(name) ? 'serif' : 'sans-serif';
return `${italic}${bold}${px}px ${family}`;
}
/** `text` broken into lines no wider than `max` pixels (by words). */
function wrap(ctx, text, max) {
const lines = [];
for (const paragraph of text.split('\n')) {
let line = '';
for (const word of paragraph.split(/\s+/).filter(Boolean)) {
const next = line ? `${line} ${word}` : word;
if (line && ctx.measureText(next).width > max) {
lines.push(line);
line = word;
} else line = next;
}
if (line) lines.push(line);
}
return lines;
}
/** Whether two `[x0, y0, x1, y1]` boxes overlap. */
const overlaps = (a, b) =>
a[0] < b[2] && b[0] < a[2] && a[1] < b[3] && b[1] < a[3];
/**
* Paint tile `z/x/y` of a vector base.
* @param {Awaited<ReturnType<typeof import('./style.js').loadVectorStyle>>} style
* @param {number} z
* @param {number} x
* @param {number} y
* @param {{size?: number, fetch?: typeof fetch, signal?: AbortSignal,
* canvas?: (size: number) => HTMLCanvasElement | OffscreenCanvas}} [options]
* `canvas` makes the canvas to paint on (by default one in the page, else
* an offscreen one).
* @returns {Promise<HTMLCanvasElement | OffscreenCanvas>}
*/
export async function paintVectorTile(
style,
z,
x,
y,
{ size = 256, fetch: fetchImpl = globalThis.fetch, signal, canvas } = {},
) {
// No style zoom is below 0.
const zoom = Math.max(0, z + Math.log2(size / STYLE_TILE_SIZE));
const shown = style.layers.filter(
(layer) => zoom >= layer.minzoom && zoom < layer.maxzoom,
);
// Each source's tile over this one: its own, or its deepest one's.
const tiles = new Map();
for (const layer of shown) {
if (layer.type === 'background' || tiles.has(layer.source)) continue;
const source = style.sources[layer.source];
if (z < source.minzoom) {
tiles.set(layer.source, null);
continue;
}
const zs = Math.min(z, source.maxzoom);
const d = z - zs;
const url = tileUrl(source, zs, x >> d, y >> d);
tiles.set(layer.source, {
tile: sourceTile(style, url, fetchImpl),
scale: 2 ** d,
dx: x - ((x >> d) << d),
dy: y - ((y >> d) << d),
});
}
for (const entry of tiles.values()) if (entry) entry.tile = await entry.tile;
if (signal?.aborted)
throw signal.reason ?? new DOMException('aborted', 'AbortError');
const out = canvas ? canvas(size) : createCanvas(size);
const ctx = out.getContext('2d');
ctx.clearRect(0, 0, size, size);
const labels = [];
for (const layer of shown) {
if (layer.type === 'background') {
const f = { zoom, properties: {}, type: 'Polygon' };
try {
ctx.globalAlpha = Number(valueOf(layer, 'background-opacity', f));
ctx.fillStyle = String(valueOf(layer, 'background-color', f));
ctx.fillRect(0, 0, size, size);
} catch {
// Not evaluated: no background from this layer.
}
ctx.globalAlpha = 1;
continue;
}
const entry = tiles.get(layer.source);
const source = entry?.tile?.layers?.[layer.sourceLayer];
if (!source) continue;
const k = (entry.scale * size) / source.extent;
const at = (p) => [p.x * k - entry.dx * size, p.y * k - entry.dy * size];
for (let i = 0; i < source.length; i++) {
const feature = source.feature(i);
const f = {
zoom,
properties: feature.properties,
type: TYPES[feature.type],
id: feature.id,
};
try {
if (!f.type || !layer.filter(f)) continue;
drawFeature(ctx, layer, feature, f, at, labels);
} catch {
// A filter or value not evaluated: the feature is left out.
}
ctx.globalAlpha = 1;
ctx.setLineDash?.([]);
}
}
placeLabels(ctx, labels, size);
return out;
}
/** Draw a feature of a fill, line or circle layer; queue a symbol's label. */
function drawFeature(ctx, layer, feature, f, at, labels) {
const v = (key) => valueOf(layer, key, f);
switch (layer.type) {
case 'fill': {
if (f.type !== 'Polygon') return;
const rings = feature.loadGeometry();
tracePath(ctx, rings, at);
ctx.globalAlpha = Number(v('fill-opacity'));
ctx.fillStyle = String(v('fill-color'));
ctx.fill('evenodd');
if (layer.values['fill-outline-color']) {
ctx.strokeStyle = String(v('fill-outline-color'));
ctx.lineWidth = 1;
ctx.stroke();
}
return;
}
case 'line': {
if (f.type === 'Point') return;
const width = Number(v('line-width'));
const gap = Number(v('line-gap-width'));
// A cased line (a gap between two lines) as one line its full width,
// under what fills the gap.
const drawn = gap > 0 ? gap + 2 * width : width;
if (!(drawn > 0)) return;
tracePath(ctx, feature.loadGeometry(), at);
ctx.globalAlpha = Number(v('line-opacity'));
ctx.strokeStyle = String(v('line-color'));
ctx.lineWidth = drawn;
ctx.lineCap = String(v('line-cap'));
ctx.lineJoin = String(v('line-join'));
const dashes = layer.values['line-dasharray'] && v('line-dasharray');
if (Array.isArray(dashes) && gap <= 0)
ctx.setLineDash(dashes.map((d) => Number(d) * width));
ctx.stroke();
return;
}
case 'circle': {
if (f.type !== 'Point') return;
const radius = Number(v('circle-radius'));
const stroke = Number(v('circle-stroke-width'));
for (const part of feature.loadGeometry())
for (const p of part) {
const [px, py] = at(p);
ctx.beginPath();
ctx.arc(px, py, radius, 0, Math.PI * 2);
ctx.globalAlpha = Number(v('circle-opacity'));
ctx.fillStyle = String(v('circle-color'));
ctx.fill();
if (stroke > 0) {
ctx.globalAlpha = Number(v('circle-stroke-opacity'));
ctx.strokeStyle = String(v('circle-stroke-color'));
ctx.lineWidth = stroke;
ctx.stroke();
}
}
return;
}
case 'symbol': {
if (!layer.hasText) return;
const field = v('text-field');
// A string (not an expression) names properties as `{name}`.
let text = layer.tokens
? fillTokens(String(field ?? ''), f.properties)
: String(field ?? '');
const transform = v('text-transform');
if (transform === 'uppercase') text = text.toUpperCase();
if (transform === 'lowercase') text = text.toLowerCase();
text = text.trim();
if (!text) return;
const geometry = feature.loadGeometry();
const anchors = [];
if (f.type === 'Point')
for (const part of geometry) for (const p of part) anchors.push(at(p));
else if (f.type === 'LineString') anchors.push(halfway(geometry[0], at));
else {
const ring = geometry[0].map(at);
const xs = ring.map((p) => p[0]);
const ys = ring.map((p) => p[1]);
anchors.push([
(Math.min(...xs) + Math.max(...xs)) / 2,
(Math.min(...ys) + Math.max(...ys)) / 2,
]);
}
const px = Number(v('text-size'));
const offset = layer.values['text-offset'] ? v('text-offset') : [0, 0];
for (const anchor of anchors)
labels.push({
text,
x: anchor[0] + Number(offset?.[0] ?? 0) * px,
y: anchor[1] + Number(offset?.[1] ?? 0) * px,
px,
font: fontOf(v('text-font'), px),
color: String(v('text-color')),
opacity: Number(v('text-opacity')),
halo: String(v('text-halo-color')),
haloWidth: Number(v('text-halo-width')),
anchor: String(
(layer.values['text-anchor'] && v('text-anchor')) ?? 'center',
),
maxWidth:
Number(
(layer.values['text-max-width'] && v('text-max-width')) ?? 10,
) * px,
});
return;
}
}
}
/** Place the labels top layer first, clear of each other, and draw them. */
function placeLabels(ctx, labels, size) {
const placed = [];
// Later in the style is on top, and placed first.
const order = labels.map((label, i) => [label, i]).reverse();
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (const [label] of order) {
ctx.font = label.font;
const lines = wrap(ctx, label.text, label.maxWidth);
if (!lines.length) continue;
const lineHeight = label.px * 1.2;
const width = Math.max(...lines.map((l) => ctx.measureText(l).width));
const height = lineHeight * lines.length;
let cx = label.x;
let cy = label.y;
if (label.anchor.includes('top')) cy += height / 2;
if (label.anchor.includes('bottom')) cy -= height / 2;
if (label.anchor.includes('left')) cx += width / 2;
if (label.anchor.includes('right')) cx -= width / 2;
const pad = label.haloWidth + 1;
const box = [
cx - width / 2 - pad,
cy - height / 2 - pad,
cx + width / 2 + pad,
cy + height / 2 + pad,
];
if (box[0] < 0 || box[1] < 0 || box[2] > size || box[3] > size) continue;
if (placed.some((b) => overlaps(b, box))) continue;
placed.push(box);
ctx.globalAlpha = label.opacity;
lines.forEach((line, i) => {
const ly = cy - height / 2 + lineHeight * (i + 0.5);
if (label.haloWidth > 0) {
ctx.lineWidth = label.haloWidth * 2;
ctx.lineJoin = 'round';
ctx.strokeStyle = label.halo;
ctx.strokeText(line, cx, ly);
}
ctx.fillStyle = label.color;
ctx.fillText(line, cx, ly);
});
}
ctx.globalAlpha = 1;
}
+221
View File
@@ -0,0 +1,221 @@
/**
* @module render/vectorBase/style
* @description Loads a MapLibre style document for the vector base painter:
* its vector sources resolved to tile URL templates (a TileJSON `url`, or
* inline `tiles`), its layers compiled ({@link module:render/vectorBase/expressions}),
* and its background. A layer the painter cannot draw is listed in `skipped`
* with the reason, never drawn wrong.
*/
import { compileFilter, compileValue, Unsupported } from './expressions.js';
/** Layer types the painter draws. */
export const PAINTED_TYPES = Object.freeze([
'background',
'fill',
'line',
'circle',
'symbol',
]);
/** Paint and layout properties that, set, make a layer one not drawn. */
const UNDRAWN = Object.freeze({
fill: ['fill-pattern', 'fill-translate'],
line: ['line-pattern', 'line-offset', 'line-translate', 'line-gradient'],
circle: ['circle-translate'],
symbol: [],
background: ['background-pattern'],
});
/** Properties whose values are arrays. */
const ARRAY_VALUES = new Set([
'text-font',
'text-offset',
'text-translate',
'text-variable-anchor',
'line-dasharray',
'icon-offset',
'icon-translate',
'fill-translate',
'line-translate',
'circle-translate',
]);
/** Defaults the painter reads for each layer type, as the specification's. */
const DEFAULTS = {
background: { 'background-color': '#000000', 'background-opacity': 1 },
fill: { 'fill-color': '#000000', 'fill-opacity': 1 },
line: {
'line-color': '#000000',
'line-opacity': 1,
'line-width': 1,
'line-gap-width': 0,
'line-cap': 'butt',
'line-join': 'miter',
},
circle: {
'circle-radius': 5,
'circle-color': '#000000',
'circle-opacity': 1,
'circle-stroke-width': 0,
'circle-stroke-color': '#000000',
'circle-stroke-opacity': 1,
},
symbol: {
'text-size': 16,
'text-color': '#000000',
'text-opacity': 1,
'text-halo-color': 'rgba(0,0,0,0)',
'text-halo-width': 0,
'text-transform': 'none',
'text-font': ['Open Sans Regular'],
'symbol-placement': 'point',
},
};
/** `url` resolved against `base`; a data or blob URL as it is. */
function resolve(url, base) {
if (/^(data|blob):/i.test(url)) return url;
try {
// A tile template's `{z}`, `{x}` and `{y}` stay as they are.
return new URL(url, base).href.replace(/%7B/gi, '{').replace(/%7D/gi, '}');
} catch {
return url;
}
}
/** A response's JSON, refusing a failed one. */
async function json(fetchImpl, url, signal) {
const response = await fetchImpl(url, { signal });
if (!response.ok)
throw new Error(`${url} answered ${response.status ?? 'an error'}`);
return response.json();
}
/**
* A compiled layer, or a reason it is not drawn.
* @returns {{layer?: object, reason?: string}}
*/
function compileLayer(layer, sources) {
const type = layer.type;
if (!PAINTED_TYPES.includes(type)) return { reason: `${type} layers` };
const layout = layer.layout ?? {};
const paint = layer.paint ?? {};
if (layout.visibility === 'none') return { reason: 'hidden' };
for (const key of UNDRAWN[type])
if (paint[key] !== undefined || layout[key] !== undefined)
return { reason: key };
if (type !== 'background') {
const source = sources[layer.source];
if (!source) return { reason: `source ${layer.source}, not vector` };
if (!layer['source-layer']) return { reason: 'no source-layer' };
}
try {
const values = {};
for (const [key, value] of Object.entries({
...DEFAULTS[type],
...layout,
...paint,
}))
if (key !== 'visibility')
values[key] = compileValue(value, { array: ARRAY_VALUES.has(key) });
return {
layer: {
id: layer.id,
type,
source: layer.source,
sourceLayer: layer['source-layer'],
minzoom: layer.minzoom ?? 0,
maxzoom: layer.maxzoom ?? 24,
filter: compileFilter(layer.filter),
values,
hasText: type === 'symbol' && layout['text-field'] !== undefined,
// A text field not an expression fills `{name}` tokens.
tokens: !Array.isArray(layout['text-field']),
},
};
} catch (error) {
// Unsupported, or not a value the specification allows: not drawn.
return {
reason: error instanceof Unsupported ? error.message : String(error),
};
}
}
/**
* Load a MapLibre style document and the TileJSON its vector sources name.
* @param {string} styleUrl
* @param {typeof fetch} [fetchImpl]
* @param {{signal?: AbortSignal}} [options]
* @returns {Promise<{
* url: string,
* style: object,
* sources: Record<string, {tiles: string[], minzoom: number, maxzoom: number,
* scheme: 'xyz'|'tms', attribution?: string}>,
* layers: object[],
* background: {color: string, opacity: number}|null,
* skipped: Array<{id: string, reason: string}>,
* attribution: string[],
* tiles: Map<string, Promise<object>>,
* }>}
*/
export async function loadVectorStyle(
styleUrl,
fetchImpl = globalThis.fetch,
{ signal } = {},
) {
const style = await json(fetchImpl, styleUrl, signal);
if (!style || typeof style !== 'object' || !Array.isArray(style.layers))
throw new TypeError(`${styleUrl} is not a style document`);
const sources = {};
const attribution = [];
for (const [name, source] of Object.entries(style.sources ?? {})) {
if (source?.type !== 'vector') continue;
let spec = source;
let base = styleUrl;
if (!Array.isArray(source.tiles) && typeof source.url === 'string') {
base = resolve(source.url, styleUrl);
spec = { ...(await json(fetchImpl, base, signal)), ...source };
}
if (!Array.isArray(spec.tiles) || spec.tiles.length === 0) continue;
sources[name] = {
tiles: spec.tiles.map((t) => resolve(t, base)),
minzoom: spec.minzoom ?? 0,
maxzoom: spec.maxzoom ?? 14,
scheme: spec.scheme === 'tms' ? 'tms' : 'xyz',
attribution: spec.attribution,
};
if (spec.attribution) attribution.push(spec.attribution);
}
const layers = [];
const skipped = [];
let background = null;
for (const raw of style.layers) {
const { layer, reason } = compileLayer(raw, sources);
if (!layer) {
skipped.push({ id: raw.id, reason });
continue;
}
layers.push(layer);
if (layer.type === 'background' && !background)
try {
const at = { zoom: 0, properties: {}, type: 'Polygon' };
background = {
color: String(layer.values['background-color'](at)),
opacity: Number(layer.values['background-opacity'](at)),
};
} catch {
background = null;
}
}
return {
url: styleUrl,
style,
sources,
layers,
background,
skipped,
attribution,
// Decoded source tiles by URL, shared by every tile painted.
tiles: new Map(),
};
}
+332
View File
@@ -0,0 +1,332 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
compileExpression,
compileFilter,
compileValue,
loadVectorStyle,
paintVectorTile,
parseColor,
Unsupported,
} from './index.js';
import { encodeVectorTile } from './encode.js';
const feature = (properties = {}, extra = {}) => ({
zoom: 10,
properties,
type: 'Polygon',
...extra,
});
test('filters in both syntaxes', () => {
const legacy = compileFilter([
'all',
['==', 'class', 'water'],
['in', 'kind', 'lake', 'sea'],
['!has', 'hidden'],
['==', '$type', 'Polygon'],
]);
assert.equal(legacy(feature({ class: 'water', kind: 'sea' })), true);
assert.equal(
legacy(feature({ class: 'water', kind: 'sea', hidden: 1 })),
false,
);
assert.equal(legacy(feature({ class: 'water', kind: 'river' })), false);
const expression = compileFilter([
'all',
['==', ['get', 'class'], 'road'],
['>=', ['zoom'], 8],
['match', ['get', 'rank'], [1, 2], true, false],
]);
assert.equal(expression(feature({ class: 'road', rank: 2 })), true);
assert.equal(expression(feature({ class: 'road', rank: 3 })), false);
assert.equal(
expression(feature({ class: 'road', rank: 1 }, { zoom: 5 })),
false,
);
assert.equal(compileFilter(undefined)(feature()), true);
assert.throws(() => compileFilter(['within', {}]), Unsupported);
});
test('values: legacy zoom functions, interpolate, step, case and colours', () => {
const width = compileValue({
base: 2,
stops: [
[10, 1],
[12, 5],
],
});
assert.equal(width(feature({}, { zoom: 9 })), 1);
assert.equal(width(feature({}, { zoom: 12 })), 5);
assert.ok(width(feature({}, { zoom: 11 })) < 3, 'exponential, not linear');
const linear = compileExpression([
'interpolate',
['linear'],
['zoom'],
0,
'#000000',
10,
'#ffffff',
]);
assert.equal(linear(feature({}, { zoom: 5 })), 'rgba(128,128,128,1)');
const step = compileExpression(['step', ['zoom'], 1, 8, 2, 12, 3]);
assert.deepEqual(
[5, 8, 13].map((zoom) => step(feature({}, { zoom }))),
[1, 2, 3],
);
const cased = compileExpression([
'case',
['has', 'name'],
['concat', ['upcase', ['get', 'name']], '!'],
'none',
]);
assert.equal(cased(feature({ name: 'ab' })), 'AB!');
assert.equal(cased(feature()), 'none');
assert.deepEqual(parseColor('#f00'), [255, 0, 0, 1]);
assert.deepEqual(parseColor('rgba(0, 0, 255, 0.5)'), [0, 0, 255, 0.5]);
assert.deepEqual(
parseColor('hsl(120, 100%, 50%)').map(Math.round),
[0, 255, 0, 1],
);
assert.throws(
() =>
compileExpression([
'interpolate',
['cubic-bezier', 0, 0, 1, 1],
['zoom'],
0,
1,
]),
Unsupported,
);
assert.throws(() => compileExpression(['distance', {}]), Unsupported);
});
/** A fetch over a map of URL to body. */
function fetchOver(bodies) {
const asked = [];
const fetch = async (url) => {
asked.push(url);
const body = bodies[url];
if (body === undefined) return { ok: false, status: 404 };
return {
ok: true,
status: 200,
json: async () => body,
arrayBuffer: async () =>
body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength),
};
};
return { fetch, asked };
}
/** A 2D context that records what is drawn. */
function recordingCanvas() {
const calls = [];
const ctx = new Proxy(
{ measureText: (text) => ({ width: text.length * 6 }) },
{
get(target, key) {
if (key in target) return target[key];
return (...args) => calls.push([key, ...args]);
},
set(target, key, value) {
calls.push([`=${String(key)}`, value]);
target[`_${String(key)}`] = value;
return true;
},
},
);
return { canvas: () => ({ getContext: () => ctx }), calls };
}
const FULL = [
[
[0, 0],
[4096, 0],
[4096, 4096],
[0, 4096],
[0, 0],
],
];
const STYLE = {
version: 8,
sources: { base: { type: 'vector', url: 'tiles.json' } },
layers: [
{ id: 'bg', type: 'background', paint: { 'background-color': '#123456' } },
{
id: 'water',
type: 'fill',
source: 'base',
'source-layer': 'water',
filter: ['==', 'class', 'sea'],
paint: { 'fill-color': '#0000ff' },
},
{
id: 'lakes',
type: 'fill',
source: 'base',
'source-layer': 'water',
filter: ['==', ['get', 'class'], 'lake'],
paint: { 'fill-color': ['distance', {}] },
},
{
id: 'roads',
type: 'line',
source: 'base',
'source-layer': 'roads',
minzoom: 1,
paint: { 'line-color': '#ff0000', 'line-width': 4 },
},
{
id: 'patterned',
type: 'fill',
source: 'base',
'source-layer': 'water',
paint: { 'fill-pattern': 'waves' },
},
{ id: 'hills', type: 'hillshade', source: 'dem' },
{
id: 'places',
type: 'symbol',
source: 'base',
'source-layer': 'places',
layout: { 'text-field': '{name}', 'text-size': 12 },
paint: { 'text-color': '#ffffff' },
},
],
};
function fixture() {
const tile = encodeVectorTile({
water: [
{ type: 'Polygon', geometry: FULL, properties: { class: 'sea' } },
{ type: 'Polygon', geometry: FULL, properties: { class: 'lake' } },
],
roads: [
{
type: 'LineString',
geometry: [
[
[0, 2048],
[4096, 2048],
],
],
},
],
places: [
{
type: 'Point',
geometry: [[[2048, 1024]]],
properties: { name: 'Harbour' },
},
],
});
return fetchOver({
'https://example.test/style.json': STYLE,
'https://example.test/tiles.json': {
tiles: ['t/{z}/{x}/{y}.pbf'],
maxzoom: 4,
attribution: 'Example',
},
'https://example.test/t/2/1/1.pbf': tile,
'https://example.test/t/4/5/6.pbf': tile,
});
}
test('a style loads its TileJSON source, compiles its layers, and lists what it skips', async () => {
const { fetch } = fixture();
const style = await loadVectorStyle('https://example.test/style.json', fetch);
assert.deepEqual(style.sources.base.tiles, [
'https://example.test/t/{z}/{x}/{y}.pbf',
]);
assert.equal(style.sources.base.maxzoom, 4);
assert.deepEqual(style.attribution, ['Example']);
assert.deepEqual(style.background, { color: '#123456', opacity: 1 });
assert.deepEqual(
style.skipped.map((s) => s.id),
['lakes', 'patterned', 'hills'],
);
assert.deepEqual(
style.layers.map((l) => l.id),
['bg', 'water', 'roads', 'places'],
);
});
test('a tile paints its background, fills, lines and labels in style order', async () => {
const { fetch } = fixture();
const style = await loadVectorStyle('https://example.test/style.json', fetch);
const { canvas, calls } = recordingCanvas();
await paintVectorTile(style, 2, 1, 1, { size: 256, fetch, canvas });
const set = (key) =>
calls.filter(([k]) => k === `=${key}`).map(([, value]) => value);
assert.deepEqual(set('fillStyle').slice(0, 2), ['#123456', '#0000ff']);
assert.deepEqual(set('strokeStyle'), ['#ff0000']);
assert.deepEqual(set('lineWidth'), [4]);
const text = calls.filter(([k]) => k === 'fillText');
assert.equal(text.length, 1);
assert.deepEqual(text[0].slice(1), ['Harbour', 128, 64]);
// The road runs across the middle.
const path = calls.filter(([k]) => k === 'moveTo' || k === 'lineTo');
assert.deepEqual(path.slice(-2), [
['moveTo', 0, 128],
['lineTo', 256, 128],
]);
});
test('past its maxzoom a source is drawn from its deepest tile, overzoomed', async () => {
const { fetch, asked } = fixture();
const style = await loadVectorStyle('https://example.test/style.json', fetch);
const { canvas, calls } = recordingCanvas();
// Tile 6/21/25 lies in 4/5/6 at its (1, 1) quarter.
await paintVectorTile(style, 6, 21, 25, { size: 256, fetch, canvas });
assert.ok(asked.includes('https://example.test/t/4/5/6.pbf'));
const road = calls.filter(([k]) => k === 'moveTo').at(-1);
// The tile's middle line, four times larger and a quarter in: off this
// tile's top (y = 2 × 256 − 256 = 256 → 512 − 256 × 1).
assert.deepEqual(road, ['moveTo', -256, 256]);
// Painted again: from the decoded tile, not fetched again.
const before = asked.length;
await paintVectorTile(style, 6, 21, 25, { size: 256, fetch, canvas });
assert.equal(asked.length, before);
});
test('a feature whose value cannot be evaluated is left out, the rest drawn', async () => {
const tile = encodeVectorTile({
water: [
{ type: 'Polygon', geometry: FULL, properties: { depth: 'deep' } },
{ type: 'Polygon', geometry: FULL, properties: { depth: 3 } },
],
});
const { fetch } = fetchOver({
'https://example.test/s.json': {
version: 8,
sources: { base: { type: 'vector', tiles: ['/{z}/{x}/{y}'] } },
layers: [
{
id: 'water',
type: 'fill',
source: 'base',
'source-layer': 'water',
paint: {
'fill-opacity': ['/', ['get', 'depth'], 10],
'fill-color': '#00f',
},
},
],
},
'https://example.test/0/0/0': tile,
});
const style = await loadVectorStyle('https://example.test/s.json', fetch);
const { canvas, calls } = recordingCanvas();
await paintVectorTile(style, 0, 0, 0, { fetch, canvas });
assert.equal(calls.filter(([k]) => k === 'fill').length, 1);
assert.deepEqual(
calls
.filter(([k]) => k === '=globalAlpha')
.map(([, v]) => v)
.filter((v) => v !== 1),
[0.3],
);
});