isard 1.3.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +23 -6
  3. package/dist/basemap/basemaps.js +1 -0
  4. package/dist/basemap/basemaps.js.map +1 -1
  5. package/dist/basemap/vectortiles/context.d.ts +43 -0
  6. package/dist/basemap/vectortiles/context.js +6 -0
  7. package/dist/basemap/vectortiles/context.js.map +1 -0
  8. package/dist/basemap/vectortiles/extrusions.d.ts +11 -0
  9. package/dist/basemap/vectortiles/extrusions.js +46 -0
  10. package/dist/basemap/vectortiles/extrusions.js.map +1 -0
  11. package/dist/basemap/vectortiles/labels.d.ts +22 -0
  12. package/dist/basemap/vectortiles/labels.js +225 -0
  13. package/dist/basemap/vectortiles/labels.js.map +1 -0
  14. package/dist/basemap/vectortiles/requests.d.ts +24 -0
  15. package/dist/basemap/vectortiles/requests.js +61 -0
  16. package/dist/basemap/vectortiles/requests.js.map +1 -0
  17. package/dist/basemap/vectortiles/street-wind.d.ts +19 -0
  18. package/dist/basemap/vectortiles/street-wind.js +133 -0
  19. package/dist/basemap/vectortiles/street-wind.js.map +1 -0
  20. package/dist/basemap/vectortiles/style.d.ts +47 -0
  21. package/dist/basemap/vectortiles/style.js +141 -0
  22. package/dist/basemap/vectortiles/style.js.map +1 -0
  23. package/dist/basemap/vectortiles/tiles.d.ts +34 -0
  24. package/dist/basemap/vectortiles/tiles.js +62 -0
  25. package/dist/basemap/vectortiles/tiles.js.map +1 -0
  26. package/dist/basemap/vectortiles/trees.d.ts +19 -0
  27. package/dist/basemap/vectortiles/trees.js +93 -0
  28. package/dist/basemap/vectortiles/trees.js.map +1 -0
  29. package/dist/basemap/vectortiles/vectors.d.ts +20 -0
  30. package/dist/basemap/vectortiles/vectors.js +167 -0
  31. package/dist/basemap/vectortiles/vectors.js.map +1 -0
  32. package/dist/basemap/vectortiles.d.ts +34 -75
  33. package/dist/basemap/vectortiles.js +70 -654
  34. package/dist/basemap/vectortiles.js.map +1 -1
  35. package/dist/basemap/workerpool.js +33 -5
  36. package/dist/basemap/workerpool.js.map +1 -1
  37. package/dist/basemap.worker.js +2 -2
  38. package/dist/basemap.worker.js.map +8 -5
  39. package/dist/bind/layers.js +10 -0
  40. package/dist/bind/layers.js.map +1 -1
  41. package/dist/decoder.worker.js +5 -4
  42. package/dist/decoder.worker.js.map +8 -6
  43. package/dist/engine/decoders.d.ts +4 -8
  44. package/dist/engine/decoders.js +29 -2
  45. package/dist/engine/decoders.js.map +1 -1
  46. package/dist/engine-loader.d.ts +4 -1
  47. package/dist/engine-loader.js +9 -0
  48. package/dist/engine-loader.js.map +1 -1
  49. package/dist/grid-module.d.ts +44 -0
  50. package/dist/grid-module.js +63 -0
  51. package/dist/grid-module.js.map +1 -0
  52. package/dist/grids.d.ts +51 -0
  53. package/dist/grids.js +88 -0
  54. package/dist/grids.js.map +1 -0
  55. package/dist/index.d.ts +10 -1
  56. package/dist/index.js +3 -1
  57. package/dist/index.js.map +1 -1
  58. package/dist/isard_bg.wasm +0 -0
  59. package/dist/isard_core_bg.wasm +0 -0
  60. package/dist/isard_grid_bg.wasm +0 -0
  61. package/dist/layers/flow.d.ts +118 -0
  62. package/dist/layers/flow.js +263 -0
  63. package/dist/layers/flow.js.map +1 -0
  64. package/dist/layers/panoramas.d.ts +2 -0
  65. package/dist/layers/panoramas.js +27 -6
  66. package/dist/layers/panoramas.js.map +1 -1
  67. package/dist/layers/symbols.d.ts +2 -0
  68. package/dist/layers/symbols.js +2 -1
  69. package/dist/layers/symbols.js.map +1 -1
  70. package/dist/map/layer-spec.d.ts +4 -1
  71. package/dist/map/layer-spec.js +2 -0
  72. package/dist/map/layer-spec.js.map +1 -1
  73. package/dist/map/workers.d.ts +4 -0
  74. package/dist/map/workers.js +38 -0
  75. package/dist/map/workers.js.map +1 -1
  76. package/dist/map.d.ts +14 -0
  77. package/dist/map.js +19 -1
  78. package/dist/map.js.map +1 -1
  79. package/dist/react/Layer.d.ts +2 -0
  80. package/dist/react/Layer.js.map +1 -1
  81. package/dist/types.d.ts +7 -3
  82. package/dist/types.js.map +1 -1
  83. package/dist/util/read.d.ts +4 -0
  84. package/dist/util/read.js +28 -0
  85. package/dist/util/read.js.map +1 -0
  86. package/dist/wasm/isard.d.ts +55 -0
  87. package/dist/wasm/isard.js +112 -1
  88. package/dist/wasm/isard_core.d.ts +55 -0
  89. package/dist/wasm/isard_core.js +112 -1
  90. package/dist/wasm/isard_grid.d.ts +101 -0
  91. package/dist/wasm/isard_grid.js +375 -0
  92. package/dist/workers/basemap/street.d.ts +19 -0
  93. package/dist/workers/basemap.worker.d.ts +21 -0
  94. package/dist/workers/basemap.worker.js +23 -4
  95. package/dist/workers/basemap.worker.js.map +1 -1
  96. package/package.json +2 -1
  97. package/vite.js +3 -2
