isard 0.0.0-stage → 0.2.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 (84) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/LICENSE +21 -0
  3. package/README.md +150 -2
  4. package/dist/basemap.worker.d.ts +66 -0
  5. package/dist/basemap.worker.js +4 -0
  6. package/dist/basemap.worker.js.map +13 -0
  7. package/dist/basemaps.d.ts +46 -0
  8. package/dist/basemaps.js +95 -0
  9. package/dist/basemaps.js.map +1 -0
  10. package/dist/color.d.ts +8 -0
  11. package/dist/color.js +98 -0
  12. package/dist/color.js.map +1 -0
  13. package/dist/controls.d.ts +43 -0
  14. package/dist/controls.js +115 -0
  15. package/dist/controls.js.map +1 -0
  16. package/dist/decoder.worker.js +6 -0
  17. package/dist/decoder.worker.js.map +12 -0
  18. package/dist/decoders.d.ts +27 -0
  19. package/dist/decoders.js +109 -0
  20. package/dist/decoders.js.map +1 -0
  21. package/dist/equirectangular.d.ts +35 -0
  22. package/dist/equirectangular.js +113 -0
  23. package/dist/equirectangular.js.map +1 -0
  24. package/dist/extrusions.d.ts +79 -0
  25. package/dist/extrusions.js +215 -0
  26. package/dist/extrusions.js.map +1 -0
  27. package/dist/features.d.ts +159 -0
  28. package/dist/features.js +387 -0
  29. package/dist/features.js.map +1 -0
  30. package/dist/geoplateforme.d.ts +35 -0
  31. package/dist/geoplateforme.js +56 -0
  32. package/dist/geoplateforme.js.map +1 -0
  33. package/dist/glyphs.d.ts +104 -0
  34. package/dist/glyphs.js +383 -0
  35. package/dist/glyphs.js.map +1 -0
  36. package/dist/index.d.ts +34 -0
  37. package/dist/index.js +25 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/interaction.d.ts +50 -0
  40. package/dist/interaction.js +243 -0
  41. package/dist/interaction.js.map +1 -0
  42. package/dist/isard_bg.wasm +0 -0
  43. package/dist/isard_core_bg.wasm +0 -0
  44. package/dist/layers.d.ts +100 -0
  45. package/dist/layers.js +281 -0
  46. package/dist/layers.js.map +1 -0
  47. package/dist/loader.d.ts +30 -0
  48. package/dist/loader.js +102 -0
  49. package/dist/loader.js.map +1 -0
  50. package/dist/map.d.ts +203 -0
  51. package/dist/map.js +1083 -0
  52. package/dist/map.js.map +1 -0
  53. package/dist/mvt.d.ts +19 -0
  54. package/dist/mvt.js +231 -0
  55. package/dist/mvt.js.map +1 -0
  56. package/dist/overlay.d.ts +118 -0
  57. package/dist/overlay.js +334 -0
  58. package/dist/overlay.js.map +1 -0
  59. package/dist/protocol.d.ts +30 -0
  60. package/dist/protocol.js +2 -0
  61. package/dist/protocol.js.map +1 -0
  62. package/dist/style.d.ts +7 -0
  63. package/dist/style.js +130 -0
  64. package/dist/style.js.map +1 -0
  65. package/dist/symbols.d.ts +61 -0
  66. package/dist/symbols.js +238 -0
  67. package/dist/symbols.js.map +1 -0
  68. package/dist/terrain.d.ts +14 -0
  69. package/dist/terrain.js +44 -0
  70. package/dist/terrain.js.map +1 -0
  71. package/dist/types.d.ts +304 -0
  72. package/dist/types.js +2 -0
  73. package/dist/types.js.map +1 -0
  74. package/dist/vectorstyle.d.ts +83 -0
  75. package/dist/vectorstyle.js +518 -0
  76. package/dist/vectorstyle.js.map +1 -0
  77. package/dist/vectortiles.d.ts +121 -0
  78. package/dist/vectortiles.js +507 -0
  79. package/dist/vectortiles.js.map +1 -0
  80. package/dist/wasm/isard.d.ts +611 -0
  81. package/dist/wasm/isard.js +2606 -0
  82. package/dist/wasm/isard_core.d.ts +468 -0
  83. package/dist/wasm/isard_core.js +2360 -0
  84. package/package.json +49 -4
