isard 0.3.0 → 0.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 (62) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/README.md +11 -3
  3. package/dist/basemap.worker.d.ts +10 -3
  4. package/dist/basemap.worker.js +2 -2
  5. package/dist/basemap.worker.js.map +4 -4
  6. package/dist/decoder.worker.js +4 -4
  7. package/dist/decoder.worker.js.map +7 -6
  8. package/dist/decoders.d.ts +3 -2
  9. package/dist/decoders.js +28 -5
  10. package/dist/decoders.js.map +1 -1
  11. package/dist/engine-loader.d.ts +8 -4
  12. package/dist/engine-loader.js +10 -3
  13. package/dist/engine-loader.js.map +1 -1
  14. package/dist/formats.d.ts +11 -0
  15. package/dist/formats.js +12 -0
  16. package/dist/formats.js.map +1 -0
  17. package/dist/glyphs.d.ts +3 -0
  18. package/dist/glyphs.js +12 -2
  19. package/dist/glyphs.js.map +1 -1
  20. package/dist/icons.d.ts +146 -0
  21. package/dist/icons.js +333 -0
  22. package/dist/icons.js.map +1 -0
  23. package/dist/index.d.ts +8 -5
  24. package/dist/index.js +2 -1
  25. package/dist/index.js.map +1 -1
  26. package/dist/isard_bg.wasm +0 -0
  27. package/dist/isard_core_bg.wasm +0 -0
  28. package/dist/isard_points_bg.wasm +0 -0
  29. package/dist/layers.d.ts +88 -1
  30. package/dist/layers.js +165 -4
  31. package/dist/layers.js.map +1 -1
  32. package/dist/loader.d.ts +9 -3
  33. package/dist/loader.js +22 -3
  34. package/dist/loader.js.map +1 -1
  35. package/dist/map.d.ts +37 -3
  36. package/dist/map.js +76 -10
  37. package/dist/map.js.map +1 -1
  38. package/dist/pointclouds.d.ts +98 -0
  39. package/dist/pointclouds.js +232 -0
  40. package/dist/pointclouds.js.map +1 -0
  41. package/dist/projections.d.ts +13 -0
  42. package/dist/projections.js +13 -0
  43. package/dist/projections.js.map +1 -0
  44. package/dist/protocol.d.ts +17 -0
  45. package/dist/protocol.js.map +1 -1
  46. package/dist/symbols.d.ts +42 -8
  47. package/dist/symbols.js +160 -35
  48. package/dist/symbols.js.map +1 -1
  49. package/dist/types.d.ts +8 -3
  50. package/dist/types.js.map +1 -1
  51. package/dist/vectorstyle.d.ts +32 -3
  52. package/dist/vectorstyle.js.map +1 -1
  53. package/dist/vectortiles.d.ts +10 -5
  54. package/dist/vectortiles.js +54 -29
  55. package/dist/vectortiles.js.map +1 -1
  56. package/dist/wasm/isard.d.ts +168 -11
  57. package/dist/wasm/isard.js +234 -9
  58. package/dist/wasm/isard_core.d.ts +28 -3
  59. package/dist/wasm/isard_core.js +77 -4
  60. package/dist/wasm/isard_points.d.ts +43 -0
  61. package/dist/wasm/isard_points.js +212 -0
  62. package/package.json +17 -1
package/dist/layers.d.ts CHANGED
@@ -1,5 +1,6 @@
1
+ import type { GeoMap } from './map.ts';
1
2
  import type { LonLat, NetworkStyle, RasterStyle, Tiles3dStyle } from './types.ts';