@@ -7,164 +7,21 @@
7
7
  *
8
8
  * Any subset of the style can be drawn on its own raster layer (`raster({ layers })`), at its own place in the stack:
9
9
  * rivers from the basemap's data over a flood layer, for instance, restyled with `extraLayers`.
10
+ *
11
+ * The layers other than the raster ones are made in `vectortiles/` (one module each), from what they use of the
12
+ * instance (`VectorTilesContext`); the style's loading is in `vectortiles/style.ts`.
10
13
  */
11
- import { withHeaders } from "../engine/requests.js";
12
- import { IGN_ATTRIBUTION } from "../geoplateforme.js";
13
- import { loadSprites, readPixels } from "../layers/icons.js";
14
- import { mercatorX, mercatorY } from "../util/geo.js";
15
- import { isRecord } from "../util/guards.js";
16
- import { Lru } from "../util/lru.js";
17
- import { OPENFREEMAP_ATTRIBUTION } from "./basemaps.js";
18
- import { pmtiles, pmtilesUrl } from "./pmtiles.js";
19
- import { isWoodland, TREE_NUMBERS, treeModel, treeSpacing } from "./trees.js";
20
- import { evaluate, isExpression, isStyle, labelFont, vectorKind, zoomOnly, } from "./vectorstyle.js";
14
+ import { loadSprites, spriteSources } from "../layers/icons.js";
15
+ import { extrusions } from "./vectortiles/extrusions.js";
16
+ import { labels, size, tileLabels } from "./vectortiles/labels.js";
17
+ import { streetWind } from "./vectortiles/street-wind.js";
18
+ import { loadStyle, OPENFREEMAP_STYLES, PLAN_STYLES, styleAttribution, VECTOR_BASEMAPS, } from "./vectortiles/style.js";
19
+ import { VECTOR_MOVE_REFRESH_MS } from "./vectortiles/tiles.js";
20
+ import { trees } from "./vectortiles/trees.js";
21
+ import { dashes, vectors } from "./vectortiles/vectors.js";
21
22
  import { rendererKey, tilePriority } from "./workerpool.js";