package/dist/map.js ADDED
@@ -0,0 +1,1083 @@
1
+ /**
2
+ * The map: canvas, camera, layers, events and the frame loop. Frames are drawn on demand only: an idle map costs
3
+ * nothing. Hover events are coalesced to one per frame, so the values computed for a mouse position are drawn in the
4
+ * same frame.
5
+ */
6
+ import { BASEMAPS, BODY_TERRAINS, basemapName, HILLSHADE, IGN_ATTRIBUTION, IMAGE_SERVER, imageServerTerrain, SEA, TERRAIN_TILES, TERRAIN_TILES_ATTRIBUTION, TERRAIN_URL, } from "./basemaps.js";
7
+ import { parseCssColor } from "./color.js";
8
+ import { AttributionControl } from "./controls.js";
9
+ import { DEFAULT_DECODERS } from "./decoders.js";
10
+ import { equirectangularLoader } from "./equirectangular.js";
11
+ import { ExtrusionLayer, extrusionStyle } from "./extrusions.js";
12
+ import { CircleLayer, circleStyle, FillLayer, fillStyle, LineLayer, lineStyle, } from "./features.js";
13
+ import { Glyphs } from "./glyphs.js";
14
+ import { Interaction } from "./interaction.js";
15
+ import { GroundLayer, NetworkLayer, RasterLayer, Tiles3dLayer } from "./layers.js";
16
+ import { TileLoader } from "./loader.js";
17
+ import { injectStyle } from "./style.js";
18
+ import { SymbolLayer, symbolStyle } from "./symbols.js";
19
+ import { encodedTerrainLoader } from "./terrain.js";
20
+ import { BasemapWorkers, defaultWorkerCount, defaultWorkerUrl, VECTOR_BASEMAPS, VectorTiles, } from "./vectortiles.js";
21
+ /** The engine of a destroyed map: every method a no-op returning undefined, but the camera (the last one) and the
22
+ * bounds, which late callers read */
23
+ function destroyed(camera) {
24
+ return new Proxy({}, {
25
+ get: (_, name) => {
26
+ if (name === 'camera')
27
+ return () => camera;
28
+ if (name === 'bounds')
29
+ return () => Float64Array.of(-180, -85, 180, 85);
30
+ return () => undefined;
31
+ },
32
+ });
33
+ }
34
+ /** Reports an error without throwing it here: the console shows it, as an uncaught one */
35
+ function report(error) {
36
+ if (typeof reportError === 'function')
37
+ reportError(error);
38
+ else
39
+ queueMicrotask(() => {
40
+ throw error;
41
+ });
42
+ }
43
+ /** The two builds of the engine, each compiled once per page: `core` without 3D Tiles (a third smaller), loaded by
44
+ * every map; `full` with them, loaded for the first 3D Tiles layer, its module shared with the decoding workers. The
45
+ * core engine has the same API but the 3D Tiles methods: its class is typed as the full one. */
46
+ const engines = {};
47
+ function loadEngine(kind, url) {
48
+ const loaded = engines[kind];
49
+ if (loaded)
50
+ return loaded;
51
+ const loading = (async () => {
52
+ // The bindings by dynamic import: an application bundles the ones it loads only
53
+ const [module, bindings] = await Promise.all([
54
+ compile(url),
55
+ kind === 'core' ? import('./wasm/isard_core.js') : import('./wasm/isard.js'),
56
+ ]);
57
+ await bindings.default({ module_or_path: module });
58
+ return { module, Engine: bindings.Engine };
59
+ })().catch((error) => {
60
+ // A later call tries again (a network error, a wrong URL fixed)
61
+ delete engines[kind];
62
+ throw error;
63
+ });
64
+ engines[kind] = loading;
65
+ return loading;
66
+ }
67
+ async function compile(url) {
68
+ const response = await fetch(url);
69
+ if (!response.ok)
70
+ throw new Error(`isard: failed to load the engine from ${url}: ${response.status}`);
71
+ try {
72
+ return await WebAssembly.compileStreaming(response.clone());
73
+ }
74
+ catch {
75
+ // Servers that do not send application/wasm
76
+ return WebAssembly.compile(await response.arrayBuffer());
77
+ }
78
+ }
79
+ /** Checks a network's arrays before the engine reads them: node index pairs, indices of existing nodes */
80
+ function validateNetwork(nodes, edges) {
81
+ if (nodes.length % 2 !== 0)
82
+ throw new Error(`isard: network nodes must be lon, lat pairs (length ${nodes.length})`);
83
+ if (edges.length % 2 !== 0)
84
+ throw new Error(`isard: network edges must be node index pairs (length ${edges.length})`);
85
+ const count = nodes.length / 2;
86
+ for (let i = 0; i < edges.length; i += 1) {
87
+ const node = edges[i];
88
+ if (node >= count)
89
+ throw new Error(`isard: network edge ${i >> 1} refers to node ${node}, of ${count} nodes`);
90
+ }
91
+ }
92
+ /** The named bodies; a body's `color` is that of its globe under the tiles (the Earth's follows its basemap), its
93
+ * `relief` the range of its ground (the Earth's dry land, from the Dead Sea to Everest). Mars: the sphere of its
94
+ * equatorial radius (its data take planetocentric latitudes), a faint butterscotch halo of dust */
95
+ const BODIES = {
96
+ earth: { radius: 6378137, flattening: 1 / 298.257223563, atmosphere: true, color: '#cacaca', relief: [-450, 8900] },
97
+ moon: { radius: 1737400, flattening: 0, atmosphere: false, color: '#77756f', relief: [-9200, 10800] },
98
+ mars: {
99
+ radius: 3396190,
100
+ flattening: 0,
101
+ atmosphere: 'rgba(232, 168, 120, 0.6)',
102
+ color: '#b5714a',
103
+ relief: [-8300, 21300],
104
+ },
105
+ };
106
+ /** The Earth's halo, RGB 0-1 and its strength: what `atmosphere: true` draws */
107
+ const EARTH_HALO = Float32Array.of(0.42, 0.66, 1, 1);
108
+ /** A body from the option, its defaults filled in */
109
+ function bodySettings(body) {
110
+ if (body === undefined || typeof body === 'string')
111
+ return BODIES[body ?? 'earth'];
112
+ const relief = [-0.01 * body.radius, 0.01 * body.radius];
113
+ return { flattening: 0, atmosphere: false, color: '#808080', relief, ...body };
114
+ }
115
+ /** The halo of an atmosphere for the engine (RGB 0-1 and its strength, the color's alpha): undefined for none */
116
+ function haloSettings(atmosphere) {
117
+ if (atmosphere === true)
118
+ return EARTH_HALO;
119
+ const color = atmosphere === false ? undefined : parseCssColor(atmosphere);
120
+ return color && Float32Array.from(color);
121
+ }
122
+ /** The loaders of the relief by encoding, URL and floor: the same loader for the same tiles (the engine keeps its
123
+ * tiles when only the exaggeration changes) */
124
+ const terrainLoaders = new Map();
125
+ function terrainLoader(url, encoding, floor) {
126
+ const key = `${encoding} ${floor ?? ''} ${url}`;
127
+ let loader = terrainLoaders.get(key);
128
+ if (!loader) {
129
+ loader = encodedTerrainLoader(url, encoding, floor);
130
+ terrainLoaders.set(key, loader);
131
+ }
132
+ return loader;
133
+ }
134
+ /** Relief settings from the option: undefined when off. On the Earth the Terrain Tiles by default (worldwide,
135
+ * Terrarium PNGs decoded in the page) or the IGN terrain model (France, raised by the geoid); NASA's on the Moon and
136
+ * Mars; an ArcGIS image service asked for in the body's Mercator */
137
+ function terrainSettings(terrain, body, radius) {
138
+ if (!terrain)
139
+ return undefined;
140
+ let options = {};
141
+ if (typeof terrain === 'string')
142
+ options = { model: terrain };
143
+ else if (terrain !== true)
144
+ options = terrain;
145
+ const earth = (body ?? 'earth') === 'earth';
146
+ const exaggeration = options.exaggeration ?? 1;
147
+ if (options.url === undefined && earth) {
148
+ if (options.model === 'ign') {
149
+ const geoid = options.geoid ?? true;
150
+ return { url: TERRAIN_URL, exaggeration, maxZoom: options.maxZoom ?? 15, geoid, attribution: IGN_ATTRIBUTION };
151
+ }
152
+ return {
153
+ url: TERRAIN_TILES.url,
154
+ exaggeration,
155
+ maxZoom: options.maxZoom ?? TERRAIN_TILES.maxZoom,
156
+ geoid: options.geoid ?? false,
157
+ // The sea floor of the model at sea level: the oceans stay flat under the basemap's water
158
+ loader: terrainLoader(TERRAIN_TILES.url, 'terrarium', 0),
159
+ attribution: TERRAIN_TILES_ATTRIBUTION,
160
+ };
161
+ }
162
+ const preset = body === 'moon' || body === 'mars' ? BODY_TERRAINS[body] : undefined;
163
+ const url = options.url ?? preset?.url;
164
+ if (url === undefined)
165
+ throw new Error('isard: the relief of this body needs a url');
166
+ const encoding = options.encoding ?? 'float32';
167
+ return {
168
+ url: IMAGE_SERVER.test(url) ? imageServerTerrain(url, earth, radius) : url,
169
+ exaggeration,
170
+ maxZoom: options.maxZoom ?? (options.url === undefined && preset ? preset.maxZoom : 15),
171
+ geoid: options.geoid ?? false,
172
+ ...(encoding === 'float32' ? {} : { loader: terrainLoader(url, encoding) }),
173
+ };
174
+ }
175
+ /** Sky settings for the engine: colors (RGB 0-1) and blends, MapLibre's defaults */
176
+ function atmosphereSettings(options) {
177
+ if (!options)
178
+ return undefined;
179
+ return Float32Array.from([
180
+ ...rgb(options.skyColor ?? '#9cc7ec'),
181
+ ...rgb(options.horizonColor ?? '#e8f1f8'),
182
+ ...rgb(options.fogColor ?? '#f2f5f8'),
183
+ options.skyHorizonBlend ?? 0.6,
184
+ options.horizonFogBlend ?? 0.7,
185
+ options.fogGroundBlend ?? 0.4,
186
+ ]);
187
+ }
188
+ /** MapLibre's default easing: cubic Bézier (0.25, 0.1, 0.25, 1) */
189
+ export function defaultEasing(t) {
190
+ if (t <= 0 || t >= 1)
191
+ return Math.max(0, Math.min(1, t));
192
+ // Solve x(u) = t for the curve parameter, Newton then bisection
193
+ const [x1, y1, x2, y2] = [0.25, 0.1, 0.25, 1];
194
+ const bezier = (u, a, b) => 3 * a * u * (1 - u) ** 2 + 3 * b * u * u * (1 - u) + u ** 3;
195
+ let u = t;
196
+ for (let i = 0; i < 8; i += 1) {
197
+ const x = bezier(u, x1, x2) - t;
198
+ const dx = 3 * x1 * (1 - u) ** 2 + 6 * (x2 - x1) * u * (1 - u) + 3 * (1 - x2) * u * u;
199
+ if (Math.abs(x) < 1e-6 || dx === 0)
200
+ break;
201
+ u = Math.max(0, Math.min(1, u - x / dx));
202
+ }
203
+ return bezier(u, y1, y2);
204
+ }
205
+ const MERCATOR_LAT = 85.051128779806589;
206
+ const toMercator = ([lon, lat]) => {
207
+ const phi = (Math.max(-MERCATOR_LAT, Math.min(MERCATOR_LAT, lat)) * Math.PI) / 180;
208
+ return [(lon + 180) / 360, 0.5 - Math.log(Math.tan(Math.PI / 4 + phi / 2)) / (2 * Math.PI)];
209
+ };
210
+ const fromMercator = ([x, y]) => [
211
+ x * 360 - 180,
212
+ (Math.atan(Math.sinh(Math.PI * (1 - 2 * y))) * 180) / Math.PI,
213
+ ];
214
+ /** A CSS color to RGB 0-1 (its alpha dropped); black if unknown */
215
+ function rgb(color) {
216
+ const [r, g, b] = parseCssColor(color) ?? [0, 0, 0, 1];
217
+ return [r, g, b];
218
+ }
219
+ const CORNERS = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
220
+ /** A map (see `GeoMap.create`); layers take it as their host */
221
+ export class GeoMap {
222
+ canvas;
223
+ #glyphs;
224
+ /** Layers new layers go under */
225
+ onTop = new Set();
226
+ /** The vector basemap, if any: its tiles' workers and its labels */
227
+ vector;
228
+ glyphsUrl;
229
+ basemapWorkerUrl;
230
+ container;
231
+ /** Markers and popups, over the canvas */
232
+ overlay;
233
+ corners;
234
+ controls = new Map();
235
+ positioned = new Set();
236
+ /** Canvas size in CSS pixels, kept on resize so placing overlays never reads the layout */
237
+ size = [0, 0];
238
+ #engine;
239
+ /** Layers in drawing order (bottom first), to recreate them after a context loss */
240
+ layers = [];
241
+ settings;
242
+ /** The WebGL context is lost: nothing is drawn until it is restored */
243
+ lost = false;
244
+ listeners = {
245
+ movestart: new Set(),
246
+ move: new Set(),
247
+ moveend: new Set(),
248
+ resize: new Set(),
249
+ hover: new Set(),
250
+ hoverfeature: new Set(),
251
+ click: new Set(),
252
+ render: new Set(),
253
+ idle: new Set(),
254
+ leave: new Set(),
255
+ };
256
+ resizeObserver;
257
+ interaction;
258
+ loader;
259
+ /** The class of the engine: without 3D Tiles until a 3D Tiles layer is added, unless asked for from the start */
260
+ engineClass;
261
+ /** The module of the engine with 3D Tiles once it runs this map (the decoding workers run it too) */
262
+ tiles3dModule;
263
+ /** The engine with 3D Tiles is loading, for the 3D Tiles layers added on the core engine */
264
+ upgrading;
265
+ /** What loading the engine with 3D Tiles and its workers needs */
266
+ tiles3dOptions;
267
+ gone = false;
268
+ /** The map is of the Earth: a basemap by default */
269
+ earth;
270
+ /** The body, as the option named it */
271
+ body;
272
+ basemap;
273
+ hillshade;
274
+ /** Called when the credits of the layers or relief change (the attribution controls) */
275
+ attributionListeners = new Set();
276
+ /** Credits of the raster layers that have some (basemaps, hillshade, the Géoplateforme's rasters…) */
277
+ rasterCredits = new Map();
278
+ animation;
279
+ hoverPoint;
280
+ /** Frame polling the engine for the answer of the hover picking, 0 if none */
281
+ hoverPoll = 0;
282
+ /** What 'hoverfeature' looks for: within `radius` CSS pixels, in `layers` only if given */
283
+ hoverPicking = {};
284
+ frameRequest = 0;
285
+ lastCamera = '';
286
+ /** The camera moved since the last 'moveend' */
287
+ moving = false;
288
+ /** The last frame found everything loaded ('idle' sent) */
289
+ settled = false;
290
+ inFrame = false;
291
+ /** Vector tiles made by `vectorTiles()`, destroyed with the map */
292
+ vectorSets = new Set();
293
+ /** The workers drawing vector tiles, shared by every `VectorTiles` of the map; created on first use */
294
+ basemapPool;
295
+ /** Stops watching the device pixel ratio */
296
+ unwatchRatio;
297
+ /** Loads the engine (once per page) and creates a map filling `container` */
298
+ static async create(container, options = {}) {
299
+ // With 3D Tiles from the start when asked, or when only that engine's URL is given (as before the core engine)
300
+ const full = options.tiles3d === true || (options.wasmUrl !== undefined && options.coreWasmUrl === undefined);
301
+ const bindings = full
302
+ ? await loadEngine('full', options.wasmUrl ?? new URL('./isard_bg.wasm', import.meta.url))
303
+ : await loadEngine('core', options.coreWasmUrl ?? new URL('./isard_core_bg.wasm', import.meta.url));
304
+ return new GeoMap(container, options, bindings.Engine, full ? bindings.module : undefined);
305
+ }
306
+ constructor(container, options, engineClass, tiles3dModule) {
307
+ this.engineClass = engineClass;
308
+ this.tiles3dModule = tiles3dModule;
309
+ this.tiles3dOptions = { ...options };
310
+ this.glyphsUrl = options.glyphs;
311
+ this.basemapWorkerUrl = options.basemapWorkerUrl;
312
+ this.container = container;
313
+ this.canvas = document.createElement('canvas');
314
+ Object.assign(this.canvas.style, { display: 'block', width: '100%', height: '100%', touchAction: 'none' });
315
+ // Overlays and controls are positioned against the container
316
+ injectStyle(container.ownerDocument);
317
+ if (getComputedStyle(container).position === 'static')
318
+ container.style.position = 'relative';
319
+ container.classList.add('isard-map');
320
+ this.overlay = document.createElement('div');
321
+ this.overlay.className = 'isard-overlay';
322
+ const corner = (position) => {
323
+ const element = document.createElement('div');
324
+ element.className = `isard-ctrl-${position}`;
325
+ return element;
326
+ };
327
+ this.corners = {
328
+ 'top-left': corner('top-left'),
329
+ 'top-right': corner('top-right'),
330
+ 'bottom-left': corner('bottom-left'),
331
+ 'bottom-right': corner('bottom-right'),
332
+ };
333
+ container.append(this.canvas, this.overlay, ...CORNERS.map((position) => this.corners[position]));
334
+ this.earth = (options.body ?? 'earth') === 'earth';
335
+ this.body = options.body;
336
+ const body = bodySettings(options.body);
337
+ this.settings = {
338
+ body,
339
+ zoomRange: [options.minZoom ?? 0, options.maxZoom ?? 22],
340
+ maxPitch: options.maxPitch ?? 70,
341
+ globe: (options.projection ?? 'globe') === 'globe',
342
+ sky: options.sky ?? true,
343
+ atmosphere: atmosphereSettings(options.atmosphere),
344
+ terrain: terrainSettings(options.terrain, options.body, body.radius),
345
+ loading: options.loading ?? 'immediate',
346
+ background: rgb(options.background ?? (this.earth ? '#f2f2f0' : '#000000')),
347
+ globeColor: this.earth ? SEA['osm-positron'] : rgb(body.color),
348
+ };
349
+ this.#engine = this.createEngine();
350
+ // The browser may take the GPU away (driver reset, background tab on mobile): the map waits, then rebuilds
351
+ this.canvas.addEventListener('webglcontextlost', (event) => {
352
+ event.preventDefault();
353
+ this.lost = true;
354
+ cancelAnimationFrame(this.frameRequest);
355
+ this.frameRequest = 0;
356
+ });
357
+ this.canvas.addEventListener('webglcontextrestored', () => this.restore());
358
+ const start = this.earth
359
+ ? { center: [2.4246, 48.8457], zoom: 13, pitch: 0, bearing: 0 }
360
+ : { center: [0, 0], zoom: 2, pitch: 0, bearing: 0 };
361
+ this.setCamera({ ...start, ...options });
362
+ this.setBasemap(options.basemap ?? (this.earth ? 'osm-positron' : 'none'), options.hillshade ?? 0);
363
+ this.resizeObserver = new ResizeObserver(() => this.resize());
364
+ this.resizeObserver.observe(container);
365
+ this.watchRatio();
366
+ this.resize();
367
+ const interactive = options.interactive ?? true;
368
+ const keyboard = interactive && (options.keyboard ?? true);
369
+ this.interaction = interactive ? new Interaction(this, { keyboard }) : undefined;
370
+ // Reached with Tab when the keys move it; named for screen readers either way
371
+ this.canvas.classList.add('isard-canvas');
372
+ this.canvas.setAttribute('role', keyboard ? 'application' : 'region');
373
+ this.canvas.setAttribute('aria-roledescription', 'map');
374
+ this.canvas.setAttribute('aria-label', options.ariaLabel ?? 'Map');
375
+ if (keyboard)
376
+ this.canvas.tabIndex = 0;
377
+ const attribution = options.attributionControl ?? true;
378
+ if (attribution !== false) {
379
+ this.addControl(new AttributionControl(attribution === true ? {} : attribution), 'bottom-right');
380
+ }
381
+ }
382
+ /** The element the map was created in */
383
+ getContainer() {
384
+ return this.container;
385
+ }
386
+ getCanvas() {
387
+ return this.canvas;
388
+ }
389
+ /** @internal The engine (replaced after a context loss) */
390
+ get engine() {
391
+ return this.#engine;
392
+ }
393
+ createEngine() {
394
+ const engine = new this.engineClass(this.canvas, () => this.requestRender());
395
+ // The body first: the layers' shaders may take its size
396
+ const { radius, flattening, atmosphere: air, relief } = this.settings.body;
397
+ engine.setBody(radius, flattening, haloSettings(air), ...relief);
398
+ const { zoomRange, maxPitch, globe, sky, atmosphere, terrain, loading, background, globeColor } = this.settings;
399
+ engine.setZoomRange(...zoomRange);
400
+ engine.setMaxPitch(maxPitch);
401
+ engine.setGlobe(globe);
402
+ engine.setSky(sky);
403
+ engine.setAtmosphere(atmosphere);
404
+ engine.setTerrain(terrain?.url, terrain?.exaggeration ?? 1, terrain?.maxZoom, terrain?.geoid, terrain?.loader);
405
+ engine.setImmediateLoading(loading === 'immediate');
406
+ engine.setBackground(...background);
407
+ engine.setGlobeColor(...globeColor);
408
+ this.loader ??= this.startLoader(engine);
409
+ if (this.loader)
410
+ engine.setTileLoader(this.loader);
411
+ return engine;
412
+ }
413
+ /** The decoding workers of 3D Tiles, with the engine that has them (they run its module) and unless turned off */
414
+ startLoader(engine) {
415
+ const { workers: count, workerUrl, decoders } = this.tiles3dOptions;
416
+ const workers = count ?? Math.min(4, Math.max(1, (navigator.hardwareConcurrency || 2) - 1));
417
+ if (!this.tiles3dModule || workers === false || workers <= 0 || typeof Worker === 'undefined')
418
+ return undefined;
419
+ return new TileLoader(this.tiles3dModule, workerUrl ?? new URL('./decoder.worker.js', import.meta.url), workers, { ...DEFAULT_DECODERS, ...decoders }, engine.textureFormats());
420
+ }
421
+ /** A 3D Tiles layer on the core engine: loads the engine with 3D Tiles, then rebuilds the map on it (camera,
422
+ * settings and layers kept, as after a context loss); the layer is created then */
423
+ upgrade() {
424
+ const url = this.tiles3dOptions.wasmUrl ?? new URL('./isard_bg.wasm', import.meta.url);
425
+ this.upgrading ??= loadEngine('full', url).then(({ module, Engine }) => {
426
+ this.upgrading = undefined;
427
+ if (this.gone)
428
+ return;
429
+ this.engineClass = Engine;
430
+ this.tiles3dModule = module;
431
+ // A lost context: the engine is rebuilt on it once restored
432
+ if (!this.lost)
433
+ this.restore();
434
+ }, (error) => {
435
+ // The 3D Tiles layers stay empty; the next one added tries again
436
+ this.upgrading = undefined;
437
+ report(error);
438
+ this.requestRender();
439
+ });
440
+ }
441
+ /** After a context loss: a new engine with the same camera, settings and layers (same handles, same order) */
442
+ restore() {
443
+ this.cancelHoverPick();
444
+ const camera = this.getCamera();
445
+ this.#engine.free();
446
+ this.#engine = this.createEngine();
447
+ this.lost = false;
448
+ this.setCamera(camera);
449
+ this.#glyphs?.attach(this.#engine);
450
+ for (const layer of this.layers)
451
+ layer.attach(this.#engine);
452
+ this.resize();
453
+ }
454
+ /** @internal Forgets a removed layer */
455
+ detach(layer) {
456
+ this.unlist(layer);
457
+ if (this.rasterCredits.delete(layer))
458
+ this.attributionChanged();
459
+ }
460
+ /** Takes a layer out of the drawing order (to put it back elsewhere, or for good) */
461
+ unlist(layer) {
462
+ const index = this.layers.indexOf(layer);
463
+ if (index >= 0)
464
+ this.layers.splice(index, 1);
465
+ }
466
+ add(layer) {
467
+ // On the core engine, a 3D Tiles layer waits for the engine with 3D Tiles: it is created with the others on it
468
+ if (layer instanceof Tiles3dLayer && !this.tiles3dModule)
469
+ this.upgrade();
470
+ else
471
+ layer.attach(this.engine);
472
+ this.layers.push(layer);
473
+ // Under the layers kept on top (the basemap's labels)
474
+ const top = this.layers.find((l) => this.onTop.has(l) && l !== layer);
475
+ if (top)
476
+ this.moveLayer(layer, top);
477
+ this.requestRender();
478
+ return layer;
479
+ }
480
+ /** @internal Keeps a layer above the layers added after it (they go under it), as the labels of a basemap */
481
+ keepOnTop(layer) {
482
+ this.onTop.add(layer);
483
+ }
484
+ /** @internal Moves a layer under `before`, or on top of all */
485
+ moveLayer(layer, before) {
486
+ const handle = layer;
487
+ this.unlist(handle);
488
+ const index = before ? this.layers.indexOf(before) : -1;
489
+ const at = index < 0 ? this.layers.length : index;
490
+ this.layers.splice(at, 0, handle);
491
+ if (handle.id >= 0)
492
+ this.engine.moveLayer(handle.id, this.engineIndex(at));
493
+ this.requestRender();
494
+ }
495
+ /** @internal See `LayerHost.replaceLayer` */
496
+ replaceLayer(layer, old) {
497
+ this.engine.removeLayer(old);
498
+ const index = this.layers.indexOf(layer);
499
+ if (index >= 0)
500
+ this.engine.moveLayer(layer.id, this.engineIndex(index));
501
+ }
502
+ /** Index in the engine of the layer at `index`: the layers waiting for the engine with 3D Tiles are not in it yet */
503
+ engineIndex(index) {
504
+ let count = 0;
505
+ for (let i = 0; i < index; i += 1)
506
+ if ((this.layers[i]?.id ?? -1) >= 0)
507
+ count += 1;
508
+ return count;
509
+ }
510
+ /** Moves a layer under all the others */
511
+ toBottom(layer) {
512
+ this.engine.moveLayer(layer.id, 0);
513
+ this.unlist(layer);
514
+ this.layers.unshift(layer);
515
+ }
516
+ // ── Events ──
517
+ /** Listens to an event; returns the function that stops listening */
518
+ on(type, listener) {
519
+ const listeners = this.listeners[type];
520
+ listeners.add(listener);
521
+ return () => listeners.delete(listener);
522
+ }
523
+ /** @internal Calls the listeners; one that throws is reported and does not stop the others nor the frame */
524
+ emit(type, event) {
525
+ const listeners = this.listeners[type];
526
+ for (const listener of listeners) {
527
+ try {
528
+ listener(event);
529
+ }
530
+ catch (error) {
531
+ report(error);
532
+ }
533
+ }
534
+ }
535
+ // ── Camera ──
536
+ getCamera() {
537
+ return this.engine.camera();
538
+ }
539
+ setCamera(camera) {
540
+ const c = { ...this.getCamera(), ...camera };
541
+ this.engine.setCamera(c.center[0], c.center[1], c.zoom, c.pitch, c.bearing);
542
+ this.requestRender();
543
+ }
544
+ /** Animated move to a camera: over `duration` milliseconds (or the options), ease-out by default */
545
+ easeTo(camera, options = 600) {
546
+ const { duration = 600, easing = (t) => 1 - (1 - t) ** 3 } = typeof options === 'number' ? { duration: options } : options;
547
+ const from = this.getCamera();
548
+ const to = { ...from, ...camera };
549
+ // Shortest way round
550
+ const turn = ((to.bearing - from.bearing + 540) % 360) - 180;
551
+ const start = performance.now();
552
+ this.animate((now) => {
553
+ if (now - start >= duration)
554
+ this.engine.clearPreload();
555
+ const t = duration > 0 ? Math.min(1, (now - start) / duration) : 1;
556
+ const k = easing(t);
557
+ const mix = (a, b) => a + (b - a) * k;
558
+ this.engine.setCamera(mix(from.center[0], to.center[0]), mix(from.center[1], to.center[1]), mix(from.zoom, to.zoom), mix(from.pitch, to.pitch), from.bearing + turn * k);
559
+ return t < 1;
560
+ });
561
+ // The destination's tiles load during the flight (as Cesium does)
562
+ this.engine.preload(to.center[0], to.center[1], to.zoom, to.pitch, to.bearing);
563
+ }
564
+ /**
565
+ * Flight to a camera that zooms out on its way and back in (van Wijk and Nuij's optimal path, as MapLibre's
566
+ * `flyTo`): long moves stay readable. Pitch and bearing follow the progress.
567
+ */
568
+ flyTo(camera, options = {}) {
569
+ const from = this.getCamera();
570
+ const to = { ...from, ...camera };
571
+ const { curve: rho = 1.42, speed = 1.2, easing = defaultEasing } = options;
572
+ const [x0, y0] = toMercator(from.center);
573
+ const [x1, y1] = toMercator(to.center);
574
+ // Across the antimeridian, the short way
575
+ const dx = x1 - x0 - Math.round(x1 - x0);
576
+ const dy = y1 - y0;
577
+ // In pixels at the start zoom (512 px world at zoom 0)
578
+ const world = 512 * 2 ** from.zoom;
579
+ const u1 = Math.hypot(dx, dy) * world;
580
+ const w0 = Math.max(this.canvas.clientWidth, this.canvas.clientHeight, 1);
581
+ const w1 = w0 / 2 ** (to.zoom - from.zoom);
582
+ const rho2 = rho * rho;
583
+ const r = (i) => {
584
+ const b = (w1 * w1 - w0 * w0 + (i ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (i ? w1 : w0) * rho2 * u1);
585
+ return Math.log(Math.sqrt(b * b + 1) - b);
586
+ };
587
+ // No move on the ground (or nearly): a plain zoom
588
+ const still = u1 < 1e-6 || !Number.isFinite(r(0)) || !Number.isFinite(r(1));
589
+ const r0 = still ? 0 : r(0);
590
+ const length = still ? Math.abs(Math.log(w1 / w0)) / rho : (r(1) - r0) / rho;
591
+ const width = (s) => still ? Math.exp((w1 < w0 ? -1 : 1) * rho * s) : Math.cosh(r0) / Math.cosh(r0 + rho * s);
592
+ const along = (s) => still ? 0 : (w0 * ((Math.cosh(r0) * Math.tanh(r0 + rho * s) - Math.sinh(r0)) / rho2)) / u1;
593
+ const duration = options.duration ?? (1000 * length) / speed;
594
+ const turn = ((to.bearing - from.bearing + 540) % 360) - 180;
595
+ const start = performance.now();
596
+ this.animate((now) => {
597
+ if (now - start >= duration)
598
+ this.engine.clearPreload();
599
+ const t = duration > 0 ? Math.min(1, (now - start) / duration) : 1;
600
+ const k = easing(t);
601
+ const s = k * length;
602
+ const u = t >= 1 ? 1 : along(s);
603
+ const zoom = t >= 1 ? to.zoom : from.zoom + Math.log2(1 / width(s));
604
+ const [lon, lat] = fromMercator([x0 + dx * u, y0 + dy * u]);
605
+ this.engine.setCamera(lon, lat, zoom, from.pitch + (to.pitch - from.pitch) * k, from.bearing + turn * k);
606
+ return t < 1;
607
+ });
608
+ this.engine.preload(to.center[0], to.center[1], to.zoom, to.pitch, to.bearing);
609
+ }
610
+ /** Longitudes and latitudes the view covers on the ground: `[west, south, east, north]` */
611
+ getBounds() {
612
+ const [west = -180, south = -85, east = 180, north = 85] = this.engine.bounds();
613
+ return [west, south, east, north];
614
+ }
615
+ /** Lowest zoom the camera accepts (the widest view) */
616
+ setMinZoom(zoom) {
617
+ this.settings.zoomRange[0] = zoom;
618
+ this.engine.setZoomRange(...this.settings.zoomRange);
619
+ this.requestRender();
620
+ }
621
+ setMaxZoom(zoom) {
622
+ this.settings.zoomRange[1] = zoom;
623
+ this.engine.setZoomRange(...this.settings.zoomRange);
624
+ this.requestRender();
625
+ }
626
+ /** Highest pitch, degrees, up to 85 */
627
+ setMaxPitch(pitch) {
628
+ this.settings.maxPitch = pitch;
629
+ this.engine.setMaxPitch(pitch);
630
+ this.requestRender();
631
+ }
632
+ /** Sky over the plane and the fog of the ground (see `GeoMapOptions.atmosphere`); undefined to remove them */
633
+ setAtmosphere(options) {
634
+ this.settings.atmosphere = atmosphereSettings(options);
635
+ this.engine.setAtmosphere(this.settings.atmosphere);
636
+ this.requestRender();
637
+ }
638
+ setProjection(projection) {
639
+ this.settings.globe = projection === 'globe';
640
+ this.engine.setGlobe(this.settings.globe);
641
+ this.requestRender();
642
+ }
643
+ /** How tiles load and show (see `LoadingMode`) */
644
+ setLoading(mode) {
645
+ this.settings.loading = mode;
646
+ this.engine.setImmediateLoading(mode === 'immediate');
647
+ this.requestRender();
648
+ }
649
+ /** Space behind the globe (stars, atmosphere halo) */
650
+ setSky(enabled) {
651
+ this.settings.sky = enabled;
652
+ this.engine.setSky(enabled);
653
+ this.requestRender();
654
+ }
655
+ /** Relief under the basemap: true for the body's terrain model (on the Earth the worldwide Terrain Tiles, NASA's
656
+ * on the Moon and Mars), one of the Earth's models by name (`'ign'`), its options, or false; on another body, its
657
+ * options with a `url` */
658
+ setTerrain(terrain) {
659
+ this.settings.terrain = terrainSettings(terrain, this.body, this.settings.body.radius);
660
+ const t = this.settings.terrain;
661
+ this.engine.setTerrain(t?.url, t?.exaggeration ?? 1, t?.maxZoom, t?.geoid, t?.loader);
662
+ this.attributionChanged();
663
+ this.requestRender();
664
+ }
665
+ /** @internal The credits of the raster layers (the basemap first) and of the relief in use, each once */
666
+ attributions() {
667
+ const layers = this.layers.map((layer) => this.rasterCredits.get(layer));
668
+ const credits = [...layers, this.settings.terrain?.attribution];
669
+ return [...new Set(credits.filter((c) => c !== undefined))];
670
+ }
671
+ /** @internal Calls `listener` when the credits change; returns what stops it */
672
+ onAttributionChange(listener) {
673
+ this.attributionListeners.add(listener);
674
+ return () => this.attributionListeners.delete(listener);
675
+ }
676
+ attributionChanged() {
677
+ for (const listener of this.attributionListeners)
678
+ listener();
679
+ }
680
+ /** Color behind the map, a CSS color (its alpha ignored) */
681
+ setBackground(color) {
682
+ this.settings.background = rgb(color);
683
+ this.engine.setBackground(...this.settings.background);
684
+ this.requestRender();
685
+ }
686
+ /** Tile counters of the raster layers, for diagnostics */
687
+ stats() {
688
+ return this.engine.stats();
689
+ }
690
+ /**
691
+ * Network edge under a screen point (CSS pixels), undefined if none. Reads one pixel of an offscreen picking pass:
692
+ * cheap whatever the number of features, call it on hover.
693
+ */
694
+ pick(point, radius = 0, layers) {
695
+ const only = layers && Uint32Array.from(layers.map((l) => l.id));
696
+ return this.engine.pick(point[0], point[1], radius, only);
697
+ }
698
+ /**
699
+ * The feature under a screen point (CSS pixels), or the nearest one within `radius` pixels: its layer handle, its
700
+ * index there and, for line, circle and fill layers, the feature itself; undefined if none. `layers` restricts the
701
+ * search to some layers (the others hide nothing).
702
+ */
703
+ pickFeature(point, options = {}) {
704
+ const hit = this.pick(point, options.radius ?? 0, options.layers);
705
+ return hit && this.featureHit(hit);
706
+ }
707
+ /** A hit with its layer handle and feature; undefined if the layer is gone */
708
+ featureHit(hit) {
709
+ const layer = this.layers.find((l) => l.id === hit.layer);
710
+ if (!layer)
711
+ return undefined;
712
+ const feature = 'featureAt' in layer && typeof layer.featureAt === 'function'
713
+ ? layer.featureAt(hit.index)
714
+ : undefined;
715
+ return { layer, index: hit.index, feature };
716
+ }
717
+ /** Asks the engine what is under the pointer; its answer, read without waiting for the GPU, comes on a later frame */
718
+ requestHoverPick(point) {
719
+ const { radius = 0, layers } = this.hoverPicking;
720
+ const only = layers && Uint32Array.from(layers.map((l) => l.id));
721
+ // A new request replaces the one in flight (in the engine too): one poll loop at most
722
+ if (!this.engine.requestPick(point[0], point[1], radius, only) || this.hoverPoll)
723
+ return;
724
+ this.hoverPoll = requestAnimationFrame(this.pollHoverPick);
725
+ }
726
+ pollHoverPick = () => {
727
+ this.hoverPoll = 0;
728
+ if (this.lost)
729
+ return;
730
+ const result = this.engine.pollPick();
731
+ if (!result) {
732
+ // The GPU is not done yet (usually a frame): asked again next frame, without drawing
733
+ this.hoverPoll = requestAnimationFrame(this.pollHoverPick);
734
+ return;
735
+ }
736
+ this.emit('hoverfeature', {
737
+ point: [result.x, result.y],
738
+ lonLat: result.lonLat,
739
+ hit: result.hit && this.featureHit(result.hit),
740
+ });
741
+ };
742
+ cancelHoverPick() {
743
+ cancelAnimationFrame(this.hoverPoll);
744
+ this.hoverPoll = 0;
745
+ }
746
+ /** Screen point (CSS pixels) of a position, undefined behind the camera */
747
+ project(lonLat) {
748
+ return this.engine.project(lonLat[0], lonLat[1]);
749
+ }
750
+ /** Position under a screen point (CSS pixels), undefined above the horizon */
751
+ unproject(point) {
752
+ return this.engine.ground(point[0], point[1]);
753
+ }
754
+ // ── Overlays and controls ──
755
+ /** Adds a control in a corner of the map; controls stack from the corner inward */
756
+ addControl(control, position = 'top-right') {
757
+ if (this.controls.has(control))
758
+ return this;
759
+ const element = control.onAdd(this);
760
+ element.classList.add('isard-ctrl');
761
+ // In the bottom corners the first control added stays lowest, as in MapLibre
762
+ if (position.startsWith('bottom'))
763
+ this.corners[position].prepend(element);
764
+ else
765
+ this.corners[position].append(element);
766
+ this.controls.set(control, element);
767
+ return this;
768
+ }
769
+ removeControl(control) {
770
+ const element = this.controls.get(control);
771
+ if (!element)
772
+ return this;
773
+ this.controls.delete(control);
774
+ control.onRemove(this);
775
+ element.remove();
776
+ return this;
777
+ }
778
+ /** @internal Shows a marker or popup, placed after every frame from now on */
779
+ attachOverlay(item, element) {
780
+ this.overlay.append(element);
781
+ this.positioned.add(item);
782
+ item.position(this.size);
783
+ }
784
+ /** @internal */
785
+ detachOverlay(item, element) {
786
+ this.positioned.delete(item);
787
+ element.remove();
788
+ }
789
+ /** @internal Places one overlay now (it moved), without drawing a frame */
790
+ positionOverlay(item) {
791
+ if (this.positioned.has(item))
792
+ item.position(this.size);
793
+ }
794
+ // ── Layers ──
795
+ /** Replaces the basemap and the IGN hillshade, under the other layers (hillshade by default: 0, none). The former
796
+ * names of the Géoplateforme basemaps (`LegacyBasemap`) are taken under their new ones */
797
+ setBasemap(basemap, hillshade = 0) {
798
+ const name = basemapName(basemap);
799
+ this.basemap?.remove();
800
+ this.hillshade?.remove();
801
+ if (this.vector) {
802
+ this.onTop.delete(this.vector.labels);
803
+ this.vector.labels.remove();
804
+ this.vector.tiles.destroy();
805
+ this.vector = undefined;
806
+ }
807
+ const vector = VECTOR_BASEMAPS[name];
808
+ if (vector) {
809
+ const tiles = new VectorTiles(this, {
810
+ style: vector,
811
+ ...(this.basemapWorkerUrl ? { workerUrl: this.basemapWorkerUrl } : {}),
812
+ });
813
+ this.basemap = tiles.raster();
814
+ this.vector = { tiles, labels: tiles.labels() };
815
+ }
816
+ else {
817
+ this.basemap = name === 'none' ? undefined : this.addRaster(BASEMAPS[name]);
818
+ }
819
+ // Off the Earth, the body's own color
820
+ if (this.earth)
821
+ this.settings.globeColor = SEA[name];
822
+ this.engine.setGlobeColor(...this.settings.globeColor);
823
+ this.hillshade = hillshade > 0 ? this.addRaster({ ...HILLSHADE, opacity: hillshade }) : undefined;
824
+ if (this.hillshade)
825
+ this.toBottom(this.hillshade);
826
+ if (this.basemap)
827
+ this.toBottom(this.basemap);
828
+ this.attributionChanged();
829
+ }
830
+ /** Raster tiles ({z}, {x}, {y} URL; Web Mercator, or reprojected from an equirectangular `grid`), over the layers
831
+ * already added */
832
+ addRaster(options) {
833
+ const { url, grid = 'mercator', minZoom = 0, maxZoom = 19, opacity = 1, saturation = 1, size, before } = options;
834
+ let layer;
835
+ if (grid === 'equirectangular' && !options.loader) {
836
+ // The source's level n has the pixel size of Mercator level n + 1 at the equator
837
+ const loader = equirectangularLoader(url, maxZoom, size ?? 256);
838
+ layer = new RasterLayer(this, { url, minZoom, maxZoom: maxZoom + 1, opacity, saturation, size, loader });
839
+ }
840
+ else {
841
+ layer = new RasterLayer(this, { url, minZoom, maxZoom, opacity, saturation, size, loader: options.loader });
842
+ }
843
+ this.place(layer, before);
844
+ if (options.attribution) {
845
+ this.rasterCredits.set(layer, options.attribution);
846
+ this.attributionChanged();
847
+ }
848
+ return layer;
849
+ }
850
+ /** Line network colored by a value per node; `layer.setValues` recolors it in one texture upload */
851
+ addNetwork(options) {
852
+ const { nodes, edges, lines, costs, edgeWidths, width = 2, max = 1800, contour = 0, opacity = 1 } = options;
853
+ const { halo = 0, haloOpacity = 0.11, ramp, unreachedColor = 'rgba(140, 140, 140, 0.25)', fade = 0 } = options;
854
+ const style = { width, max, contour, opacity, halo, haloOpacity, ramp, unreachedColor, fade };
855
+ validateNetwork(nodes, edges);
856
+ return this.add(new NetworkLayer(this, { nodes, edges, lines }, costs, style, edgeWidths));
857
+ }
858
+ /** Lines from GeoJSON (line strings, and polygon outlines), styled per feature */
859
+ addLines(options) {
860
+ return this.place(new LineLayer(this, options.data, lineStyle(options)), options.before);
861
+ }
862
+ /** Discs from GeoJSON points, styled per feature */
863
+ addCircles(options) {
864
+ return this.place(new CircleLayer(this, options.data, circleStyle(options)), options.before);
865
+ }
866
+ /** Filled polygons from GeoJSON (holes included), styled per feature; over the relief they lie on the ground */
867
+ addFills(options) {
868
+ return this.place(new FillLayer(this, options.data, fillStyle(options)), options.before);
869
+ }
870
+ /** The application's fragment shader over the ground (see `GroundOptions`); under `before` if given */
871
+ addGround(options) {
872
+ return this.place(new GroundLayer(this, options), options.before);
873
+ }
874
+ /** Polygons raised into blocks with depth (buildings), styled per feature; tiles of them come with `setTile` */
875
+ addExtrusions(options = {}) {
876
+ return this.place(new ExtrusionLayer(this, options.data, extrusionStyle(options)), options.before);
877
+ }
878
+ /** Text labels from GeoJSON (points, the middle of lines, the center of polygons), placed without overlaps */
879
+ addSymbols(options) {
880
+ return this.place(new SymbolLayer(this, options.data, symbolStyle(options)), options.before);
881
+ }
882
+ /** @internal The glyphs of the symbol layers, loaded on first use */
883
+ get glyphs() {
884
+ if (!this.#glyphs) {
885
+ // The engine's context: the atlas stays within its texture size limit
886
+ const gl = this.canvas.getContext('webgl2');
887
+ const max = gl?.getParameter(gl.MAX_TEXTURE_SIZE);
888
+ this.#glyphs = new Glyphs(this.glyphsUrl, typeof max === 'number' ? max : undefined);
889
+ this.#glyphs.attach(this.engine);
890
+ }
891
+ return this.#glyphs;
892
+ }
893
+ /**
894
+ * Vector tiles with a MapLibre style (OpenFreeMap's Positron by default): `tiles.raster(…)` draws its fills and lines
895
+ * (or a subset) as a raster layer, `tiles.labels(…)` its labels. `setBasemap('osm-positron')` does both for the
896
+ * basemap.
897
+ */
898
+ vectorTiles(options = {}) {
899
+ const tiles = new VectorTiles(this, {
900
+ ...(this.basemapWorkerUrl ? { workerUrl: this.basemapWorkerUrl } : {}),
901
+ ...options,
902
+ });
903
+ // Its workers stop with the map
904
+ this.vectorSets.add(tiles);
905
+ return tiles;
906
+ }
907
+ /**
908
+ * @internal The workers for a `VectorTiles`: the map's shared pool, or a pool of its own (`own`, to stop with it)
909
+ * when it asks for another count or URL
910
+ */
911
+ basemapWorkers(count, url) {
912
+ const sharedUrl = this.basemapWorkerUrl ?? defaultWorkerUrl();
913
+ const shared = defaultWorkerCount();
914
+ const workers = Math.max(1, count ?? shared);
915
+ const workerUrl = url ?? sharedUrl;
916
+ if (workers === shared && String(workerUrl) === String(sharedUrl)) {
917
+ this.basemapPool ??= new BasemapWorkers(shared, sharedUrl);
918
+ return { pool: this.basemapPool, own: false };
919
+ }
920
+ return { pool: new BasemapWorkers(workers, workerUrl), own: true };
921
+ }
922
+ /** Adds a layer, under `before` if given */
923
+ place(layer, before) {
924
+ this.add(layer);
925
+ if (before)
926
+ this.moveLayer(layer, before);
927
+ return layer;
928
+ }
929
+ /** Textured meshes in 3D Tiles (photogrammetry, buildings), drawn with depth over the basemap */
930
+ addTiles3d(options) {
931
+ const { url, maxScreenSpaceError = 16, opacity = 1 } = options;
932
+ return this.add(new Tiles3dLayer(this, url, { maxScreenSpaceError, opacity }));
933
+ }
934
+ // ── Frames ──
935
+ /** Asks for a frame; several calls before the next frame draw it once */
936
+ requestRender() {
937
+ // Changes made by listeners during a frame are drawn by that frame; nothing is drawn without a context
938
+ if (this.inFrame || this.lost)
939
+ return;
940
+ this.frameRequest ||= requestAnimationFrame((now) => this.frame(now));
941
+ }
942
+ /** @internal Runs `step` every frame until it returns false; replaces the running animation */
943
+ animate(step) {
944
+ // A flight cut short no longer needs its destination
945
+ if (this.animation)
946
+ this.engine.clearPreload();
947
+ this.animation = step;
948
+ this.requestRender();
949
+ }
950
+ /** @internal */
951
+ hover(point) {
952
+ this.hoverPoint = point;
953
+ if (point)
954
+ this.requestRender();
955
+ else
956
+ this.cancelHoverPick();
957
+ }
958
+ frame(now) {
959
+ this.frameRequest = 0;
960
+ try {
961
+ this.inFrame = true;
962
+ this.drawFrame(now);
963
+ }
964
+ finally {
965
+ // Whatever throws in a frame, the next ones are still drawn
966
+ this.inFrame = false;
967
+ }
968
+ }
969
+ drawFrame(now) {
970
+ if (this.animation && !this.animation(now))
971
+ this.animation = undefined;
972
+ const camera = this.getCamera();
973
+ const key = `${camera.center}|${camera.zoom}|${camera.pitch}|${camera.bearing}`;
974
+ const moved = key !== this.lastCamera;
975
+ if (moved) {
976
+ // The first frame is no move
977
+ if (!this.moving && this.lastCamera !== '') {
978
+ this.moving = true;
979
+ this.emit('movestart', camera);
980
+ }
981
+ this.lastCamera = key;
982
+ this.emit('move', camera);
983
+ }
984
+ else if (this.moving && !this.animation && !this.interaction?.active) {
985
+ this.moving = false;
986
+ this.emit('moveend', camera);
987
+ }
988
+ // Values for the pointer position are computed before drawing, in the same frame
989
+ let hovered;
990
+ if (this.hoverPoint) {
991
+ const point = this.hoverPoint;
992
+ hovered = point;
993
+ this.hoverPoint = undefined;
994
+ this.emit('hover', { point, lonLat: this.unproject(point) });
995
+ }
996
+ const t0 = performance.now();
997
+ // The engine asks for the next frame while it draws (uploads past the frame budget, fades): not ignored
998
+ this.inFrame = false;
999
+ const loading = this.engine.render();
1000
+ this.inFrame = true;
1001
+ // The picking pass sees the frame just drawn; its answer comes on a later frame
1002
+ if (hovered && this.listeners.hoverfeature.size > 0)
1003
+ this.requestHoverPick(hovered);
1004
+ // Overlays follow the frame just drawn (camera, relief altitudes): all in one pass, transforms only
1005
+ for (const item of this.positioned)
1006
+ item.position(this.size);
1007
+ this.emit('render', { ms: performance.now() - t0 });
1008
+ this.inFrame = false;
1009
+ // A move goes on until a frame finds the camera still: that frame sends 'moveend'
1010
+ if (this.animation || (moved && this.moving))
1011
+ this.requestRender();
1012
+ // Idle: nothing loading (the engine with 3D Tiles neither), no animation, no frame asked for (uploads waiting,
1013
+ // fades, listeners)
1014
+ if (loading || this.upgrading || this.animation || this.frameRequest !== 0) {
1015
+ this.settled = false;
1016
+ }
1017
+ else if (!this.settled) {
1018
+ this.settled = true;
1019
+ this.emit('idle', {});
1020
+ }
1021
+ }
1022
+ /** Resizes when the device pixel ratio changes (browser zoom, a window moved to another screen) */
1023
+ watchRatio() {
1024
+ if (typeof matchMedia !== 'function')
1025
+ return;
1026
+ const query = matchMedia(`(resolution: ${window.devicePixelRatio || 1}dppx)`);
1027
+ const changed = () => {
1028
+ // A query for the new ratio
1029
+ this.unwatchRatio?.();
1030
+ this.watchRatio();
1031
+ this.resize();
1032
+ };
1033
+ query.addEventListener('change', changed, { once: true });
1034
+ this.unwatchRatio = () => query.removeEventListener('change', changed);
1035
+ }
1036
+ resize() {
1037
+ if (this.lost)
1038
+ return;
1039
+ const { clientWidth: width, clientHeight: height } = this.canvas;
1040
+ const ratio = window.devicePixelRatio || 1;
1041
+ this.canvas.width = Math.round(width * ratio);
1042
+ this.canvas.height = Math.round(height * ratio);
1043
+ this.engine.resize(width, height, ratio);
1044
+ this.size = [width, height];
1045
+ this.emit('resize', { width, height });
1046
+ // Draw at once: a resized canvas is cleared, waiting one frame would flash
1047
+ cancelAnimationFrame(this.frameRequest);
1048
+ this.frame(performance.now());
1049
+ }
1050
+ destroy() {
1051
+ this.gone = true;
1052
+ const camera = this.getCamera();
1053
+ cancelAnimationFrame(this.frameRequest);
1054
+ this.cancelHoverPick();
1055
+ this.vector?.tiles.destroy();
1056
+ for (const tiles of this.vectorSets)
1057
+ tiles.destroy();
1058
+ this.vectorSets.clear();
1059
+ this.basemapPool?.terminate();
1060
+ this.basemapPool = undefined;
1061
+ this.unwatchRatio?.();
1062
+ this.unwatchRatio = undefined;
1063
+ this.resizeObserver.disconnect();
1064
+ this.interaction?.destroy();
1065
+ this.loader?.destroy();
1066
+ this.engine.free();
1067
+ // Work still under way (labels being shaped, tiles arriving, timers) may call the engine after this: it finds one
1068
+ // that does nothing, and nothing is drawn again
1069
+ this.#engine = destroyed(camera);
1070
+ this.lost = true;
1071
+ for (const control of [...this.controls.keys()])
1072
+ this.removeControl(control);
1073
+ this.positioned.clear();
1074
+ this.canvas.remove();
1075
+ this.overlay.remove();
1076
+ for (const position of CORNERS)
1077
+ this.corners[position].remove();
1078
+ this.container.classList.remove('isard-map');
1079
+ for (const listeners of Object.values(this.listeners))
1080
+ listeners.clear();
1081
+ }
1082
+ }
1083
+ //# sourceMappingURL=map.js.map