2
- import type { NetworkStats, Tiles3dStats } from './wasm/isard.js';
3
+ import type { Camera, NetworkStats, Tiles3dStats } from './wasm/isard.js';
3
4
  export declare abstract class Layer {
4
5
  #private;
5
6
  /** Id of the layer in the engine */
@@ -101,3 +102,89 @@ export declare class GroundLayer extends Layer {
101
102
  setVisible(visible: boolean): void;
102
103
  private sendTexture;
103
104
  }
105
+ /** What a custom layer gets to draw a frame (`CustomLayerInterface.render`) */
106
+ export interface CustomFrame {
107
+ /**
108
+ * The model-view-projection matrix of a local frame at a position and altitude (metres above the ellipsoid, as the
109
+ * relief is drawn: times its exaggeration), column-major for `uniformMatrix4fv` or a three.js camera: x east, y
110
+ * north, z up, in metres. Made in double precision relative to the camera, so that what is drawn stays exact at
111
+ * any zoom; draw within a few kilometres of the position (or take one matrix per object far apart). Only during
112
+ * `render`.
113
+ */
114
+ matrixAt(lonLat: LonLat, altitude?: number): Float32Array;
115
+ /** The camera of the frame */
116
+ readonly camera: Camera;
117
+ }
118
+ /**
119
+ * A layer drawn by the page with its own WebGL code, as MapLibre's `CustomLayerInterface`: `render` is called at the
120
+ * layer's place in every frame drawn. It starts with the canvas bound, its viewport set, blending on (`SRC_ALPHA`,
121
+ * `ONE_MINUS_SRC_ALPHA`), no culling, and in `'3d'` mode the depth test on (`LEQUAL`, depth written): the relief, the
122
+ * buildings and the 3D Tiles hide what it draws and what it draws hides them. Whatever WebGL state it changes is set
123
+ * back afterwards; a library that caches the WebGL state (three.js) must forget it first (`renderer.resetState()`).
124
+ *
125
+ * The map is busy drawing meanwhile: `render` reads the frame, not the map (`getCamera` excepted); it may call
126
+ * `requestRender` for an animation.
127
+ */
128
+ export interface CustomLayerInterface {
129
+ /** A name for the application (the map numbers its layers) */
130
+ id?: string;
131
+ /** `'2d'` (the default): drawn over what is under it; `'3d'`: with the depth buffer of the 3D layers */
132
+ renderingMode?: '2d' | '3d';
133
+ /** Creates the WebGL objects: once added, and again after the WebGL context was lost and restored */
134
+ onAdd?(gl: WebGL2RenderingContext, map: GeoMap): void;
135
+ render(gl: WebGL2RenderingContext, frame: CustomFrame): void;
136
+ /** Frees the WebGL objects: the layer is removed, or the map destroyed */
137
+ onRemove?(gl: WebGL2RenderingContext, map: GeoMap): void;
138
+ }
139
+ /** A layer drawn by the page's WebGL code (see `CustomLayerInterface`) */
140
+ export declare class CustomLayer extends Layer {
141
+ /** The application's object */
142
+ readonly implementation: CustomLayerInterface;
143
+ private readonly canvas;
144
+ private readonly owner;
145
+ /** The map's WebGL context, and whether `onAdd` made the layer's objects there (until `onRemove`) */
146
+ private readonly gl;
147
+ private added;
148
+ /** The context was lost since `onAdd`: its objects are gone */
149
+ private stale;
150
+ private readonly lost;
151
+ private readonly frame;
152
+ /** Called by the engine at the layer's place in the frame; the page's errors are reported, the frame goes on */
153
+ private readonly draw;
154
+ remove(): void;
155
+ }
156
+ /** Where and how a model stands */
157
+ export interface ModelInstance {
158
+ lonLat: LonLat;
159
+ /** Metres above the ground (or above the ellipsoid, `altitudeReference: 'sea'`); 0 by default */
160
+ altitude?: number;
161
+ /** Degrees clockwise from the north of the model's front (glTF +Z); 0 by default */
162
+ heading?: number;
163
+ /** Degrees, nose up */
164
+ pitch?: number;
165
+ /** Degrees, right side down */
166
+ roll?: number;
167
+ /** 1 by default: the model's metres */
168
+ scale?: number;
169
+ }
170
+ export interface ModelOptions {
171
+ /** URL of a glTF binary (`.glb`): meshes, textures, Draco, meshopt, KTX2, as in 3D Tiles; or its bytes (`data`) */
172
+ url?: string;
173
+ data?: ArrayBuffer | ArrayBufferView<ArrayBuffer>;
174
+ instances: readonly ModelInstance[];
175
+ /** What the altitudes are above: `'ground'` (the relief, the default) or `'sea'` (the ellipsoid) */
176
+ altitudeReference?: 'ground' | 'sea';
177
+ }
178
+ /** The numbers of instances for the engine: longitude, latitude, altitude, heading, pitch, roll, scale */
179
+ export declare function instanceNumbers(instances: readonly ModelInstance[]): Float64Array;
180
+ /** A glTF model drawn at positions, in one instanced draw; `pickFeature` gives the instance's index */
181
+ export declare class ModelLayer extends Layer {
182
+ private readonly url;
183
+ /** The `blob:` URL of the page's bytes, revoked once the layer is gone */
184
+ private readonly blob;
185
+ private instances;
186
+ private ground;
187
+ /** Replaces the instances (and what their altitudes are above, kept if not given) */
188
+ setInstances(instances: readonly ModelInstance[], altitudeReference?: 'ground' | 'sea'): void;
189
+ remove(): void;
190
+ }
package/dist/layers.js CHANGED
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * Handles of the layers added to a map. Each one keeps what it needs to be created again: after a WebGL context loss,
3
- * the map recreates its engine and every layer in order, with the same handle (its id is updated).
3
+ * the map recreates its engine and every layer in order, with the same handle (its id is updated). Also the page's
4
+ * own 3D content: custom layers (its WebGL code called in every frame) and glTF models drawn at positions.
4
5
  */
5
6
  import { parseColor, rampTexels, stops } from "./features.js";
6
7
  import { mercatorX, mercatorY, toMercator } from "./geo.js";
@@ -27,8 +28,14 @@ export class Layer {
27
28
  }
28
29
  /** @internal Sends what refers to other layers, once every layer of a new engine has its id */
29
30
  relink(_engine) { }
31
+ /** @internal Drawn by the engine with 3D Tiles only (3D Tiles, models): on the core engine, it waits for that one */
32
+ get needsFullEngine() {
33
+ return false;
34
+ }
35
+ /** @internal The layer is removed or its map destroyed: frees what it holds outside the engine */
36
+ dispose() { }
30
37
  remove() {
31
- // Not created yet: a 3D Tiles layer waiting for the engine with 3D Tiles
38
+ // Not created yet: a 3D Tiles layer or a model waiting for the engine with 3D Tiles
32
39
  if (this.#id >= 0)
33
40
  this.map.engine.removeLayer(this.#id);
34
41
  this.#id = -1;
@@ -197,9 +204,13 @@ export class Tiles3dLayer extends Layer {
197
204
  // Kept for its creation while the engine with 3D Tiles loads
198
205
  if (this.id < 0)
199
206
  return;
200
- this.map.engine.setTiles3dStyle(this.id, this.style.maxScreenSpaceError, this.style.opacity);
207
+ this.map.engine.setTiles3dStyle(this.id, this.style.maxScreenSpaceError, this.style.opacity, this.style.pointSize);
201
208
  this.map.requestRender();
202
209
  }
210
+ /** @internal */
211
+ get needsFullEngine() {
212
+ return true;
213
+ }
203
214
  /** Loading counters; undefined once the layer is removed, and while the engine with 3D Tiles loads (see
204
215
  * `GeoMapOptions.tiles3d`) */
205
216
  stats() {
@@ -208,7 +219,7 @@ export class Tiles3dLayer extends Layer {
208
219
  /** @internal */
209
220
  create(engine) {
210
221
  const id = engine.addTiles3d(this.url, this.style.maxScreenSpaceError);
211
- engine.setTiles3dStyle(id, this.style.maxScreenSpaceError, this.style.opacity);
222
+ engine.setTiles3dStyle(id, this.style.maxScreenSpaceError, this.style.opacity, this.style.pointSize);
212
223
  return id;
213
224
  }
214
225
  }
@@ -282,4 +293,154 @@ function mercatorBox([west, south, east, north]) {
282
293
  const [x1, y0] = toMercator([east, north]);
283
294
  return [x0, y0, x1, y1];
284
295
  }
296
+ // ── The page's own 3D content: custom layers, glTF models ──
297
+ /** Reports an error of the page without throwing it here: the console shows it, as an uncaught one */
298
+ function report(error) {
299
+ if (typeof reportError === 'function')
300
+ reportError(error);
301
+ else
302
+ queueMicrotask(() => {
303
+ throw error;
304
+ });
305
+ }
306
+ /** A layer drawn by the page's WebGL code (see `CustomLayerInterface`) */
307
+ export class CustomLayer extends Layer {
308
+ implementation;
309
+ canvas;
310
+ owner;
311
+ /** The map's WebGL context, and whether `onAdd` made the layer's objects there (until `onRemove`) */
312
+ gl;
313
+ added = false;
314
+ /** The context was lost since `onAdd`: its objects are gone */
315
+ stale = false;
316
+ lost = () => {
317
+ this.stale = true;
318
+ };
319
+ frame;
320
+ /** @internal */
321
+ constructor(map,
322
+ /** The application's object */
323
+ implementation, canvas, owner, matrix, camera) {
324
+ super(map);
325
+ this.implementation = implementation;
326
+ this.canvas = canvas;
327
+ this.owner = owner;
328
+ // The context the engine made on the canvas
329
+ this.gl = canvas.getContext('webgl2');
330
+ this.frame = {
331
+ matrixAt: ([lon, lat], altitude = 0) => {
332
+ const m = matrix(lon, lat, altitude);
333
+ if (!m)
334
+ throw new Error('isard: frame.matrixAt is only available during render');
335
+ return m;
336
+ },
337
+ get camera() {
338
+ return camera();
339
+ },
340
+ };
341
+ }
342
+ /** @internal */
343
+ create(engine) {
344
+ // Once, and again on a context restored (not when the map moves onto another engine: the same context)
345
+ if (!this.added || this.stale) {
346
+ if (!this.added)
347
+ this.canvas.addEventListener('webglcontextlost', this.lost);
348
+ this.added = true;
349
+ this.stale = false;
350
+ this.implementation.onAdd?.(this.gl, this.owner);
351
+ }
352
+ return engine.addCustomLayer(this.draw, this.implementation.renderingMode === '3d');
353
+ }
354
+ /** Called by the engine at the layer's place in the frame; the page's errors are reported, the frame goes on */
355
+ draw = () => {
356
+ try {
357
+ this.implementation.render(this.gl, this.frame);
358
+ }
359
+ catch (error) {
360
+ report(error);
361
+ }
362
+ };
363
+ remove() {
364
+ super.remove();
365
+ this.dispose();
366
+ }
367
+ /** @internal The layer is removed or the map destroyed: `onRemove`, unless the context is lost */
368
+ dispose() {
369
+ if (!this.added)
370
+ return;
371
+ this.added = false;
372
+ this.canvas.removeEventListener('webglcontextlost', this.lost);
373
+ if (this.stale)
374
+ return;
375
+ try {
376
+ this.implementation.onRemove?.(this.gl, this.owner);
377
+ }
378
+ catch (error) {
379
+ report(error);
380
+ }
381
+ }
382
+ }
383
+ /** The numbers of instances for the engine: longitude, latitude, altitude, heading, pitch, roll, scale */
384
+ export function instanceNumbers(instances) {
385
+ const out = new Float64Array(instances.length * 7);
386
+ instances.forEach(({ lonLat, altitude = 0, heading = 0, pitch = 0, roll = 0, scale = 1 }, i) => {
387
+ out.set([lonLat[0], lonLat[1], altitude, heading, pitch, roll, scale], i * 7);
388
+ });
389
+ return out;
390
+ }
391
+ /** A glTF model drawn at positions, in one instanced draw; `pickFeature` gives the instance's index */
392
+ export class ModelLayer extends Layer {
393
+ url;
394
+ /** The `blob:` URL of the page's bytes, revoked once the layer is gone */
395
+ blob;
396
+ instances;
397
+ ground;
398
+ /** @internal */
399
+ constructor(map, options) {
400
+ super(map);
401
+ const { url, data } = options;
402
+ if (data) {
403
+ this.blob = URL.createObjectURL(new Blob([data], { type: 'model/gltf-binary' }));
404
+ this.url = this.blob;
405
+ }
406
+ else if (url) {
407
+ // Against the page: the decoding workers fetch it, and a relative URL would be theirs
408
+ const base = typeof document === 'undefined' ? undefined : document.baseURI;
409
+ this.url = base ? new URL(url, base).href : url;
410
+ }
411
+ else {
412
+ throw new Error('isard: a model needs a url or data');
413
+ }
414
+ this.instances = instanceNumbers(options.instances);
415
+ this.ground = options.altitudeReference !== 'sea';
416
+ }
417
+ /** @internal The engine with 3D Tiles decodes and draws the models */
418
+ get needsFullEngine() {
419
+ return true;
420
+ }
421
+ /** Replaces the instances (and what their altitudes are above, kept if not given) */
422
+ setInstances(instances, altitudeReference) {
423
+ this.instances = instanceNumbers(instances);
424
+ if (altitudeReference)
425
+ this.ground = altitudeReference === 'ground';
426
+ // Kept for its creation while the engine with 3D Tiles loads
427
+ if (this.id < 0)
428
+ return;
429
+ this.map.engine.setModelInstances(this.id, this.instances, this.ground);
430
+ this.map.requestRender();
431
+ }
432
+ remove() {
433
+ super.remove();
434
+ this.dispose();
435
+ }
436
+ /** @internal */
437
+ dispose() {
438
+ if (this.blob)
439
+ URL.revokeObjectURL(this.blob);
440
+ }
441
+ /** @internal */
442
+ create(engine) {
443
+ return engine.addModels(this.url, this.instances, this.ground);
444
+ }
445
+ }
285
446
  //# sourceMappingURL=layers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"layers.js","sourceRoot":"","sources":["../src/layers.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AAY5D,MAAM,OAAgB,KAAK;IACzB,GAAG,GAAG,CAAC,CAAC,CAAC;IAET,gBAAgB;IACG,GAAG,CAAY;IAElC,gBAAgB;IAChB,YAAY,GAAc;QACxB,IAAI,CAAC,GAAG,GAAG,GAAG,CAAC;IACjB,CAAC;IAED,oCAAoC;IACpC,IAAI,EAAE;QACJ,OAAO,IAAI,CAAC,GAAG,CAAC;IAClB,CAAC;IAED,wGAAwG;IACxG,MAAM,CAAC,MAAc;QACnB,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC;QACd,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACjC,CAAC;IAED,sGAAsG;IACtG,YAAY;QACV,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC;IAChB,CAAC;IAED,+FAA+F;IAC/F,MAAM,CAAC,OAAe,IAAS,CAAC;IAKhC,MAAM;QACJ,yEAAyE;QACzE,IAAI,IAAI,CAAC,GAAG,IAAI,CAAC;YAAE,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,WAAW,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACzD,IAAI,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC;QACd,IAAI,CAAC,GAAG,CAAC,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context loss,\n * the map recreates its engine and every layer in order, with the same handle (its id is updated).\n */\nimport { parseColor, rampTexels, stops } from './features.ts';\nimport { mercatorX, mercatorY, toMercator } from './geo.ts';\nimport type {\n LayerHost,\n LonLat,\n NetworkOptions,\n NetworkStyle,\n RasterOptions,\n RasterStyle,\n Tiles3dStyle,\n} from './types.ts';\nimport type { Engine, NetworkStats, Tiles3dStats } from './wasm/isard.js';\n\nexport abstract class Layer {\n #id = -1;\n\n /** @internal */\n protected readonly map: LayerHost;\n\n /** @internal */\n constructor(map: LayerHost) {\n this.map = map;\n }\n\n /** Id of the layer in the engine */\n get id(): number {\n return this.#id;\n }\n\n /** @internal Creates the layer in an engine (again after a context loss); its id is -1 if that fails */\n attach(engine: Engine): void {\n this.#id = -1;\n this.#id = this.create(engine);\n }\n\n /** @internal Forgets its id in an engine that is gone (before the layers are created in a new one) */\n forgetEngine(): void {\n this.#id = -1;\n }\n\n /** @internal Sends what refers to other layers, once every layer of a new engine has its id */\n relink(_engine: Engine): void {}\n\n /** @internal */\n protected abstract create(engine: Engine): number;\n\n remove(): void {\n // Not created yet: a 3D Tiles layer waiting for the engine with 3D Tiles\n if (this.#id >= 0) this.map.engine.removeLayer(this.#id);\n this.#id = -1;\n this.map.detach(this);\n this.map.requestRender();\n }\n\n /** Moves the layer under `other`, or on top of every layer (above the labels of a vector basemap too) */\n moveBefore(other: Layer | undefined): void {\n this.map.moveLayer(this, other);\n }\n}\n\n/** Raster tiles (basemaps, overlays) */\nexport class RasterLayer extends Layer {\n /** @internal */\n constructor(\n map: LayerHost,\n private readonly options: Required<Omit<RasterOptions, 'size' | 'loader' | 'grid' | 'attribution'>> & {\n size: number | undefined;\n loader: RasterOptions['loader'] | undefined;\n },\n ) {\n super(map);\n }\n\n /** Changes the opacity or saturation, the other kept */\n setStyle(style: Partial<RasterStyle>): void;\n /** @deprecated Positional form (saturation back to 1 when not given): `setStyle({ opacity, saturation })` */\n setStyle(opacity: number, saturation?: number): void;\n setStyle(style: Partial<RasterStyle> | number, saturation = 1): void {\n const changed = typeof style === 'number' ? { opacity: style, saturation } : style;\n this.options.opacity = changed.opacity ?? this.options.opacity;\n this.options.saturation = changed.saturation ?? this.options.saturation;\n this.map.engine.setRasterStyle(this.id, this.options.opacity, this.options.saturation);\n this.map.requestRender();\n }\n\n /** @internal */\n protected create(engine: Engine): number {\n const { url, minZoom, maxZoom, opacity, saturation, size, loader } = this.options;\n return engine.addRaster(url, minZoom, maxZoom, opacity, saturation, size, loader);\n }\n}\n\n/** Line network colored by a value per node (travel time, water depth…) */\nexport class NetworkLayer extends Layer {\n private values: Float32Array | undefined;\n /** Node and line positions in Mercator, kept for a context loss: f32 offsets from an origin (exact to the centimetre\n * across a region, half the memory of f64) */\n private kept: { origin: [number, number]; nodes: Float32Array; lines: Float32Array | undefined } | undefined;\n\n /** @internal */\n constructor(\n map: LayerHost,\n private geometry: { nodes: Float64Array; edges: Uint32Array; lines: NetworkOptions['lines'] | undefined },\n private costs: Float32Array | undefined,\n private style: NetworkStyle,\n private edgeWidths: Float32Array | undefined,\n ) {\n super(map);\n }\n\n /** One value per node, in node order; negative (or 1e30 and above) = unreached. Costs one texture upload, drawn\n * next frame. */\n setValues(values: Float32Array): void {\n this.values = values;\n this.map.engine.setNetworkValues(this.id, values);\n this.map.requestRender();\n }\n\n /** Costs of the edges, A → B then B → A (see `NetworkOptions.costs`), when the way the network is travelled\n * changes; undefined: values interpolated along the edges. The geometry stays on the graphics card. */\n setCosts(costs: Float32Array | undefined): void {\n this.costs = costs;\n this.map.engine.setNetworkCosts(this.id, costs);\n this.map.requestRender();\n }\n\n setStyle(style: Partial<NetworkStyle>): void {\n const ramp = this.style.ramp;\n this.style = { ...this.style, ...style };\n this.map.engine.setNetworkStyle(this.id, networkStyle(this.style));\n if (this.style.ramp !== ramp)\n this.map.engine.setNetworkRamp(this.id, this.style.ramp && rampTexels(this.style.ramp).rgba);\n this.map.requestRender();\n }\n\n /** Width factor of each edge (undefined: 1 for all) */\n setEdgeWidths(widths: Float32Array | undefined): void {\n this.edgeWidths = widths;\n this.map.engine.setNetworkScales(this.id, widths);\n this.map.requestRender();\n }\n\n /** Pieces in all and drawn in the last frame */\n stats(): NetworkStats | undefined {\n return this.map.engine.networkStats(this.id);\n }\n\n /** @internal */\n protected create(engine: Engine): number {\n const { nodes, edges, lines } = this.geometry;\n let mercator: { nodes: Float64Array; lines: Float64Array | undefined };\n if (this.kept) {\n const { origin, nodes: n, lines: l } = this.kept;\n mercator = { nodes: unpack(n, origin), lines: l && unpack(l, origin) };\n } else {\n // Mercator here: Math.tan and Math.log run natively, several times faster than in WebAssembly\n mercator = { nodes: mercatorPoints(nodes), lines: lines && mercatorPoints(lines.points) };\n const origin: [number, number] = [mercator.nodes[0] ?? 0, mercator.nodes[1] ?? 0];\n this.kept = {\n origin,\n nodes: pack(mercator.nodes, origin),\n lines: mercator.lines && pack(mercator.lines, origin),\n };\n // The degrees are not needed again: millions of points for a region\n this.geometry = { nodes: EMPTY, edges, lines: lines && { start: lines.start, points: EMPTY } };\n }\n const id = engine.addNetwork(\n mercator.nodes,\n edges,\n lines?.start,\n mercator.lines,\n this.costs,\n networkStyle(this.style),\n );\n if (this.style.ramp) engine.setNetworkRamp(id, rampTexels(this.style.ramp).rgba);\n if (this.edgeWidths) engine.setNetworkScales(id, this.edgeWidths);\n if (this.values) engine.setNetworkValues(id, this.values);\n return id;\n }\n}\n\n/** The 25 numbers of a network style for the engine */\nfunction networkStyle(style: NetworkStyle): Float32Array {\n const { width, halo, max, contour, opacity, haloOpacity, unreachedColor, fade } = style;\n return Float32Array.from([\n ...stops(width),\n ...stops(halo),\n max,\n contour,\n opacity,\n haloOpacity,\n ...parseColor(unreachedColor),\n fade,\n ]);\n}\n\nconst EMPTY = new Float64Array(0);\n\n/** Interleaved points as f32 offsets from an origin, and back */\nfunction pack(points: Float64Array, [ox, oy]: [number, number]): Float32Array {\n const out = new Float32Array(points.length);\n for (let i = 0; i < points.length; i += 2) {\n out[i] = (points[i] ?? 0) - ox;\n out[i + 1] = (points[i + 1] ?? 0) - oy;\n }\n return out;\n}\n\nfunction unpack(points: Float32Array, [ox, oy]: [number, number]): Float64Array {\n const out = new Float64Array(points.length);\n for (let i = 0; i < points.length; i += 2) {\n out[i] = (points[i] ?? 0) + ox;\n out[i + 1] = (points[i + 1] ?? 0) + oy;\n }\n return out;\n}\n\n/** Longitudes and latitudes (degrees, interleaved) to Mercator [0, 1], y towards the south */\nfunction mercatorPoints(lonLat: Float64Array): Float64Array {\n const out = new Float64Array(lonLat.length);\n for (let i = 0; i < lonLat.length; i += 2) {\n out[i] = mercatorX(lonLat[i] ?? 0);\n out[i + 1] = mercatorY(lonLat[i + 1] ?? 0);\n }\n return out;\n}\n\n/** Textured meshes in 3D Tiles */\nexport class Tiles3dLayer extends Layer {\n /** @internal */\n constructor(\n map: LayerHost,\n private readonly url: string,\n private style: Tiles3dStyle,\n ) {\n super(map);\n }\n\n setStyle(style: Partial<Tiles3dStyle>): void {\n this.style = { ...this.style, ...style };\n // Kept for its creation while the engine with 3D Tiles loads\n if (this.id < 0) return;\n this.map.engine.setTiles3dStyle(this.id, this.style.maxScreenSpaceError, this.style.opacity);\n this.map.requestRender();\n }\n\n /** Loading counters; undefined once the layer is removed, and while the engine with 3D Tiles loads (see\n * `GeoMapOptions.tiles3d`) */\n stats(): Tiles3dStats | undefined {\n return this.id < 0 ? undefined : this.map.engine.tiles3dStats(this.id);\n }\n\n /** @internal */\n protected create(engine: Engine): number {\n const id = engine.addTiles3d(this.url, this.style.maxScreenSpaceError);\n engine.setTiles3dStyle(id, this.style.maxScreenSpaceError, this.style.opacity);\n return id;\n }\n}\n\n/** A texture of a ground layer (see `GroundLayer`) */\nexport interface GroundTexture {\n /** `r8`, `r8ui`, `r16ui`, `r16i`, `r32ui`, `r32f`, `rg16ui`, `rg32f`, `rgba8`, `rgba8ui`, `rgba16ui`, `rgba32f`:\n * integer formats are read with `usampler2D` / `isampler2D` and `texelFetch` */\n format: string;\n width: number;\n height: number;\n /** Layers of a 2D array (`sampler2DArray`, `usampler2DArray`…); 0 or undefined: a 2D texture */\n depth?: number;\n /** Linear filtering (non-integer formats); default nearest */\n linear?: boolean;\n /** Texels row after row (layer after layer), any typed array; undefined: left empty */\n data?: ArrayBufferView;\n}\n\nexport interface GroundOptions {\n /**\n * GLSL ES 3.0 defining `vec4 ground(vec2 offset)`: the color of the ground (premultiplied alpha, 0 for nothing) at\n * `offset`, the Mercator offset of the pixel from `anchor` (times `ISARD_CIRCUMFERENCE`: metres of EPSG:3857), exact to\n * the millimetre at any zoom. The code declares its own uniforms and samplers; also there: `u_zoom`,\n * `u_pixel_ratio`\n */\n code: string;\n /** Where the offsets are taken from */\n anchor: LonLat;\n /** Box it shows in, `[west, south, east, north]` (default the world): only the ground there is drawn again */\n bounds?: [west: number, south: number, east: number, north: number];\n textures?: Record<string, GroundTexture>;\n uniforms?: Record<string, number | readonly number[]>;\n}\n\nconst bytesOf = (data: ArrayBufferView) => new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n\n/** The application's fragment shader run over the ground, draped on the relief (water depth, heat maps…) */\nexport class GroundLayer extends Layer {\n private readonly textures = new Map<string, GroundTexture>();\n private readonly uniforms = new Map<string, number[]>();\n private visible = true;\n\n /** @internal */\n constructor(\n map: LayerHost,\n private readonly options: GroundOptions,\n ) {\n super(map);\n for (const [name, texture] of Object.entries(options.textures ?? {})) this.textures.set(name, texture);\n for (const [name, value] of Object.entries(options.uniforms ?? {})) this.uniforms.set(name, [value].flat());\n }\n\n /** Creates or replaces a texture of the code's sampler `name` */\n setTexture(name: string, texture: GroundTexture): void {\n this.textures.set(name, texture);\n this.sendTexture(this.map.engine, this.id, name, texture);\n this.map.requestRender();\n }\n\n /**\n * Replaces a region of a texture: `data` holds `width` × `height` texels for (`x`, `y`) of `layer` (2D arrays).\n * Keep the texture's own `data` up to date too if it must survive a WebGL context loss.\n */\n updateTexture(\n name: string,\n data: ArrayBufferView,\n region: { x?: number; y?: number; layer?: number; width: number; height: number },\n ): void {\n const { x = 0, y = 0, layer = 0, width, height } = region;\n this.map.engine.updateGroundTexture(this.id, name, x, y, layer, width, height, bytesOf(data));\n this.map.requestRender();\n }\n\n /** A uniform of the code: a number, or numbers for vectors, arrays and matrices (column major) */\n setUniform(name: string, value: number | readonly number[]): void {\n const values = [value].flat();\n this.uniforms.set(name, values);\n this.map.engine.setGroundUniform(this.id, name, Float64Array.from(values));\n this.map.requestRender();\n }\n\n setBounds(bounds: [west: number, south: number, east: number, north: number]): void {\n this.options.bounds = bounds;\n this.map.engine.setGroundBounds(this.id, ...mercatorBox(bounds));\n this.map.requestRender();\n }\n\n setVisible(visible: boolean): void {\n this.visible = visible;\n this.map.engine.setGroundVisible(this.id, visible);\n this.map.requestRender();\n }\n\n private sendTexture(engine: Engine, id: number, name: string, t: GroundTexture): void {\n const data = t.data && bytesOf(t.data);\n engine.setGroundTexture(id, name, t.format, t.width, t.height, t.depth ?? 0, t.linear ?? false, data);\n }\n\n /** @internal */\n protected create(engine: Engine): number {\n const [ax, ay] = toMercator(this.options.anchor);\n const id = engine.addGround(\n this.options.code,\n ax,\n ay,\n ...mercatorBox(this.options.bounds ?? [-180, -85.06, 180, 85.06]),\n );\n for (const [name, texture] of this.textures) this.sendTexture(engine, id, name, texture);\n for (const [name, values] of this.uniforms) engine.setGroundUniform(id, name, Float64Array.from(values));\n engine.setGroundVisible(id, this.visible);\n return id;\n }\n}\n\n/** A lon/lat box to Mercator min x, min y, max x, max y (y towards the south) */\nfunction mercatorBox([west, south, east, north]: [number, number, number, number]): [number, number, number, number] {\n const [x0, y1] = toMercator([west, south]);\n const [x1, y0] = toMercator([east, north]);\n return [x0, y0, x1, y1];\n}\n"]}
1
+ {"version":3,"file":"layers.js","sourceRoot":"","sources":["../src/layers.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,SAAS,EAAE,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,EAAE,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,MAAM,CAAC,CAAC;IACjE,CAAC;CACF","sourcesContent":["/**\n * Handles of the layers added to a map. Each one keeps what it needs to be created again: after a WebGL context loss,\n * the map recreates its engine and every layer in order, with the same handle (its id is updated). Also the page's\n * own 3D content: custom layers (its WebGL code called in every frame) and glTF models drawn at positions.\n */\nimport { parseColor, rampTexels, stops } from './features.ts';\nimport { mercatorX, mercatorY, toMercator } from './geo.ts';\nimport type { GeoMap } from './map.ts';\nimport type {\n LayerHost,\n LonLat,\n NetworkOptions,\n NetworkStyle,\n RasterOptions,\n RasterStyle,\n Tiles3dStyle,\n} from './types.ts';\nimport type { Camera, Engine, NetworkStats, Tiles3dStats } from './wasm/isard.js';\n\nexport abstract class Layer {\n #id = -1;\n\n /** @internal */\n protected readonly map: LayerHost;\n\n /** @internal */\n constructor(map: LayerHost) {\n this.map = map;\n }\n\n /** Id of the layer in the engine */\n get id(): number {\n return this.#id;\n }\n\n /** @internal Creates the layer in an engine (again after a context loss); its id is -1 if that fails */\n attach(engine: Engine): void {\n this.#id = -1;\n this.#id = this.create(engine);\n }\n\n /** @internal Forgets its id in an engine that is gone (before the layers are created in a new one) */\n forgetEngine(): void {\n this.#id = -1;\n }\n\n /** @internal Sends what refers to other layers, once every layer of a new engine has its id */\n relink(_engine: Engine): void {}\n\n /** @internal Drawn by the engine with 3D Tiles only (3D Tiles, models): on the core engine, it waits for that one */\n get needsFullEngine(): boolean {\n return false;\n }\n\n /** @internal The layer is removed or its map destroyed: frees what it holds outside the engine */\n dispose(): void {}\n\n /** @internal */\n protected abstract create(engine: Engine): number;\n\n remove(): void {\n // Not created yet: a 3D Tiles layer or a model waiting for the engine with 3D Tiles\n if (this.#id >= 0) this.map.engine.removeLayer(this.#id);\n this.#id = -1;\n this.map.detach(this);\n this.map.requestRender();\n }\n\n /** Moves the layer under `other`, or on top of every layer (above the labels of a vector basemap too) */\n moveBefore(other: Layer | undefined): void {\n this.map.moveLayer(this, other);\n }\n}\n\n/** Raster tiles (basemaps, overlays) */\nexport class RasterLayer extends Layer {\n /** @internal */\n constructor(\n map: LayerHost,\n private readonly options: Required<Omit<RasterOptions, 'size' | 'loader' | 'grid' | 'attribution'>> & {\n size: number | undefined;\n loader: RasterOptions['loader'] | undefined;\n },\n ) {\n super(map);\n }\n\n /** Changes the opacity or saturation, the other kept */\n setStyle(style: Partial<RasterStyle>): void;\n /** @deprecated Positional form (saturation back to 1 when not given): `setStyle({ opacity, saturation })` */\n setStyle(opacity: number, saturation?: number): void;\n setStyle(style: Partial<RasterStyle> | number, saturation = 1): void {\n const changed = typeof style === 'number' ? { opacity: style, saturation } : style;\n this.options.opacity = changed.opacity ?? this.options.opacity;\n this.options.saturation = changed.saturation ?? this.options.saturation;\n this.map.engine.setRasterStyle(this.id, this.options.opacity, this.options.saturation);\n this.map.requestRender();\n }\n\n /** @internal */\n protected create(engine: Engine): number {\n const { url, minZoom, maxZoom, opacity, saturation, size, loader } = this.options;\n return engine.addRaster(url, minZoom, maxZoom, opacity, saturation, size, loader);\n }\n}\n\n/** Line network colored by a value per node (travel time, water depth…) */\nexport class NetworkLayer extends Layer {\n private values: Float32Array | undefined;\n /** Node and line positions in Mercator, kept for a context loss: f32 offsets from an origin (exact to the centimetre\n * across a region, half the memory of f64) */\n private kept: { origin: [number, number]; nodes: Float32Array; lines: Float32Array | undefined } | undefined;\n\n /** @internal */\n constructor(\n map: LayerHost,\n private geometry: { nodes: Float64Array; edges: Uint32Array; lines: NetworkOptions['lines'] | undefined },\n private costs: Float32Array | undefined,\n private style: NetworkStyle,\n private edgeWidths: Float32Array | undefined,\n ) {\n super(map);\n }\n\n /** One value per node, in node order; negative (or 1e30 and above) = unreached. Costs one texture upload, drawn\n * next frame. */\n setValues(values: Float32Array): void {\n this.values = values;\n this.map.engine.setNetworkValues(this.id, values);\n this.map.requestRender();\n }\n\n /** Costs of the edges, A → B then B → A (see `NetworkOptions.costs`), when the way the network is travelled\n * changes; undefined: values interpolated along the edges. The geometry stays on the graphics card. */\n setCosts(costs: Float32Array | undefined): void {\n this.costs = costs;\n this.map.engine.setNetworkCosts(this.id, costs);\n this.map.requestRender();\n }\n\n setStyle(style: Partial<NetworkStyle>): void {\n const ramp = this.style.ramp;\n this.style = { ...this.style, ...style };\n this.map.engine.setNetworkStyle(this.id, networkStyle(this.style));\n if (this.style.ramp !== ramp)\n this.map.engine.setNetworkRamp(this.id, this.style.ramp && rampTexels(this.style.ramp).rgba);\n this.map.requestRender();\n }\n\n /** Width factor of each edge (undefined: 1 for all) */\n setEdgeWidths(widths: Float32Array | undefined): void {\n this.edgeWidths = widths;\n this.map.engine.setNetworkScales(this.id, widths);\n this.map.requestRender();\n }\n\n /** Pieces in all and drawn in the last frame */\n stats(): NetworkStats | undefined {\n return this.map.engine.networkStats(this.id);\n }\n\n /** @internal */\n protected create(engine: Engine): number {\n const { nodes, edges, lines } = this.geometry;\n let mercator: { nodes: Float64Array; lines: Float64Array | undefined };\n if (this.kept) {\n const { origin, nodes: n, lines: l } = this.kept;\n mercator = { nodes: unpack(n, origin), lines: l && unpack(l, origin) };\n } else {\n // Mercator here: Math.tan and Math.log run natively, several times faster than in WebAssembly\n mercator = { nodes: mercatorPoints(nodes), lines: lines && mercatorPoints(lines.points) };\n const origin: [number, number] = [mercator.nodes[0] ?? 0, mercator.nodes[1] ?? 0];\n this.kept = {\n origin,\n nodes: pack(mercator.nodes, origin),\n lines: mercator.lines && pack(mercator.lines, origin),\n };\n // The degrees are not needed again: millions of points for a region\n this.geometry = { nodes: EMPTY, edges, lines: lines && { start: lines.start, points: EMPTY } };\n }\n const id = engine.addNetwork(\n mercator.nodes,\n edges,\n lines?.start,\n mercator.lines,\n this.costs,\n networkStyle(this.style),\n );\n if (this.style.ramp) engine.setNetworkRamp(id, rampTexels(this.style.ramp).rgba);\n if (this.edgeWidths) engine.setNetworkScales(id, this.edgeWidths);\n if (this.values) engine.setNetworkValues(id, this.values);\n return id;\n }\n}\n\n/** The 25 numbers of a network style for the engine */\nfunction networkStyle(style: NetworkStyle): Float32Array {\n const { width, halo, max, contour, opacity, haloOpacity, unreachedColor, fade } = style;\n return Float32Array.from([\n ...stops(width),\n ...stops(halo),\n max,\n contour,\n opacity,\n haloOpacity,\n ...parseColor(unreachedColor),\n fade,\n ]);\n}\n\nconst EMPTY = new Float64Array(0);\n\n/** Interleaved points as f32 offsets from an origin, and back */\nfunction pack(points: Float64Array, [ox, oy]: [number, number]): Float32Array {\n const out = new Float32Array(points.length);\n for (let i = 0; i < points.length; i += 2) {\n out[i] = (points[i] ?? 0) - ox;\n out[i + 1] = (points[i + 1] ?? 0) - oy;\n }\n return out;\n}\n\nfunction unpack(points: Float32Array, [ox, oy]: [number, number]): Float64Array {\n const out = new Float64Array(points.length);\n for (let i = 0; i < points.length; i += 2) {\n out[i] = (points[i] ?? 0) + ox;\n out[i + 1] = (points[i + 1] ?? 0) + oy;\n }\n return out;\n}\n\n/** Longitudes and latitudes (degrees, interleaved) to Mercator [0, 1], y towards the south */\nfunction mercatorPoints(lonLat: Float64Array): Float64Array {\n const out = new Float64Array(lonLat.length);\n for (let i = 0; i < lonLat.length; i += 2) {\n out[i] = mercatorX(lonLat[i] ?? 0);\n out[i + 1] = mercatorY(lonLat[i + 1] ?? 0);\n }\n return out;\n}\n\n/** Textured meshes in 3D Tiles */\nexport class Tiles3dLayer extends Layer {\n /** @internal */\n constructor(\n map: LayerHost,\n private readonly url: string,\n private style: Tiles3dStyle,\n ) {\n super(map);\n }\n\n setStyle(style: Partial<Tiles3dStyle>): void {\n this.style = { ...this.style, ...style };\n // Kept for its creation while the engine with 3D Tiles loads\n if (this.id < 0) return;\n this.map.engine.setTiles3dStyle(this.id, this.style.maxScreenSpaceError, this.style.opacity, this.style.pointSize);\n this.map.requestRender();\n }\n\n /** @internal */\n override get needsFullEngine(): boolean {\n return true;\n }\n\n /** Loading counters; undefined once the layer is removed, and while the engine with 3D Tiles loads (see\n * `GeoMapOptions.tiles3d`) */\n stats(): Tiles3dStats | undefined {\n return this.id < 0 ? undefined : this.map.engine.tiles3dStats(this.id);\n }\n\n /** @internal */\n protected create(engine: Engine): number {\n const id = engine.addTiles3d(this.url, this.style.maxScreenSpaceError);\n engine.setTiles3dStyle(id, this.style.maxScreenSpaceError, this.style.opacity, this.style.pointSize);\n return id;\n }\n}\n\n/** A texture of a ground layer (see `GroundLayer`) */\nexport interface GroundTexture {\n /** `r8`, `r8ui`, `r16ui`, `r16i`, `r32ui`, `r32f`, `rg16ui`, `rg32f`, `rgba8`, `rgba8ui`, `rgba16ui`, `rgba32f`:\n * integer formats are read with `usampler2D` / `isampler2D` and `texelFetch` */\n format: string;\n width: number;\n height: number;\n /** Layers of a 2D array (`sampler2DArray`, `usampler2DArray`…); 0 or undefined: a 2D texture */\n depth?: number;\n /** Linear filtering (non-integer formats); default nearest */\n linear?: boolean;\n /** Texels row after row (layer after layer), any typed array; undefined: left empty */\n data?: ArrayBufferView;\n}\n\nexport interface GroundOptions {\n /**\n * GLSL ES 3.0 defining `vec4 ground(vec2 offset)`: the color of the ground (premultiplied alpha, 0 for nothing) at\n * `offset`, the Mercator offset of the pixel from `anchor` (times `ISARD_CIRCUMFERENCE`: metres of EPSG:3857), exact to\n * the millimetre at any zoom. The code declares its own uniforms and samplers; also there: `u_zoom`,\n * `u_pixel_ratio`\n */\n code: string;\n /** Where the offsets are taken from */\n anchor: LonLat;\n /** Box it shows in, `[west, south, east, north]` (default the world): only the ground there is drawn again */\n bounds?: [west: number, south: number, east: number, north: number];\n textures?: Record<string, GroundTexture>;\n uniforms?: Record<string, number | readonly number[]>;\n}\n\nconst bytesOf = (data: ArrayBufferView) => new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n\n/** The application's fragment shader run over the ground, draped on the relief (water depth, heat maps…) */\nexport class GroundLayer extends Layer {\n private readonly textures = new Map<string, GroundTexture>();\n private readonly uniforms = new Map<string, number[]>();\n private visible = true;\n\n /** @internal */\n constructor(\n map: LayerHost,\n private readonly options: GroundOptions,\n ) {\n super(map);\n for (const [name, texture] of Object.entries(options.textures ?? {})) this.textures.set(name, texture);\n for (const [name, value] of Object.entries(options.uniforms ?? {})) this.uniforms.set(name, [value].flat());\n }\n\n /** Creates or replaces a texture of the code's sampler `name` */\n setTexture(name: string, texture: GroundTexture): void {\n this.textures.set(name, texture);\n this.sendTexture(this.map.engine, this.id, name, texture);\n this.map.requestRender();\n }\n\n /**\n * Replaces a region of a texture: `data` holds `width` × `height` texels for (`x`, `y`) of `layer` (2D arrays).\n * Keep the texture's own `data` up to date too if it must survive a WebGL context loss.\n */\n updateTexture(\n name: string,\n data: ArrayBufferView,\n region: { x?: number; y?: number; layer?: number; width: number; height: number },\n ): void {\n const { x = 0, y = 0, layer = 0, width, height } = region;\n this.map.engine.updateGroundTexture(this.id, name, x, y, layer, width, height, bytesOf(data));\n this.map.requestRender();\n }\n\n /** A uniform of the code: a number, or numbers for vectors, arrays and matrices (column major) */\n setUniform(name: string, value: number | readonly number[]): void {\n const values = [value].flat();\n this.uniforms.set(name, values);\n this.map.engine.setGroundUniform(this.id, name, Float64Array.from(values));\n this.map.requestRender();\n }\n\n setBounds(bounds: [west: number, south: number, east: number, north: number]): void {\n this.options.bounds = bounds;\n this.map.engine.setGroundBounds(this.id, ...mercatorBox(bounds));\n this.map.requestRender();\n }\n\n setVisible(visible: boolean): void {\n this.visible = visible;\n this.map.engine.setGroundVisible(this.id, visible);\n this.map.requestRender();\n }\n\n private sendTexture(engine: Engine, id: number, name: string, t: GroundTexture): void {\n const data = t.data && bytesOf(t.data);\n engine.setGroundTexture(id, name, t.format, t.width, t.height, t.depth ?? 0, t.linear ?? false, data);\n }\n\n /** @internal */\n protected create(engine: Engine): number {\n const [ax, ay] = toMercator(this.options.anchor);\n const id = engine.addGround(\n this.options.code,\n ax,\n ay,\n ...mercatorBox(this.options.bounds ?? [-180, -85.06, 180, 85.06]),\n );\n for (const [name, texture] of this.textures) this.sendTexture(engine, id, name, texture);\n for (const [name, values] of this.uniforms) engine.setGroundUniform(id, name, Float64Array.from(values));\n engine.setGroundVisible(id, this.visible);\n return id;\n }\n}\n\n/** A lon/lat box to Mercator min x, min y, max x, max y (y towards the south) */\nfunction mercatorBox([west, south, east, north]: [number, number, number, number]): [number, number, number, number] {\n const [x0, y1] = toMercator([west, south]);\n const [x1, y0] = toMercator([east, north]);\n return [x0, y0, x1, y1];\n}\n\n// ── The page's own 3D content: custom layers, glTF models ──\n\n/** Reports an error of the page without throwing it here: the console shows it, as an uncaught one */\nfunction report(error: unknown): void {\n if (typeof reportError === 'function') reportError(error);\n else\n queueMicrotask(() => {\n throw error;\n });\n}\n\n/** What a custom layer gets to draw a frame (`CustomLayerInterface.render`) */\nexport interface CustomFrame {\n /**\n * The model-view-projection matrix of a local frame at a position and altitude (metres above the ellipsoid, as the\n * relief is drawn: times its exaggeration), column-major for `uniformMatrix4fv` or a three.js camera: x east, y\n * north, z up, in metres. Made in double precision relative to the camera, so that what is drawn stays exact at\n * any zoom; draw within a few kilometres of the position (or take one matrix per object far apart). Only during\n * `render`.\n */\n matrixAt(lonLat: LonLat, altitude?: number): Float32Array;\n /** The camera of the frame */\n readonly camera: Camera;\n}\n\n/**\n * A layer drawn by the page with its own WebGL code, as MapLibre's `CustomLayerInterface`: `render` is called at the\n * layer's place in every frame drawn. It starts with the canvas bound, its viewport set, blending on (`SRC_ALPHA`,\n * `ONE_MINUS_SRC_ALPHA`), no culling, and in `'3d'` mode the depth test on (`LEQUAL`, depth written): the relief, the\n * buildings and the 3D Tiles hide what it draws and what it draws hides them. Whatever WebGL state it changes is set\n * back afterwards; a library that caches the WebGL state (three.js) must forget it first (`renderer.resetState()`).\n *\n * The map is busy drawing meanwhile: `render` reads the frame, not the map (`getCamera` excepted); it may call\n * `requestRender` for an animation.\n */\nexport interface CustomLayerInterface {\n /** A name for the application (the map numbers its layers) */\n id?: string;\n /** `'2d'` (the default): drawn over what is under it; `'3d'`: with the depth buffer of the 3D layers */\n renderingMode?: '2d' | '3d';\n /** Creates the WebGL objects: once added, and again after the WebGL context was lost and restored */\n onAdd?(gl: WebGL2RenderingContext, map: GeoMap): void;\n render(gl: WebGL2RenderingContext, frame: CustomFrame): void;\n /** Frees the WebGL objects: the layer is removed, or the map destroyed */\n onRemove?(gl: WebGL2RenderingContext, map: GeoMap): void;\n}\n\n/** The model-view-projection of a local frame in the engine running the map (`Engine.customMatrix`) */\n/** @internal */\nexport type CustomMatrix = (lon: number, lat: number, altitude: number) => Float32Array | undefined;\n\n/** A layer drawn by the page's WebGL code (see `CustomLayerInterface`) */\nexport class CustomLayer extends Layer {\n /** The map's WebGL context, and whether `onAdd` made the layer's objects there (until `onRemove`) */\n private readonly gl: WebGL2RenderingContext;\n private added = false;\n /** The context was lost since `onAdd`: its objects are gone */\n private stale = false;\n private readonly lost = () => {\n this.stale = true;\n };\n private readonly frame: CustomFrame;\n\n /** @internal */\n constructor(\n map: LayerHost,\n /** The application's object */\n readonly implementation: CustomLayerInterface,\n private readonly canvas: HTMLCanvasElement,\n private readonly owner: GeoMap,\n matrix: CustomMatrix,\n camera: () => Camera,\n ) {\n super(map);\n // The context the engine made on the canvas\n this.gl = canvas.getContext('webgl2') as WebGL2RenderingContext;\n this.frame = {\n matrixAt: ([lon, lat], altitude = 0) => {\n const m = matrix(lon, lat, altitude);\n if (!m) throw new Error('isard: frame.matrixAt is only available during render');\n return m;\n },\n get camera() {\n return camera();\n },\n };\n }\n\n /** @internal */\n protected create(engine: Engine): number {\n // Once, and again on a context restored (not when the map moves onto another engine: the same context)\n if (!this.added || this.stale) {\n if (!this.added) this.canvas.addEventListener('webglcontextlost', this.lost);\n this.added = true;\n this.stale = false;\n this.implementation.onAdd?.(this.gl, this.owner);\n }\n return engine.addCustomLayer(this.draw, this.implementation.renderingMode === '3d');\n }\n\n /** Called by the engine at the layer's place in the frame; the page's errors are reported, the frame goes on */\n private readonly draw = (): void => {\n try {\n this.implementation.render(this.gl, this.frame);\n } catch (error) {\n report(error);\n }\n };\n\n override remove(): void {\n super.remove();\n this.dispose();\n }\n\n /** @internal The layer is removed or the map destroyed: `onRemove`, unless the context is lost */\n override dispose(): void {\n if (!this.added) return;\n this.added = false;\n this.canvas.removeEventListener('webglcontextlost', this.lost);\n if (this.stale) return;\n try {\n this.implementation.onRemove?.(this.gl, this.owner);\n } catch (error) {\n report(error);\n }\n }\n}\n\n/** Where and how a model stands */\nexport interface ModelInstance {\n lonLat: LonLat;\n /** Metres above the ground (or above the ellipsoid, `altitudeReference: 'sea'`); 0 by default */\n altitude?: number;\n /** Degrees clockwise from the north of the model's front (glTF +Z); 0 by default */\n heading?: number;\n /** Degrees, nose up */\n pitch?: number;\n /** Degrees, right side down */\n roll?: number;\n /** 1 by default: the model's metres */\n scale?: number;\n}\n\nexport interface ModelOptions {\n /** URL of a glTF binary (`.glb`): meshes, textures, Draco, meshopt, KTX2, as in 3D Tiles; or its bytes (`data`) */\n url?: string;\n data?: ArrayBuffer | ArrayBufferView<ArrayBuffer>;\n instances: readonly ModelInstance[];\n /** What the altitudes are above: `'ground'` (the relief, the default) or `'sea'` (the ellipsoid) */\n altitudeReference?: 'ground' | 'sea';\n}\n\n/** The numbers of instances for the engine: longitude, latitude, altitude, heading, pitch, roll, scale */\nexport function instanceNumbers(instances: readonly ModelInstance[]): Float64Array {\n const out = new Float64Array(instances.length * 7);\n instances.forEach(({ lonLat, altitude = 0, heading = 0, pitch = 0, roll = 0, scale = 1 }, i) => {\n out.set([lonLat[0], lonLat[1], altitude, heading, pitch, roll, scale], i * 7);\n });\n return out;\n}\n\n/** A glTF model drawn at positions, in one instanced draw; `pickFeature` gives the instance's index */\nexport class ModelLayer extends Layer {\n private readonly url: string;\n /** The `blob:` URL of the page's bytes, revoked once the layer is gone */\n private readonly blob: string | undefined;\n private instances: Float64Array;\n private ground: boolean;\n\n /** @internal */\n constructor(map: LayerHost, options: ModelOptions) {\n super(map);\n const { url, data } = options;\n if (data) {\n this.blob = URL.createObjectURL(new Blob([data], { type: 'model/gltf-binary' }));\n this.url = this.blob;\n } else if (url) {\n // Against the page: the decoding workers fetch it, and a relative URL would be theirs\n const base = typeof document === 'undefined' ? undefined : document.baseURI;\n this.url = base ? new URL(url, base).href : url;\n } else {\n throw new Error('isard: a model needs a url or data');\n }\n this.instances = instanceNumbers(options.instances);\n this.ground = options.altitudeReference !== 'sea';\n }\n\n /** @internal The engine with 3D Tiles decodes and draws the models */\n override get needsFullEngine(): boolean {\n return true;\n }\n\n /** Replaces the instances (and what their altitudes are above, kept if not given) */\n setInstances(instances: readonly ModelInstance[], altitudeReference?: 'ground' | 'sea'): void {\n this.instances = instanceNumbers(instances);\n if (altitudeReference) this.ground = altitudeReference === 'ground';\n // Kept for its creation while the engine with 3D Tiles loads\n if (this.id < 0) return;\n this.map.engine.setModelInstances(this.id, this.instances, this.ground);\n this.map.requestRender();\n }\n\n override remove(): void {\n super.remove();\n this.dispose();\n }\n\n /** @internal */\n override dispose(): void {\n if (this.blob) URL.revokeObjectURL(this.blob);\n }\n\n /** @internal */\n protected create(engine: Engine): number {\n return engine.addModels(this.url, this.instances, this.ground);\n }\n}\n"]}
package/dist/loader.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Pool of decoding workers for 3D Tiles content. The engine calls `load` and `abort` (`TileLoaderLike`); the main
3
- * thread then only uploads the decoded arrays to the GPU.
2
+ * Pool of decoding workers for 3D Tiles content and point clouds. The engine calls `load`, `loadPoints` and `abort`
3
+ * (`TileLoaderLike`); the main thread then only uploads the decoded arrays to the GPU.
4
4
  */
5
5
  import type { DecoderUrls } from './decoders.ts';
6
6
  import type { DecodedTile, TextureFormats, TileLoaderLike } from './wasm/isard.js';
@@ -10,15 +10,21 @@ export declare class TileLoader implements TileLoaderLike {
10
10
  private readonly size;
11
11
  private readonly decoders;
12
12
  private readonly formats;
13
+ /** URL of the point cloud module, for the workers */
14
+ private readonly points;
13
15
  private workers;
14
16
  /** Requests in flight per worker */
15
17
  private readonly busy;
16
18
  private readonly pending;
17
19
  /** Every worker failed: why */
18
20
  private failed;
19
- constructor(module: WebAssembly.Module, workerUrl: string | URL, size: number, decoders: DecoderUrls, formats: TextureFormats);
21
+ constructor(module: WebAssembly.Module, workerUrl: string | URL, size: number, decoders: DecoderUrls, formats: TextureFormats,
22
+ /** URL of the point cloud module, for the workers */
23
+ points?: string);
20
24
  /** Called by the engine: fetch and decode off the main thread, on the least busy worker */
21
25
  load(id: number, url: string, transform: Float64Array, yUp: boolean, reload: boolean, priority?: 'high' | 'low'): Promise<DecodedTile>;
26
+ /** Called by the engine: the points of a COPC node, fetched (a range request) and decoded off the main thread */
27
+ loadPoints(id: number, url: string, offset: number, size: number, laz: Uint8Array, layout: Float64Array, grid: Float64Array, count: number, priority?: 'high' | 'low'): Promise<Uint8Array<ArrayBuffer>>;
22
28
  abort(id: number): void;
23
29
  destroy(): void;
24
30
  /** Workers start with the first tile: a map without 3D Tiles costs nothing */
package/dist/loader.js CHANGED
@@ -4,18 +4,22 @@ export class TileLoader {
4
4
  size;
5
5
  decoders;
6
6
  formats;
7
+ points;
7
8
  workers = [];
8
9
  /** Requests in flight per worker */
9
10
  busy = new Map();
10
11
  pending = new Map();
11
12
  /** Every worker failed: why */
12
13
  failed;
13
- constructor(module, workerUrl, size, decoders, formats) {
14
+ constructor(module, workerUrl, size, decoders, formats,
15
+ /** URL of the point cloud module, for the workers */
16
+ points = '') {
14
17
  this.module = module;
15
18
  this.workerUrl = workerUrl;
16
19
  this.size = size;
17
20
  this.decoders = decoders;
18
21
  this.formats = formats;
22
+ this.points = points;
19
23
  }
20
24
  /** Called by the engine: fetch and decode off the main thread, on the least busy worker */
21
25
  load(id, url, transform, yUp, reload, priority) {
@@ -24,10 +28,22 @@ export class TileLoader {
24
28
  const worker = this.leastBusy();
25
29
  this.busy.set(worker, (this.busy.get(worker) ?? 0) + 1);
26
30
  return new Promise((resolve, reject) => {
27
- this.pending.set(id, { resolve, reject, worker });
31
+ this.pending.set(id, { resolve: resolve, reject, worker });
28
32
  this.send(worker, { type: 'load', id, url, transform, yUp, reload, ...(priority ? { priority } : {}) });
29
33
  });
30
34
  }
35
+ /** Called by the engine: the points of a COPC node, fetched (a range request) and decoded off the main thread */
36
+ loadPoints(id, url, offset, size, laz, layout, grid, count, priority) {
37
+ if (this.failed)
38
+ return Promise.reject(this.failed);
39
+ const worker = this.leastBusy();
40
+ this.busy.set(worker, (this.busy.get(worker) ?? 0) + 1);
41
+ return new Promise((resolve, reject) => {
42
+ this.pending.set(id, { resolve: resolve, reject, worker });
43
+ const message = { type: 'points', id, url, offset, size, laz, layout, grid, count };
44
+ this.send(worker, { ...message, ...(priority ? { priority } : {}) });
45
+ });
46
+ }
31
47
  abort(id) {
32
48
  const pending = this.pending.get(id);
33
49
  if (pending)
@@ -54,7 +70,8 @@ export class TileLoader {
54
70
  this.fail(worker, `the decoding worker ${this.workerUrl} failed${event.message ? `: ${event.message}` : ''}`);
55
71
  };
56
72
  worker.onmessageerror = () => this.fail(worker, `the decoding worker ${this.workerUrl} sent an unreadable message`);
57
- this.send(worker, { type: 'init', module: this.module, decoders: this.decoders, formats: this.formats });
73
+ const { module, decoders, formats, points } = this;
74
+ this.send(worker, { type: 'init', module, decoders, formats, points });
58
75
  this.workers.push(worker);
59
76
  this.busy.set(worker, 0);
60
77
  }
@@ -77,6 +94,8 @@ export class TileLoader {
77
94
  this.pending.delete(reply.id);
78
95
  if (reply.type === 'tile')
79
96
  pending.resolve(reply.tile);
97
+ else if (reply.type === 'points')
98
+ pending.resolve(reply.vertices);
80
99
  else if (reply.aborted)
81
100
  pending.reject(new DOMException(`tile ${reply.id} aborted`, 'AbortError'));
82
101
  else
@@ -1 +1 @@
1
- {"version":3,"file":"loader.js","sourceRoot":"","sources":["../src/loader.ts"],"names":[],"mappings":"AAcA,MAAM,OAAO,UAAU;IASF;IACA;IACA;IACA;IACA;IAZX,OAAO,GAAa,EAAE,CAAC;IAC/B,oCAAoC;IACnB,IAAI,GAAG,IAAI,GAAG,EAAkB,CAAC;IACjC,OAAO,GAAG,IAAI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,CAAC,MAAM,GAAG,KAAK,CAAC;IACrD,CAAC;CACF","sourcesContent":["/**\n * Pool of decoding workers for 3D Tiles content. The engine calls `load` and `abort` (`TileLoaderLike`); the main\n * thread then only uploads the decoded arrays to the GPU.\n */\nimport type { DecoderUrls } from './decoders.ts';\nimport type { WorkerReply, WorkerRequest } from './protocol.ts';\nimport type { DecodedTile, TextureFormats, TileLoaderLike } from './wasm/isard.js';\n\ninterface Pending {\n resolve: (tile: DecodedTile) => void;\n reject: (error: Error) => void;\n worker: Worker;\n}\n\nexport class TileLoader implements TileLoaderLike {\n private workers: Worker[] = [];\n /** Requests in flight per worker */\n private readonly busy = new Map<Worker, number>();\n private readonly pending = new Map<number, Pending>();\n /** Every worker failed: why */\n private failed: Error | undefined;\n\n constructor(\n private readonly module: WebAssembly.Module,\n private readonly workerUrl: string | URL,\n private readonly size: number,\n private readonly decoders: DecoderUrls,\n private readonly formats: TextureFormats,\n ) {}\n\n /** Called by the engine: fetch and decode off the main thread, on the least busy worker */\n load(\n id: number,\n url: string,\n transform: Float64Array,\n yUp: boolean,\n reload: boolean,\n priority?: 'high' | 'low',\n ): Promise<DecodedTile> {\n if (this.failed) return Promise.reject(this.failed);\n const worker = this.leastBusy();\n this.busy.set(worker, (this.busy.get(worker) ?? 0) + 1);\n return new Promise((resolve, reject) => {\n this.pending.set(id, { resolve, reject, worker });\n this.send(worker, { type: 'load', id, url, transform, yUp, reload, ...(priority ? { priority } : {}) });\n });\n }\n\n abort(id: number): void {\n const pending = this.pending.get(id);\n if (pending) this.send(pending.worker, { type: 'abort', id });\n }\n\n destroy(): void {\n for (const worker of this.workers) worker.terminate();\n this.workers = [];\n this.busy.clear();\n for (const { reject } of this.pending.values()) reject(new Error('loader destroyed'));\n this.pending.clear();\n }\n\n /** Workers start with the first tile: a map without 3D Tiles costs nothing */\n private leastBusy(): Worker {\n if (this.workers.length === 0) {\n for (let i = 0; i < this.size; i++) {\n const worker = new Worker(this.workerUrl, { type: 'module' });\n worker.onmessage = (event: MessageEvent<WorkerReply>) => this.receive(worker, event.data);\n // A worker that fails to load (a bundler serving it from elsewhere) or to read a message fails its requests\n worker.onerror = (event) => {\n event.preventDefault();\n this.fail(worker, `the decoding worker ${this.workerUrl} failed${event.message ? `: ${event.message}` : ''}`);\n };\n worker.onmessageerror = () =>\n this.fail(worker, `the decoding worker ${this.workerUrl} sent an unreadable message`);\n this.send(worker, { type: 'init', module: this.module, decoders: this.decoders, formats: this.formats });\n this.workers.push(worker);\n this.busy.set(worker, 0);\n }\n }\n let best = this.workers[0] as Worker;\n for (const worker of this.workers) {\n if ((this.busy.get(worker) ?? 0) < (this.busy.get(best) ?? 0)) best = worker;\n }\n return best;\n }\n\n private send(worker: Worker, message: WorkerRequest): void {\n worker.postMessage(message);\n }\n\n private receive(worker: Worker, reply: WorkerReply): void {\n this.busy.set(worker, Math.max(0, (this.busy.get(worker) ?? 1) - 1));\n const pending = this.pending.get(reply.id);\n if (!pending) return;\n this.pending.delete(reply.id);\n if (reply.type === 'tile') pending.resolve(reply.tile);\n else if (reply.aborted) pending.reject(new DOMException(`tile ${reply.id} aborted`, 'AbortError'));\n else pending.reject(new Error(reply.error));\n }\n\n /** Rejects the requests of a failed worker */\n private fail(worker: Worker, message: string): void {\n const error = new Error(\n `isard: ${message}. If a bundler moves the worker, give its URL in the \\`workerUrl\\` option (see \"With a bundler\" in the guide)`,\n );\n for (const [id, pending] of this.pending) {\n if (pending.worker !== worker) continue;\n this.pending.delete(id);\n pending.reject(error);\n }\n // Out of the pool: when none is left, the next requests fail at once\n worker.terminate();\n this.workers = this.workers.filter((w) => w !== worker);\n this.busy.delete(worker);\n if (this.workers.length === 0) this.failed = error;\n }\n}\n"]}
1
+ {"version":3,"file":"loader.js","sourceRoot":"","sources":["../src/loader.ts"],"names":[],"mappings":"AAcA,MAAM,OAAO,UAAU;IASF;IACA;IACA;IACA;IACA;IAEA;IAdX,OAAO,GAAa,EAAE,CAAC;IAC/B,oCAAoC;IACnB,IAAI,GAA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YAAE,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;IACrD,CAAC;CACF","sourcesContent":["/**\n * Pool of decoding workers for 3D Tiles content and point clouds. The engine calls `load`, `loadPoints` and `abort`\n * (`TileLoaderLike`); the main thread then only uploads the decoded arrays to the GPU.\n */\nimport type { DecoderUrls } from './decoders.ts';\nimport type { WorkerReply, WorkerRequest } from './protocol.ts';\nimport type { DecodedTile, TextureFormats, TileLoaderLike } from './wasm/isard.js';\n\ninterface Pending {\n resolve: (result: DecodedTile | Uint8Array<ArrayBuffer>) => void;\n reject: (error: Error) => void;\n worker: Worker;\n}\n\nexport class TileLoader implements TileLoaderLike {\n private workers: Worker[] = [];\n /** Requests in flight per worker */\n private readonly busy = new Map<Worker, number>();\n private readonly pending = new Map<number, Pending>();\n /** Every worker failed: why */\n private failed: Error | undefined;\n\n constructor(\n private readonly module: WebAssembly.Module,\n private readonly workerUrl: string | URL,\n private readonly size: number,\n private readonly decoders: DecoderUrls,\n private readonly formats: TextureFormats,\n /** URL of the point cloud module, for the workers */\n private readonly points: string = '',\n ) {}\n\n /** Called by the engine: fetch and decode off the main thread, on the least busy worker */\n load(\n id: number,\n url: string,\n transform: Float64Array,\n yUp: boolean,\n reload: boolean,\n priority?: 'high' | 'low',\n ): Promise<DecodedTile> {\n if (this.failed) return Promise.reject(this.failed);\n const worker = this.leastBusy();\n this.busy.set(worker, (this.busy.get(worker) ?? 0) + 1);\n return new Promise((resolve, reject) => {\n this.pending.set(id, { resolve: resolve as Pending['resolve'], reject, worker });\n this.send(worker, { type: 'load', id, url, transform, yUp, reload, ...(priority ? { priority } : {}) });\n });\n }\n\n /** Called by the engine: the points of a COPC node, fetched (a range request) and decoded off the main thread */\n loadPoints(\n id: number,\n url: string,\n offset: number,\n size: number,\n laz: Uint8Array,\n layout: Float64Array,\n grid: Float64Array,\n count: number,\n priority?: 'high' | 'low',\n ): Promise<Uint8Array<ArrayBuffer>> {\n if (this.failed) return Promise.reject(this.failed);\n const worker = this.leastBusy();\n this.busy.set(worker, (this.busy.get(worker) ?? 0) + 1);\n return new Promise((resolve, reject) => {\n this.pending.set(id, { resolve: resolve as Pending['resolve'], reject, worker });\n const message = { type: 'points', id, url, offset, size, laz, layout, grid, count } as const;\n this.send(worker, { ...message, ...(priority ? { priority } : {}) });\n });\n }\n\n abort(id: number): void {\n const pending = this.pending.get(id);\n if (pending) this.send(pending.worker, { type: 'abort', id });\n }\n\n destroy(): void {\n for (const worker of this.workers) worker.terminate();\n this.workers = [];\n this.busy.clear();\n for (const { reject } of this.pending.values()) reject(new Error('loader destroyed'));\n this.pending.clear();\n }\n\n /** Workers start with the first tile: a map without 3D Tiles costs nothing */\n private leastBusy(): Worker {\n if (this.workers.length === 0) {\n for (let i = 0; i < this.size; i++) {\n const worker = new Worker(this.workerUrl, { type: 'module' });\n worker.onmessage = (event: MessageEvent<WorkerReply>) => this.receive(worker, event.data);\n // A worker that fails to load (a bundler serving it from elsewhere) or to read a message fails its requests\n worker.onerror = (event) => {\n event.preventDefault();\n this.fail(worker, `the decoding worker ${this.workerUrl} failed${event.message ? `: ${event.message}` : ''}`);\n };\n worker.onmessageerror = () =>\n this.fail(worker, `the decoding worker ${this.workerUrl} sent an unreadable message`);\n const { module, decoders, formats, points } = this;\n this.send(worker, { type: 'init', module, decoders, formats, points });\n this.workers.push(worker);\n this.busy.set(worker, 0);\n }\n }\n let best = this.workers[0] as Worker;\n for (const worker of this.workers) {\n if ((this.busy.get(worker) ?? 0) < (this.busy.get(best) ?? 0)) best = worker;\n }\n return best;\n }\n\n private send(worker: Worker, message: WorkerRequest): void {\n worker.postMessage(message);\n }\n\n private receive(worker: Worker, reply: WorkerReply): void {\n this.busy.set(worker, Math.max(0, (this.busy.get(worker) ?? 1) - 1));\n const pending = this.pending.get(reply.id);\n if (!pending) return;\n this.pending.delete(reply.id);\n if (reply.type === 'tile') pending.resolve(reply.tile);\n else if (reply.type === 'points') pending.resolve(reply.vertices);\n else if (reply.aborted) pending.reject(new DOMException(`tile ${reply.id} aborted`, 'AbortError'));\n else pending.reject(new Error(reply.error));\n }\n\n /** Rejects the requests of a failed worker */\n private fail(worker: Worker, message: string): void {\n const error = new Error(\n `isard: ${message}. If a bundler moves the worker, give its URL in the \\`workerUrl\\` option (see \"With a bundler\" in the guide)`,\n );\n for (const [id, pending] of this.pending) {\n if (pending.worker !== worker) continue;\n this.pending.delete(id);\n pending.reject(error);\n }\n // Out of the pool: when none is left, the next requests fail at once\n worker.terminate();\n this.workers = this.workers.filter((w) => w !== worker);\n this.busy.delete(worker);\n if (this.workers.length === 0) this.failed = error;\n }\n}\n"]}