22
- /** OpenFreeMap's styles: OpenStreetMap data in the OpenMapTiles schema, worldwide, free and without a key */
23
- export const OPENFREEMAP_STYLES = {
24
- positron: 'https://tiles.openfreemap.org/styles/positron',
25
- liberty: 'https://tiles.openfreemap.org/styles/liberty',
26
- bright: 'https://tiles.openfreemap.org/styles/bright',
27
- };
28
- /** PLAN.IGN vector styles of the Géoplateforme (France) */
29
- export const PLAN_STYLES = {
30
- standard: 'https://data.geopf.fr/annexes/ressources/vectorTiles/styles/PLAN.IGN/standard.json',
31
- grey: 'https://data.geopf.fr/annexes/ressources/vectorTiles/styles/PLAN.IGN/gris.json',
32
- };
33
- /** Vector basemaps by name (see `BasemapName`) */
34
- export const VECTOR_BASEMAPS = {
35
- 'osm-positron': OPENFREEMAP_STYLES.positron,
36
- 'osm-liberty': OPENFREEMAP_STYLES.liberty,
37
- 'osm-bright': OPENFREEMAP_STYLES.bright,
38
- 'ign-plan-vector': PLAN_STYLES.standard,
39
- 'ign-plan-grey-vector': PLAN_STYLES.grey,
40
- };
41
- /** The credits of a known style: OpenFreeMap's, PLAN.IGN's */
42
- export const styleAttribution = (style) => {
43
- if (typeof style !== 'string')
44
- return undefined;
45
- if (Object.values(OPENFREEMAP_STYLES).some((s) => s === style))
46
- return OPENFREEMAP_ATTRIBUTION;
47
- if (Object.values(PLAN_STYLES).some((s) => s === style))
48
- return IGN_ATTRIBUTION;
49
- return undefined;
50
- };
51
- /** Text or icon size of a style (a number, legacy stops, or the stops of a zoom expression made by the worker) as a
52
- * size for the symbol layer */
53
- export const size = (value, fallback = 16) => {
54
- const stop = (s) => {
55
- const [z, v] = Array.isArray(s) ? s : [];
56
- return [Number(z), Number(v)];
57
- };
58
- if (typeof value === 'number')
59
- return value;
60
- if (Array.isArray(value) && value.length > 0 && value.every(Array.isArray))
61
- return value.map(stop);
62
- if (isRecord(value) && Array.isArray(value.stops))
63
- return value.stops.map(stop);
64
- return fallback;
65
- };
66
- /** The anchors of the symbol layer */
67
- const ANCHORS = new Set([
68
- 'center',
69
- 'top',
70
- 'bottom',
71
- 'left',
72
- 'right',
73
- 'top-left',
74
- 'top-right',
75
- 'bottom-left',
76
- 'bottom-right',
77
- ]);
78
- const isAnchor = (value) => value !== undefined && ANCHORS.has(value);
79
- /** A style's anchor (`text-anchor`, `icon-anchor`) for the symbol layer: `center` if it is none */
80
- const anchor = (value) => (isAnchor(value) ? value : 'center');
81
- /** Fetches a JSON document (a style, a TileJSON) */
82
- const json = async (url) => {
83
- const response = await fetch(url, withHeaders(url));
84
- if (!response.ok)
85
- throw new Error(`${url}: ${response.status}`);
86
- return response.json();
87
- };
88
- /** A style fetched: a MapLibre style, or an error */
89
- const fetchStyle = async (url) => {
90
- const style = await json(url);
91
- if (!isStyle(style))
92
- throw new Error(`${url}: not a MapLibre style`);
93
- return style;
94
- };
95
- const isTileJson = (value) => isRecord(value) &&
96
- Array.isArray(value.tiles) &&
97
- value.tiles.every((t) => typeof t === 'string') &&
98
- (value.maxzoom === undefined || typeof value.maxzoom === 'number');
99
- /** A TileJSON fetched, or an error */
100
- const fetchTileJson = async (url) => {
101
- const tilejson = await json(url);
102
- if (!isTileJson(tilejson))
103
- throw new Error(`${url}: not a TileJSON`);
104
- return tilejson;
105
- };
106
- /**
107
- * A style source's tiles and deepest level: a `pmtiles://` archive (its `url`, or a `tiles` template) read for its
108
- * header, its tiles then named `pmtiles://<absolute archive URL>/{z}/{x}/{y}` for the workers; other sources as they are
109
- */
110
- const resolveSource = async (source) => {
111
- const given = source.url ?? source.tiles?.[0] ?? '';
112
- const archive = pmtilesUrl(given.replace(/\/\{z\}\/\{x\}\/\{y\}$/, ''));
113
- if (!archive)
114
- return {
115
- ...(source.tiles ? { tiles: source.tiles } : {}),
116
- ...(source.maxzoom === undefined ? {} : { maxzoom: source.maxzoom }),
117
- };
118
- const header = await pmtiles(archive).header();
119
- return { tiles: [`pmtiles://${archive}/{z}/{x}/{y}`], maxzoom: source.maxzoom ?? header.maxZoom };
120
- };
121
- /** Pause before the labels of tiles that failed are asked for again, when no move brings an update (ms) */
122
- const RETRY_LABELS_MS = 3000;
123
- /** The style layers of buildings, by default: PLAN IGN's `bati_surf` (not its built-up areas nor its parks), the
124
- * OpenMapTiles' `building` */
125
- const isBuildings = (layer) => ['bati_surf', 'building'].includes(layer['source-layer'] ?? '');
126
- /**
127
- * The tiles of level `z` in view, within a window around the center (a tilted view's bounds reach far), the
128
- * `maxTiles` nearest to the center first
129
- */
130
- const tilesAround = (map, camera, z, maxTiles) => {
131
- const n = 2 ** z;
132
- const [west, south, east, north] = map.getBounds();
133
- const tx = (lon) => Math.floor(mercatorX(lon) * n);
134
- const ty = (lat) => Math.floor(mercatorY(lat) * n);
135
- const [cx, cy] = [mercatorX(camera.center[0]) * n, mercatorY(camera.center[1]) * n];
136
- const reach = Math.ceil(Math.sqrt(maxTiles)) + 2;
137
- const [x0, x1] = [Math.max(0, tx(west), Math.floor(cx) - reach), Math.min(n - 1, tx(east), Math.floor(cx) + reach)];
138
- const [y0, y1] = [Math.max(0, ty(north), Math.floor(cy) - reach), Math.min(n - 1, ty(south), Math.floor(cy) + reach)];
139
- const wanted = Array.from({ length: Math.max(0, y1 - y0 + 1) }, (_, j) => y0 + j).flatMap((y) => Array.from({ length: Math.max(0, x1 - x0 + 1) }, (_, i) => [x0 + i, y]));
140
- wanted.sort((a, b) => Math.hypot(a[0] + 0.5 - cx, a[1] + 0.5 - cy) - Math.hypot(b[0] + 0.5 - cx, b[1] + 0.5 - cy));
141
- return wanted.slice(0, maxTiles);
142
- };
143
- /** A tile's label candidates as features, by style layer */
144
- export const tileLabels = (candidates) => {
145
- const byLayer = new Map();
146
- candidates.forEach((p) => {
147
- const feature = {
148
- type: 'Feature',
149
- properties: p,
150
- geometry: p.along
151
- ? {
152
- type: 'LineString',
153
- coordinates: [
154
- [p.lon - p.along[0] / 2, p.lat - p.along[1] / 2],
155
- [p.lon + p.along[0] / 2, p.lat + p.along[1] / 2],
156
- ],
157
- }
158
- : { type: 'Point', coordinates: [p.lon, p.lat] },
159
- };
160
- const list = byLayer.get(p.layer);
161
- if (list)
162
- list.push(feature);
163
- else
164
- byLayer.set(p.layer, [feature]);
165
- });
166
- return [...byLayer].sort((a, b) => b[0] - a[0]);
167
- };
23
+ // The names the package and its tests import from here, now made in `vectortiles/`
24
+ export { dashes, OPENFREEMAP_STYLES, PLAN_STYLES, size, styleAttribution, tileLabels, VECTOR_BASEMAPS };
168
25
  export class VectorTiles {
169
26
  map;
170
27
  pool;
@@ -183,6 +40,8 @@ export class VectorTiles {
183
40
  layers = [];
184
41
  /** Its first raster layer: the ground its labels follow */
185
42
  ground;
43
+ /** What its layers made in `vectortiles/` use of it */
44
+ context;
186
45
  /** The style once loaded, with its source resolved */
187
46
  ready;
188
47
  /**
@@ -197,57 +56,49 @@ export class VectorTiles {
197
56
  this.namespace = pool.namespace();
198
57
  const style = options.style ?? OPENFREEMAP_STYLES.positron;
199
58
  this.attribution = options.attribution ?? styleAttribution(style);
200
- this.ready = this.load(style);
59
+ this.ready = loadStyle(style);
201
60
  // Reported once here; `ready`, the raster tiles and the labels fail with it
202
61
  this.ready.catch((error) => {
203
62
  if (!this.destroyed)
204
63
  console.warn('isard: vector tiles', error);
205
64
  });
206
- }
207
- async load(input) {
208
- const style = typeof input === 'string' ? await fetchStyle(input) : input;
209
- const [name, source] = Object.entries(style.sources).find(([, s]) => s.type === 'vector') ?? [];
210
- if (!name || !source)
211
- throw new Error('the style has no vector source');
212
- const resolved = await resolveSource(source);
213
- const tilejson = !resolved.tiles && source.url ? await fetchTileJson(source.url) : undefined;
214
- const tiles = tilejson === undefined ? resolved.tiles : tilejson.tiles;
215
- const maxzoom = resolved.maxzoom ?? tilejson?.maxzoom;
216
- const template = tiles?.[0];
217
- if (!template)
218
- throw new Error(`source ${name} has no tiles`);
219
- // Its raster sources of tiles, drawn into the same images (the shaded relief of a style at low zoom)
220
- const rasters = {};
221
- for (const [key, s] of Object.entries(style.sources)) {
222
- if (s.type !== 'raster')
223
- continue;
224
- const r = await resolveSource(s);
225
- const url = r.tiles?.[0];
226
- if (url)
227
- rasters[key] = { tiles: url, maxzoom: r.maxzoom ?? 22, tileSize: s.tileSize ?? 512 };
228
- }
229
- // Only the layers of those sources (and the background); other types (hillshade, heatmap…) are left out. The
230
- // application's style object stays as it is
231
- const layers = style.layers.filter((l) => l.type === 'background' ||
232
- (l.source === name && l.type !== 'raster') ||
233
- (l.type === 'raster' && l.source !== undefined && rasters[l.source] !== undefined));
234
- return { style: { ...style, layers }, tiles: template, maxzoom: maxzoom ?? 14, rasters };
235
- }
236
- /** The fonts of the style's labels, for its glyphs (the first of each `text-font`, as the workers take it) */
237
- static fonts(style) {
238
- const fonts = new Set();
239
- style.layers.forEach((layer) => {
240
- const font = layer.layout?.['text-font'];
241
- if (layer.type === 'symbol' && Array.isArray(font) && typeof font[0] === 'string')
242
- fonts.add(labelFont(font[0]));
243
- });
244
- return [...fonts];
65
+ this.context = {
66
+ map,
67
+ ready: this.ready,
68
+ layers: this.layers,
69
+ cleanup: this.cleanup,
70
+ iconPrefix: this.iconPrefix,
71
+ destroyed: () => this.destroyed,
72
+ ground: () => this.ground,
73
+ broadcast: (message) => {
74
+ this.pool.broadcast(message);
75
+ },
76
+ request: (vz, vx, vy, work, signal) => this.request(vz, vx, vy, work, signal),
77
+ renderer: (select, extra, again) => this.renderer(select, extra, again),
78
+ loadSprites: (sprite) => this.loadSprites(sprite),
79
+ followView: (update, requests, moving) => {
80
+ this.followView(update, requests, moving);
81
+ },
82
+ };
245
83
  }
246
84
  /** The style's sprites (their JSON and their images), loaded once, for the fill patterns and the icons */
247
85
  sprites;
86
+ /** The style's sprites, kept once all of them came: one that failed is asked for again by the next layer */
248
87
  loadSprites(sprite) {
249
- this.sprites ??= loadSprites(sprite).catch(() => []);
250
- return this.sprites;
88
+ if (this.sprites)
89
+ return this.sprites;
90
+ const wanted = spriteSources(sprite).length;
91
+ const loading = loadSprites(sprite)
92
+ .catch(() => [])
93
+ .then((loaded) => {
94
+ if (loaded.length < wanted && this.sprites === loading) {
95
+ console.warn(`isard: ${wanted - loaded.length} of the style's sprites not loaded, its icons and patterns missing`);
96
+ this.sprites = undefined;
97
+ }
98
+ return loaded;
99
+ });
100
+ this.sprites = loading;
101
+ return loading;
251
102
  }
252
103
  /** Prefix of the names of its sprites' images among the map's icons */
253
104
  get iconPrefix() {
@@ -314,51 +165,21 @@ export class VectorTiles {
314
165
  * leaving the view are dropped.
315
166
  */
316
167
  extrusions(options = {}) {
317
- const { layers = isBuildings, minZoom = 15, maxTiles = 36, ...style } = options;
318
- const extrusions = this.map.addExtrusions(style);
319
- const renderer = this.renderer((l) => (l.type === 'fill' || l.type === 'fill-extrusion') && layers(l), []);
320
- renderer.catch(() => undefined);
321
- this.layers.push(extrusions);
322
- /** The tiles held or asked for, by key */
323
- const held = new Map();
324
- const update = async () => {
325
- if (this.destroyed)
326
- return;
327
- const { key, maxzoom } = await renderer;
328
- const camera = this.map.getCamera();
329
- const z = maxzoom;
330
- const wanted = camera.zoom < minZoom ? [] : tilesAround(this.map, camera, z, maxTiles);
331
- const keys = new Set(wanted.map(([x, y]) => `${z}/${x}/${y}`));
332
- // Out of view: dropped, or no longer asked for
333
- [...held].forEach(([k, controller]) => {
334
- if (keys.has(k))
335
- return;
336
- controller.abort();
337
- held.delete(k);
338
- extrusions.removeTile(k);
339
- });
340
- wanted.forEach(([x, y], index) => {
341
- const k = `${z}/${x}/${y}`;
342
- if (held.has(k))
343
- return;
344
- const controller = new AbortController();
345
- const work = { type: 'polygons', key, z, x, y, priority: index < 4 ? 'auto' : 'low' };
346
- held.set(k, controller);
347
- this.request(z, x, y, work, controller.signal).then((r) => {
348
- if (controller.signal.aborted || !('polygons' in r))
349
- return;
350
- const tile = r.polygons;
351
- // The features' properties as the style reads them
352
- extrusions.setTile(k, { arrays: tile.arrays, properties: tile.properties });
353
- }, () => {
354
- // A failure is asked for again on the next update
355
- if (held.get(k) === controller)
356
- held.delete(k);
357
- });
358
- });
359
- };
360
- this.followView(update, held, update);
361
- return extrusions;
168
+ return extrusions(this.context, options);
169
+ }
170
+ /**
171
+ * The wind through the streets around the view, as particles at street level (`height`, default 3 metres) between
172
+ * the style's buildings (`layers`, default its `building` and `bati_surf` layers): their footprints laid on a grid of
173
+ * `cell` metres (default 4) over a square of `size` metres (default 1200) around the view's center, the flow of the
174
+ * air round them a potential flow (it goes round the blocks and faster through the narrow streets; no wake behind
175
+ * them), computed in a worker by the grid module from street level (`minZoom`, default 15) and again when the view
176
+ * leaves the square's middle. `wind` is the wind far away (east and north, m/s, default a light breeze from the
177
+ * south-west); `setWind` changes it at once (the flow is linear in it: nothing computed again), from a model's hour
178
+ * (`windAt`) for instance; `computed` resolves once the first square's flow is there. The other options are the flow
179
+ * layer's (`addFlow`)
180
+ */
181
+ streetWind(options = {}) {
182
+ return streetWind(this.context, options);
362
183
  }
363
184
  /**
364
185
  * Trees on the style's woods, forests and grass (or the fill layers `layers` keeps) as 3D models, from street level
@@ -371,87 +192,7 @@ export class VectorTiles {
371
192
  * engine with 3D Tiles.
372
193
  */
373
194
  trees(options = {}) {
374
- const { layers = isWoodland, spacing = treeSpacing, minZoom = 15, maxTiles = 9, maxTrees = 30000, maxInstances = 25000, } = options;
375
- const model = options.url ? { url: options.url } : { data: options.data ?? treeModel(options.colors) };
376
- const trees = this.map.addModels({
377
- ...model,
378
- instances: [],
379
- ...(options.before ? { before: options.before } : {}),
380
- });
381
- const renderer = this.renderer((l) => l.type === 'fill' && layers(l), []);
382
- renderer.catch(() => undefined);
383
- this.layers.push(trees);
384
- /** The tiles held or asked for, by key, and the trees of those that came */
385
- const held = new Map();
386
- const found = new Map();
387
- /** The trees drawn to the engine (longitude, latitude, altitude, heading, pitch, roll, scale each): all of them
388
- * near the view's center, past `near` metres those of a rank under (near / distance)², at most `maxInstances` */
389
- const send = () => {
390
- const { center, zoom } = this.map.getCamera();
391
- const near = TREES_NEAR_METRES * 2 ** (16 - zoom);
392
- const metresPerDegree = 111320;
393
- const cos = Math.cos((center[1] * Math.PI) / 180);
394
- const chosen = [];
395
- found.forEach((t) => {
396
- for (let i = 0; i < t.length / TREE_NUMBERS; i += 1) {
397
- const dx = ((t[i * TREE_NUMBERS] ?? 0) - center[0]) * metresPerDegree * cos;
398
- const dy = ((t[i * TREE_NUMBERS + 1] ?? 0) - center[1]) * metresPerDegree;
399
- const far = (dx * dx + dy * dy) / (near * near);
400
- const score = (t[i * TREE_NUMBERS + 4] ?? 0) * Math.max(1, far);
401
- if (score < 1)
402
- chosen.push([score, t, i]);
403
- }
404
- });
405
- if (chosen.length > maxInstances)
406
- chosen.sort((a, b) => a[0] - b[0]).splice(maxInstances);
407
- const out = new Float64Array(chosen.length * 7);
408
- chosen.forEach(([, t, i], k) => {
409
- const at = i * TREE_NUMBERS;
410
- out.set([t[at] ?? 0, t[at + 1] ?? 0, 0, t[at + 3] ?? 0, 0, 0, t[at + 2] ?? 1], k * 7);
411
- });
412
- trees.setInstanceNumbers(out);
413
- };
414
- const update = async () => {
415
- if (this.destroyed)
416
- return;
417
- const { key, maxzoom, layers: list } = await renderer;
418
- const camera = this.map.getCamera();
419
- const z = maxzoom;
420
- const wanted = camera.zoom < minZoom ? [] : tilesAround(this.map, camera, z, maxTiles);
421
- const keys = new Set(wanted.map(([x, y]) => `${z}/${x}/${y}`));
422
- const metres = list.map((l) => (typeof spacing === 'number' ? spacing : spacing(l)));
423
- const dropped = [...held.keys()].filter((k) => !keys.has(k));
424
- // Out of view: dropped, or no longer asked for
425
- dropped.forEach((k) => {
426
- held.get(k)?.abort();
427
- held.delete(k);
428
- found.delete(k);
429
- });
430
- // Dense around the new center
431
- send();
432
- wanted.forEach(([x, y], index) => {
433
- const k = `${z}/${x}/${y}`;
434
- if (held.has(k))
435
- return;
436
- const controller = new AbortController();
437
- const priority = index < 4 ? 'auto' : 'low';
438
- const work = { type: 'trees', key, z, x, y, spacing: metres, maxTrees, priority };
439
- held.set(k, controller);
440
- this.request(z, x, y, work, controller.signal).then((r) => {
441
- if (controller.signal.aborted || !('trees' in r))
442
- return;
443
- found.set(k, r.trees);
444
- send();
445
- }, () => {
446
- // A failure is asked for again on the next update
447
- if (held.get(k) === controller)
448
- held.delete(k);
449
- });
450
- });
451
- };
452
- // While the camera moves, the trees drawn follow its center (dense near it)
453
- this.followView(update, held, send);
454
- return trees;
195
+ return trees(this.context, options);
455
196
  }
456
197
  /**
457
198
  * A layer drawing the style's fills, lines and buildings (or those `layers` keeps; backgrounds as fills, the
@@ -469,146 +210,7 @@ export class VectorTiles {
469
210
  * a road, not its casing, a railway, a path or a tunnel).
470
211
  */
471
212
  vectors(options = {}) {
472
- const { layers = () => true, streets = isStreet, before } = options;
473
- const vector = this.map.addVectorLayer(before);
474
- const state = { renderer: this.renderer((l) => vectorKind(l) !== undefined && layers(l), []), update: 0, style: 0 };
475
- state.renderer.catch(() => undefined);
476
- this.layers.push(vector);
477
- const sublayers = (list) => {
478
- const zoom = this.map.getCamera().zoom;
479
- return list.map((l) => ({
480
- id: l.id,
481
- sourceLayer: l['source-layer'],
482
- kind: vectorKind(l) ?? 'fill',
483
- minZoom: l.minzoom ?? 0,
484
- maxZoom: l.maxzoom ?? 24,
485
- visible: l.layout?.visibility !== 'none',
486
- opacity: zoomOnly(l.paint?.[`${l.type}-opacity`], 1) ?? 1,
487
- cap: lineCap(l.layout?.['line-cap'], zoom),
488
- lit: l.type === 'line' && streets(l),
489
- dash: l.type === 'line' ? dashes(l.paint?.['line-dasharray'], zoom) : [0, 0, 0, 0],
490
- }));
491
- };
492
- /** The tiles held or asked for, by `z/x/y` */
493
- const held = new Map();
494
- /** A tile's geometry, or its styles alone, asked of the worker of its tile of the source's level (which keeps the
495
- * decoded tile its deeper tiles are cut from) */
496
- const ask = ({ key, maxzoom }, [z = 0, x = 0, y = 0], styles, priority, signal) => {
497
- const d = Math.max(0, z - maxzoom);
498
- const work = { type: 'vectors', key, z, x, y, deepest: deepestLevel(maxzoom), priority };
499
- // The geometry made ready for the GPU in the workers, with the prisms the relief needs
500
- return this.request(z - d, Math.floor(x / 2 ** d), Math.floor(y / 2 ** d), styles ? { ...work, styles } : { ...work, prism: this.map.hasRelief }, signal);
501
- };
502
- // The workers tessellate the tiles (the main thread only uploads them), once they know the module
503
- this.pool.broadcast({ type: 'tess', url: this.map.tessUrl });
504
- /** The styles of a tile held asked for again, the tile kept as it is */
505
- const restyleTile = async (renderer, k) => {
506
- const r = await ask(renderer, k.split('/').map(Number), true, 'auto').catch(() => undefined);
507
- if (r && 'styles' in r)
508
- vector.setTileStyles(k, r.styles);
509
- };
510
- const update = async () => {
511
- if (this.destroyed)
512
- return;
513
- const generation = ++state.update;
514
- const { key, maxzoom, layers: list } = await state.renderer;
515
- vector.setSublayers(sublayers(state.own ?? list));
516
- const view = this.map.engine.vectorTilesInView(0, deepestLevel(maxzoom));
517
- const wanted = Array.from({ length: Math.floor(view.length / 3) }, (_, i) => [
518
- ...view.subarray(i * 3, i * 3 + 3),
519
- ]);
520
- const keys = new Set(wanted.map((t) => t.join('/')));
521
- const loads = wanted.flatMap((t, index) => {
522
- const k = t.join('/');
523
- if (held.has(k))
524
- return [];
525
- const controller = new AbortController();
526
- const style = state.style;
527
- held.set(k, controller);
528
- return [
529
- ask({ key, maxzoom }, t, false, index < 4 ? 'high' : 'auto', controller.signal).then(async (r) => {
530
- if (controller.signal.aborted || !('vectors' in r))
531
- return;
532
- vector.setTile(k, r.vectors);
533
- // Cut under a style changed since: its styles asked for again
534
- if (style !== state.style)
535
- await restyleTile(await state.renderer, k);
536
- }, () => {
537
- // A failure is asked for again on the next update
538
- if (held.get(k) === controller)
539
- held.delete(k);
540
- }),
541
- ];
542
- });
543
- // Out of view: those still asked for go at once, those drawn once their replacements are there (no hole)
544
- const drop = (drawn) => {
545
- const shown = new Set(vector.tileKeys);
546
- [...held].forEach(([k, controller]) => {
547
- if (keys.has(k) || shown.has(k) !== drawn)
548
- return;
549
- controller.abort();
550
- held.delete(k);
551
- vector.removeTile(k);
552
- });
553
- };
554
- drop(false);
555
- await Promise.all(loads);
556
- // A later update (the view moved again meanwhile) drops for its own view: these keys are no longer the view
557
- if (!this.destroyed && generation === state.update)
558
- drop(true);
559
- };
560
- const refresh = () => {
561
- update().catch(() => undefined);
562
- };
563
- /** The style layers changed: the workers' copy, then the styles of the tiles held */
564
- const restyle = async (list) => {
565
- state.own = list;
566
- state.style++;
567
- state.renderer = state.renderer.then(({ key }) => this.renderer(() => false, list, key));
568
- const renderer = await state.renderer;
569
- vector.setSublayers(sublayers(list));
570
- await Promise.all(vector.tileKeys.map((k) => restyleTile(renderer, k)));
571
- };
572
- vector.restyle = (id, group, name, value) => {
573
- state.renderer
574
- .then(({ layers: list }) => {
575
- const next = (state.own ?? list).map((l) => l.id === id ? { ...l, [group]: { ...l[group], [name]: value } } : l);
576
- // Visibility and dashes are the engine's: the tiles stay as they are
577
- if ((group === 'layout' && name === 'visibility') || name === 'line-dasharray') {
578
- state.own = next;
579
- vector.setSublayers(sublayers(next));
580
- return undefined;
581
- }
582
- // An outline added or taken away: a feature more or less in each tile, cut again
583
- if (name === 'fill-outline-color' || name === 'fill-antialias') {
584
- state.own = next;
585
- state.style++;
586
- state.renderer = state.renderer.then(({ key }) => this.renderer(() => false, next, key));
587
- vector.setSublayers(sublayers(next));
588
- vector.recut?.();
589
- return undefined;
590
- }
591
- return restyle(next);
592
- })
593
- .catch(() => undefined);
594
- };
595
- vector.recut = () => {
596
- held.forEach((controller) => {
597
- controller.abort();
598
- });
599
- held.clear();
600
- refresh();
601
- };
602
- vector.styled = state.renderer.then(({ layers: list }) => {
603
- if (!this.destroyed)
604
- vector.setSublayers(sublayers(state.own ?? list));
605
- });
606
- // Reported by the style's `ready`
607
- vector.styled.catch(() => undefined);
608
- // While the camera moves, the tiles follow it (as the labels do: a long drag or flight does not leave the view of
609
- // its start drawn)
610
- this.followView(update, held, update);
611
- return vector;
213
+ return vectors(this.context, options);
612
214
  }
613
215
  /**
614
216
  * A symbol layer with the labels of the style's symbol layers (or those `layers` keeps), updated as the view
@@ -618,166 +220,13 @@ export class VectorTiles {
618
220
  * the center at the zoom of the view. It stays above the layers added after it unless one is moved over it.
619
221
  */
620
222
  labels(options = {}) {
621
- const { layers = () => true, maxTiles = 36 } = options;
622
- const symbol = this.map.addSymbols({
623
- data: [],
624
- text: (p) => p.text,
625
- font: (p) => p.font,
626
- size: (p) => size(p.size),
627
- color: (p) => p.color,
628
- haloColor: (p) => p.haloColor,
629
- haloWidth: (p) => p.haloWidth,
630
- anchor: (p) => anchor(p.anchor),
631
- offset: (p) => p.offset,
632
- maxWidth: (p) => p.maxWidth,
633
- lineHeight: (p) => p.lineHeight,
634
- overlap: (p) => p.overlap,
635
- placement: (p) => (p.textAlong ? 'line' : 'point'),
636
- textOptional: (p) => p.textOptional === true,
637
- icon: (p) => (p.icon ? this.iconPrefix + p.icon.image : ''),
638
- iconSize: (p) => size(p.icon?.size ?? 1, 1),
639
- iconAnchor: (p) => anchor(p.icon?.anchor),
640
- iconOffset: (p) => p.icon?.offset ?? [0, 0],
641
- iconRotate: (p) => p.icon?.rotate ?? 0,
642
- iconRotationAlignment: (p) => p.icon?.alignment ?? 'viewport',
643
- iconOverlap: (p) => p.icon?.overlap ?? false,
644
- iconOptional: (p) => p.icon?.optional ?? false,
645
- iconTextFit: (p) => p.icon?.fit ?? 'none',
646
- iconTextFitPadding: (p) => p.icon?.padding ?? [0, 0, 0, 0],
647
- iconColor: (p) => p.icon?.color ?? '#000',
648
- iconOpacity: (p) => p.icon?.opacity ?? 1,
649
- });
650
- this.map.keepOnTop(symbol);
651
- this.layers.push(symbol);
652
- const renderer = this.ready.then(async ({ style }) => {
653
- // The style's fonts from its own glyphs
654
- if (style.glyphs)
655
- this.map.glyphs.register(style.glyphs, VectorTiles.fonts(style));
656
- // Its icons from its sprites, before the first labels
657
- const icons = style.layers.some((l) => l.type === 'symbol' && l.layout?.['icon-image'] !== undefined);
658
- if (icons && style.sprite) {
659
- (await this.loadSprites(style.sprite)).forEach((sprite) => {
660
- if (!this.destroyed)
661
- this.map.icons.addSprite(this.iconPrefix, sprite.icons, () => readPixels(sprite.image));
662
- });
663
- }
664
- return this.renderer((l) => l.type === 'symbol' && layers(l), []);
665
- });
666
- renderer.catch(() => undefined);
667
- /** The labels of the tiles, as features by style layer, the higher layers first: each list is given to the symbol
668
- * layer as a group, shaped once while the tile is kept */
669
- const tiles = new Lru(256);
670
- let generation = 0;
671
- /** The tiles whose labels are shown */
672
- let shown = '';
673
- /** The update asked again after tiles failed */
674
- let retry = 0;
675
- const update = async () => {
676
- if (this.destroyed)
677
- return;
678
- const { key, maxzoom } = await renderer;
679
- const run = ++generation;
680
- const camera = this.map.getCamera();
681
- const zoom = Math.max(0, Math.min(Math.floor(camera.zoom), 24));
682
- const ground = this.ground && this.map.hasLayer(this.ground) ? this.map.engine.wantedTiles(this.ground.id) : [];
683
- const keys = [];
684
- if (ground.length > 0) {
685
- // The ground's tiles, the nearest first: a tile so many levels coarser than the finest in view has its
686
- // labels of a zoom as many under the view's, past the source's deepest level those of that level at the zoom
687
- const groundTiles = Array.from({ length: Math.ceil(ground.length / 3) }, (_, k) => [
688
- ground[3 * k] ?? 0,
689
- ground[3 * k + 1] ?? 0,
690
- ground[3 * k + 2] ?? 0,
691
- ]);
692
- const top = groundTiles.reduce((t, [z]) => Math.max(t, z), 0);
693
- groundTiles.forEach(([z, x, y]) => {
694
- if (keys.length >= maxTiles)
695
- return;
696
- const at = Math.max(0, zoom - (top - z));
697
- const tz = Math.min(at, maxzoom, z);
698
- const shift = 2 ** (z - tz);
699
- const key = `${tz}/${Math.floor(x / shift)}/${Math.floor(y / shift)}${at > tz ? `@${at}` : ''}`;
700
- if (!keys.includes(key))
701
- keys.push(key);
702
- });
703
- }
704
- else {
705
- const z = Math.min(zoom, maxzoom);
706
- const wanted = tilesAround(this.map, camera, z, maxTiles);
707
- // Past the source's deepest level, its tiles' labels at the zoom of the view (the layers of the deeper zooms)
708
- keys.push(...wanted.map(([x, y]) => `${z}/${x}/${y}${zoom > z ? `@${zoom}` : ''}`));
709
- }
710
- // The same tiles as the labels shown: nothing to do
711
- const set = keys.join(' ');
712
- if (set === shown)
713
- return;
714
- const lists = await Promise.all(keys.map((k, index) => {
715
- const cached = tiles.get(k);
716
- if (cached)
717
- return cached;
718
- const [tile, deeper] = k.split('@');
719
- const [tz = 0, x = 0, y = 0] = (tile ?? '').split('/').map(Number);
720
- // The nearest tiles first: the others wait for the raster tiles
721
- const priority = index < 4 ? 'auto' : 'low';
722
- const work = {
723
- type: 'labels',
724
- key,
725
- z: tz,
726
- x,
727
- y,
728
- priority,
729
- ...(deeper === undefined ? {} : { zoom: Number(deeper) }),
730
- };
731
- const p = this.request(tz, x, y, work).then((r) => tileLabels('labels' in r ? r.labels : []), () => {
732
- // A network error is not kept: the tile is asked for again on the next update
733
- tiles.delete(k);
734
- return [];
735
- });
736
- // A bounded cache of tiles' labels, the least recently used dropped
737
- tiles.set(k, p);
738
- return p;
739
- }));
740
- if (run !== generation || this.destroyed)
741
- return;
742
- // A tile that failed is missing: the next update asks for it again, after a pause if no move brings one
743
- shown = keys.every((k) => tiles.has(k)) ? set : '';
744
- if (shown === '' && !retry) {
745
- retry = window.setTimeout(() => {
746
- retry = 0;
747
- refresh();
748
- }, RETRY_LABELS_MS);
749
- }
750
- // The labels of the higher style layers first: they win the collisions; for each style layer, the tiles nearest
751
- // to the center first
752
- const layerIds = [...new Set(lists.flatMap((list) => list.map(([layer]) => layer)))].sort((a, b) => b - a);
753
- const groups = layerIds.flatMap((layer) => lists.map((list) => list.find(([l]) => l === layer)?.[1]).filter((group) => group !== undefined));
754
- symbol.setGroups(groups);
755
- };
756
- // The style failed to load: reported by `ready`
757
- const refresh = () => {
758
- update().catch(() => undefined);
759
- };
760
- let timer = 0;
761
- const schedule = () => {
762
- if (timer)
763
- return;
764
- timer = window.setTimeout(() => {
765
- timer = 0;
766
- refresh();
767
- }, 250);
768
- };
769
- this.cleanup.push(this.map.on('move', schedule), this.map.on('moveend', refresh), () => {
770
- clearTimeout(timer);
771
- clearTimeout(retry);
772
- });
773
- refresh();
774
- return symbol;
223
+ return labels(this.context, options);
775
224
  }
776
225
  /**
777
226
  * Makes a layer's tiles follow the view: `update` now and where the camera stops (`moveend`), `moving` every
778
- * `VECTOR_MOVE_REFRESH_MS` while it moves; the requests `held` aborted when destroyed
227
+ * `VECTOR_MOVE_REFRESH_MS` while it moves; the `requests` aborted when destroyed
779
228
  */
780
- followView(update, held, moving) {
229
+ followView(update, requests, moving) {
781
230
  const refresh = () => {
782
231
  update().catch(() => undefined);
783
232
  };
@@ -792,10 +241,7 @@ export class VectorTiles {
792
241
  };
793
242
  this.cleanup.push(this.map.on('move', follow), this.map.on('moveend', refresh), () => {
794
243
  clearTimeout(pace.timer);
795
- held.forEach((controller) => {
796
- controller.abort();
797
- });
798
- held.clear();
244
+ requests.abortAll();
799
245
  });
800
246
  refresh();
801
247
  }
@@ -836,34 +282,4 @@ export class VectorTiles {
836
282
  this.renderers.length = 0;
837
283
  }
838
284
  }
839
- /**
840
- * A `line-dasharray` as the engine takes it: two dashes and gaps in line widths (an odd count repeated, as the
841
- * canvas's `setLineDash`; past four, the first four), zeros for a solid line
842
- */
843
- export const dashes = (value, zoom) => {
844
- const v = isExpression(value) ? evaluate(value, { zoom, properties: {}, type: 'Unknown' }) : value;
845
- const list = Array.isArray(v) ? v.map(Number).filter((d) => Number.isFinite(d) && d >= 0) : [];
846
- const even = list.length % 2 === 1 ? [...list, ...list] : list;
847
- const [a = 0, b = 0, c = 0, d = 0] = even.length >= 2 && even.some((x) => x > 0) ? even : [];
848
- return [a, b, c, d];
849
- };
850
- /** Metres around the view's center where every tree is drawn at zoom 16 (twice as far a zoom level out) */
851
- const TREES_NEAR_METRES = 350;
852
- /** Whether a style layer draws streets, which glow at night: its id names a road (OpenMapTiles' styles, PLAN IGN's),
853
- * not its casing, a railway, a path or a tunnel */
854
- const isStreet = (layer) => /road|highway|street|motorway|trunk|primary|secondary|tertiary|minor|routier/i.test(layer.id) &&
855
- !/casing|outline|rail|path|track|ferry|tunnel|pier|area|pattern|label/i.test(layer.id);
856
- /** A `line-cap` as the engine draws it, at the camera's zoom (MapLibre's default: butt) */
857
- const lineCap = (value, zoom) => {
858
- const v = isExpression(value) ? evaluate(value, { zoom, properties: {}, type: 'Unknown' }) : value;
859
- return v === 'round' || v === 'square' ? v : 'butt';
860
- };
861
- /** The deepest level `vectors()` cuts its tiles at: past the source's deepest level, its tiles cut again into deeper
862
- * ones (overzoom, as MapLibre does) down to level 18, their filters and styles those of their level, smaller tiles
863
- * drawn in a closer view; past it, the tiles of that level stretched */
864
- const OVERZOOM_LEVEL = 18;
865
- /** The deepest level of the tiles of `vectors()` over a source whose deepest is `maxzoom` */
866
- const deepestLevel = (maxzoom) => Math.max(maxzoom, OVERZOOM_LEVEL);
867
- /** Milliseconds between two updates of the tiles of `vectors()` while the camera moves */
868
- const VECTOR_MOVE_REFRESH_MS = 250;
869
285
  //# sourceMappingURL=vectortiles.js.map