@tangram.gl/basemap-layers 0.0.0 → 10.0.0-alpha.3

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 (139) hide show
  1. package/README.md +12 -7
  2. package/THIRD-PARTY-NOTICES.md +7 -5
  3. package/dist/geojson-task-worker.js +3166 -0
  4. package/dist/geojson-task-worker.js.map +6 -0
  5. package/dist/geojson-worker.js +1089 -7
  6. package/dist/geojson-worker.js.map +3 -3
  7. package/dist/index.cjs +9588 -2093
  8. package/dist/index.cjs.map +3 -3
  9. package/dist/index.js +9599 -2090
  10. package/dist/index.js.map +3 -3
  11. package/dist/map-style.cjs +456 -20
  12. package/dist/map-style.cjs.map +3 -3
  13. package/dist/map-style.js +456 -19
  14. package/dist/map-style.js.map +2 -2
  15. package/dist/types/basemap-error.d.ts +52 -0
  16. package/dist/types/basemap-layer.d.ts +378 -25
  17. package/dist/types/basemap-protocol.d.ts +91 -0
  18. package/dist/types/basemap-request.d.ts +73 -0
  19. package/dist/types/circle-layer.d.ts +65 -8
  20. package/dist/types/color-relief-layer.d.ts +184 -0
  21. package/dist/types/dem-pixels.d.ts +40 -0
  22. package/dist/types/feature-state.d.ts +55 -0
  23. package/dist/types/fill-extrusion-lighting-extension.d.ts +1 -2
  24. package/dist/types/fill-outline-extension.d.ts +2 -3
  25. package/dist/types/fill-pattern.d.ts +35 -3
  26. package/dist/types/fill-style-extensions.d.ts +11 -59
  27. package/dist/types/geojson-resource.d.ts +18 -0
  28. package/dist/types/geojson-source.d.ts +13 -2
  29. package/dist/types/geojson-task-handler.d.ts +2 -0
  30. package/dist/types/geojson-task.d.ts +26 -0
  31. package/dist/types/geojson-tiler.d.ts +29 -2
  32. package/dist/types/geojson-worker.d.ts +5 -1
  33. package/dist/types/globe-horizon-extension.d.ts +2 -45
  34. package/dist/types/globe-layers.d.ts +141 -45
  35. package/dist/types/globe-line-angle-extension.d.ts +20 -17
  36. package/dist/types/glyph-store.d.ts +10 -1
  37. package/dist/types/heatmap-layer.d.ts +99 -0
  38. package/dist/types/hillshade-layer.d.ts +159 -27
  39. package/dist/types/icon-text-fit.d.ts +92 -0
  40. package/dist/types/image-source-layer.d.ts +142 -0
  41. package/dist/types/index.d.ts +25 -1
  42. package/dist/types/line-blur-extension.d.ts +3 -11
  43. package/dist/types/line-dash-extension.d.ts +53 -0
  44. package/dist/types/line-gradient-extension.d.ts +69 -0
  45. package/dist/types/line-metrics.d.ts +24 -0
  46. package/dist/types/line-pattern-extension.d.ts +50 -0
  47. package/dist/types/line-shape-extension.d.ts +76 -0
  48. package/dist/types/map-style-loader.d.ts +1 -1
  49. package/dist/types/map-style.d.ts +2 -2
  50. package/dist/types/mvt-label-layer.d.ts +111 -20
  51. package/dist/types/pmtiles-source.d.ts +38 -0
  52. package/dist/types/projected-background-layer.d.ts +63 -0
  53. package/dist/types/projected-bitmap-layer.d.ts +58 -0
  54. package/dist/types/projected-tile-data.d.ts +16 -0
  55. package/dist/types/projected-tile-selection.d.ts +72 -0
  56. package/dist/types/projected-tileset.d.ts +92 -0
  57. package/dist/types/projected-viewport.d.ts +76 -0
  58. package/dist/types/raster-color-extension.d.ts +4 -7
  59. package/dist/types/raster-fade.d.ts +155 -0
  60. package/dist/types/raster-tile-fingerprint.d.ts +11 -0
  61. package/dist/types/raster-tile-loader.d.ts +80 -0
  62. package/dist/types/shader-injection-plugin.d.ts +8 -0
  63. package/dist/types/source-features.d.ts +58 -0
  64. package/dist/types/source-tiles.d.ts +32 -0
  65. package/dist/types/sprite.d.ts +37 -3
  66. package/dist/types/stretch-icon-layer.d.ts +28 -0
  67. package/dist/types/style-accessor.d.ts +50 -12
  68. package/dist/types/style-expression.d.ts +22 -2
  69. package/dist/types/style-resolver.d.ts +47 -2
  70. package/dist/types/terrain-query.d.ts +39 -0
  71. package/dist/types/zoom-load-gate.d.ts +22 -0
  72. package/dist/types/zoom-paint-extension.d.ts +80 -11
  73. package/package.json +24 -21
  74. package/src/basemap-error.ts +82 -0
  75. package/src/basemap-layer.ts +1289 -101
  76. package/src/basemap-protocol.ts +353 -0
  77. package/src/basemap-request.ts +212 -0
  78. package/src/circle-layer.ts +430 -54
  79. package/src/color-relief-layer.ts +572 -0
  80. package/src/dem-pixels.ts +174 -0
  81. package/src/feature-state.ts +164 -0
  82. package/src/fill-extrusion-lighting-extension.ts +126 -9
  83. package/src/fill-outline-extension.ts +4 -4
  84. package/src/fill-pattern.ts +87 -9
  85. package/src/fill-style-extensions.ts +114 -44
  86. package/src/geojson-resource.ts +58 -0
  87. package/src/geojson-source.ts +106 -85
  88. package/src/geojson-task-handler.ts +11 -0
  89. package/src/geojson-task-worker.ts +8 -0
  90. package/src/geojson-task.ts +34 -0
  91. package/src/geojson-tiler.ts +270 -4
  92. package/src/geojson-worker.ts +36 -6
  93. package/src/globe-horizon-extension.ts +14 -4
  94. package/src/globe-layers.ts +1905 -406
  95. package/src/globe-line-angle-extension.ts +183 -23
  96. package/src/glyph-store.ts +28 -6
  97. package/src/heatmap-layer.ts +591 -0
  98. package/src/hillshade-layer.ts +309 -88
  99. package/src/icon-text-fit.ts +358 -0
  100. package/src/image-source-layer.ts +380 -0
  101. package/src/index.ts +58 -1
  102. package/src/line-blur-extension.ts +14 -12
  103. package/src/line-dash-extension.ts +303 -0
  104. package/src/line-gradient-extension.ts +191 -0
  105. package/src/line-metrics.ts +90 -0
  106. package/src/line-pattern-extension.ts +173 -0
  107. package/src/line-shape-extension.ts +272 -0
  108. package/src/map-style-loader.ts +5 -4
  109. package/src/map-style.ts +2 -1
  110. package/src/mvt-label-layer.ts +568 -144
  111. package/src/pmtiles-source.ts +276 -0
  112. package/src/projected-background-layer.ts +202 -0
  113. package/src/projected-bitmap-layer.ts +262 -0
  114. package/src/projected-tile-data.ts +132 -0
  115. package/src/projected-tile-selection.ts +605 -0
  116. package/src/projected-tileset.ts +183 -0
  117. package/src/projected-viewport.ts +254 -0
  118. package/src/raster-color-extension.ts +43 -18
  119. package/src/raster-fade.ts +319 -0
  120. package/src/raster-tile-fingerprint.ts +31 -0
  121. package/src/raster-tile-loader.ts +211 -0
  122. package/src/shader-injection-plugin.ts +25 -0
  123. package/src/source-features.ts +170 -0
  124. package/src/source-tiles.ts +102 -0
  125. package/src/sprite.ts +122 -15
  126. package/src/stretch-icon-layer.ts +87 -0
  127. package/src/style-accessor.ts +105 -17
  128. package/src/style-expression.ts +80 -3
  129. package/src/style-resolver.ts +200 -22
  130. package/src/terrain-query.ts +86 -0
  131. package/src/text-layout.ts +2 -3
  132. package/src/zoom-load-gate.ts +57 -0
  133. package/src/zoom-paint-extension.ts +245 -47
  134. package/dist/types/arabic-shaping.d.ts +0 -7
  135. package/dist/types/bidi.d.ts +0 -8
  136. package/dist/types/polylabel.d.ts +0 -17
  137. package/src/arabic-shaping.ts +0 -366
  138. package/src/bidi.ts +0 -199
  139. package/src/polylabel.ts +0 -312
@@ -7,8 +7,10 @@
7
7
  // Copyright (c) vis.gl contributors
8
8
 
9
9
  import {LayerExtension, project} from '@deck.gl/core';
10
- import type {CompositeLayer, Layer} from '@deck.gl/core';
10
+ import type {Layer} from '@deck.gl/core';
11
11
  import {FillStyleExtension} from '@deck.gl/extensions';
12
+ import type {ShaderModule, ShaderPlugin} from '@luma.gl/shaders';
13
+ import {createShaderInjectionPlugin} from './shader-injection-plugin';
12
14
 
13
15
  /** Whether a layer's device runs the GLSL injections of these extensions. */
14
16
  function isGLSLDevice(layer: Layer): boolean {
@@ -18,15 +20,31 @@ function isGLSLDevice(layer: Layer): boolean {
18
20
  /**
19
21
  * `fill-translate` in common space. The offset is in pixels on the ground plane, as MapLibre GL
20
22
  * JS applies it in tile units: x east and y south on a map, along the local east and south on a
21
- * globe. The vertex moves before later injections run, so a pattern moves with the fill.
23
+ * globe. Only the clip-space position moves: a pattern is placed by the vertex's own position, so
24
+ * it moves with the fill, as in MapLibre GL JS.
22
25
  */
23
- const fillTranslateModule = {
26
+ const fillTranslateModule = createShaderInjectionPlugin({
24
27
  name: 'fillTranslate',
25
28
  dependencies: [project],
26
29
  vs: /* glsl */ `\
27
30
  layout(std140) uniform fillTranslateUniforms {
28
31
  vec2 offset;
29
32
  } fillTranslate;
33
+
34
+ vec4 fillTranslate_getPosition(vec4 position) {
35
+ vec2 pixels = vec2(fillTranslate.offset.x, -fillTranslate.offset.y);
36
+ if (project.projectionMode == PROJECTION_MODE_GLOBE) {
37
+ // The globe is centred at the origin with its axis along z.
38
+ vec3 up = normalize(position.xyz);
39
+ vec3 east = vec3(-up.y, up.x, 0.0);
40
+ east = length(east) > 0.0 ? normalize(east) : vec3(1.0, 0.0, 0.0);
41
+ vec3 north = cross(up, east);
42
+ position.xyz += (east * pixels.x + north * pixels.y) / project.scale;
43
+ } else {
44
+ position.xy += pixels / project.scale;
45
+ }
46
+ return position;
47
+ }
30
48
  `,
31
49
  uniformTypes: {offset: 'vec2<f32>'},
32
50
  inject: {
@@ -34,32 +52,64 @@ layout(std140) uniform fillTranslateUniforms {
34
52
  order: -1,
35
53
  injection: /* glsl */ `
36
54
  if (fillTranslate.offset != vec2(0.0)) {
37
- vec2 fillTranslate_pixels = vec2(fillTranslate.offset.x, -fillTranslate.offset.y);
38
- if (project.projectionMode == PROJECTION_MODE_GLOBE) {
39
- // The globe is centred at the origin with its axis along z.
40
- vec3 fillTranslate_up = normalize(geometry.position.xyz);
41
- vec3 fillTranslate_east = vec3(-fillTranslate_up.y, fillTranslate_up.x, 0.0);
42
- fillTranslate_east = length(fillTranslate_east) > 0.0
43
- ? normalize(fillTranslate_east)
44
- : vec3(1.0, 0.0, 0.0);
45
- vec3 fillTranslate_north = cross(fillTranslate_up, fillTranslate_east);
46
- geometry.position.xyz +=
47
- (fillTranslate_east * fillTranslate_pixels.x + fillTranslate_north * fillTranslate_pixels.y) /
48
- project.scale;
49
- } else {
50
- geometry.position.xy += fillTranslate_pixels / project.scale;
51
- }
52
- position = project_common_position_to_clipspace(geometry.position);
55
+ position = project_common_position_to_clipspace(fillTranslate_getPosition(geometry.position));
53
56
  }
54
57
  `
55
58
  }
56
59
  }
57
- } as const;
60
+ });
61
+
62
+ /** The WGSL uniform and common-space offset shared by fill and circle translation. */
63
+ export const fillTranslateModuleWGSL: ShaderModule = {
64
+ name: 'fillTranslate',
65
+ dependencies: [project],
66
+ source: /* wgsl */ `\
67
+ struct FillTranslateUniforms {
68
+ offset: vec2<f32>,
69
+ };
70
+
71
+ @group(0) @binding(auto) var<uniform> fillTranslate: FillTranslateUniforms;
72
+
73
+ // The common position moved by the offset, as the GLSL injection moves it.
74
+ fn fillTranslate_getPosition(position: vec4<f32>) -> vec4<f32> {
75
+ let pixels = vec2<f32>(fillTranslate.offset.x, -fillTranslate.offset.y);
76
+ if (project.projectionMode == PROJECTION_MODE_GLOBE) {
77
+ // The globe is centred at the origin with its axis along z.
78
+ let up = normalize(position.xyz);
79
+ var east = vec3<f32>(-up.y, up.x, 0.0);
80
+ east = select(vec3<f32>(1.0, 0.0, 0.0), normalize(east), length(east) > 0.0);
81
+ let north = cross(up, east);
82
+ return vec4<f32>(position.xyz + (east * pixels.x + north * pixels.y) / project.scale, position.w);
83
+ }
84
+ return vec4<f32>(position.xy + pixels / project.scale, position.zw);
85
+ }
86
+ `,
87
+ uniformTypes: {offset: 'vec2<f32>'}
88
+ };
89
+
90
+ /** The WGSL of `fillTranslateModule`. */
91
+ const fillTranslatePluginWGSL: ShaderPlugin = {
92
+ name: 'fillTranslate',
93
+ module: fillTranslateModuleWGSL,
94
+ injections: [
95
+ {
96
+ stage: 'vertex',
97
+ target: 'DECKGL_FILTER_GL_POSITION',
98
+ order: -1,
99
+ wgsl: /* wgsl */ `
100
+ if (any(fillTranslate.offset != vec2<f32>(0.0))) {
101
+ *position = project_common_position_to_clipspace(fillTranslate_getPosition(geometry.position));
102
+ }
103
+ `
104
+ }
105
+ ]
106
+ };
58
107
 
59
108
  /** The anchor of `fill-translate`. */
60
109
  export type FillTranslateAnchor = 'map' | 'viewport';
61
110
 
62
- type FillTranslateExtensionProps = {
111
+ /** The props of `FillTranslateExtension`. */
112
+ export type FillTranslateExtensionProps = {
63
113
  /** `fill-translate`: the offset in pixels, x right and y down. */
64
114
  fillTranslate?: [number, number];
65
115
  /** `fill-translate-anchor`: `'map'` turns the offset with the map, `'viewport'` keeps it on screen. */
@@ -88,7 +138,7 @@ export function getFillTranslateOffset(
88
138
 
89
139
  /**
90
140
  * Offsets a fill and its outline by `fill-translate` pixels, anchored to the map or to the
91
- * viewport by `fill-translate-anchor`. WebGL only; on WebGPU fills draw untranslated.
141
+ * viewport by `fill-translate-anchor`, on WebGL and WebGPU.
92
142
  *
93
143
  * Added to a `GeoJsonLayer`, it reaches the polygon fill and outline sublayers.
94
144
  */
@@ -100,16 +150,10 @@ export class FillTranslateExtension extends LayerExtension {
100
150
  };
101
151
 
102
152
  getShaders(this: Layer) {
103
- if (!isGLSLDevice(this)) {
104
- return {};
105
- }
106
- return {modules: [fillTranslateModule]};
153
+ return {plugins: [isGLSLDevice(this) ? fillTranslateModule : fillTranslatePluginWGSL]};
107
154
  }
108
155
 
109
156
  draw(this: Layer<FillTranslateExtensionProps>) {
110
- if (!isGLSLDevice(this)) {
111
- return;
112
- }
113
157
  const {fillTranslate = [0, 0], fillTranslateAnchor = 'map'} = this.props;
114
158
  const bearing = (this.context.viewport as {bearing?: number}).bearing || 0;
115
159
  this.setShaderModuleProps({
@@ -126,7 +170,7 @@ export class FillTranslateExtension extends LayerExtension {
126
170
  * size and shape across the globe, and stays continuous across tiles, as on a map. Runs after
127
171
  * `FillStyleExtension`'s injection (`order: 1`), with the pattern size in common units.
128
172
  */
129
- const globePatternModule = {
173
+ const globePatternModule = createShaderInjectionPlugin({
130
174
  name: 'globeFillPattern',
131
175
  dependencies: [project],
132
176
  inject: {
@@ -142,12 +186,45 @@ const globePatternModule = {
142
186
  `
143
187
  }
144
188
  }
145
- } as const;
189
+ });
146
190
 
147
191
  /**
148
- * `FillStyleExtension` with image patterns, run only where its GLSL shader runs. On WebGPU it adds
149
- * no shader code, and the fills it is added to draw nothing, as before patterns were supported:
150
- * their fill color is only the pattern's opacity.
192
+ * deck.gl 10.0.0-alpha.1's WGSL pattern places the pattern with
193
+ * `project_common_position_to_flat_continuous(geometry.position, ...)`, which takes a `vec3<f32>`,
194
+ * so its vertex shader does not compile. This copy of its plugin passes `geometry.position.xyz`.
195
+ * Where the call is already correct, the plugin is returned unchanged.
196
+ */
197
+ const BROKEN_FLAT_POSITION = 'project_common_position_to_flat_continuous(geometry.position,';
198
+ const FIXED_FLAT_POSITION = 'project_common_position_to_flat_continuous(geometry.position.xyz,';
199
+ const fixedPatternPlugins = new WeakMap<ShaderPlugin, ShaderPlugin>();
200
+
201
+ function fixPatternPluginWGSL(plugin: ShaderPlugin): ShaderPlugin {
202
+ const {injections} = plugin;
203
+ if (!injections || Array.isArray(injections)) {
204
+ return plugin;
205
+ }
206
+ const key = 'wgsl:vs:DECKGL_FILTER_GL_POSITION';
207
+ if (!injections[key]?.includes(BROKEN_FLAT_POSITION)) {
208
+ return plugin;
209
+ }
210
+ let fixed = fixedPatternPlugins.get(plugin);
211
+ if (!fixed) {
212
+ fixed = {
213
+ ...plugin,
214
+ injections: {
215
+ ...injections,
216
+ [key]: injections[key].replaceAll(BROKEN_FLAT_POSITION, FIXED_FLAT_POSITION)
217
+ }
218
+ };
219
+ fixedPatternPlugins.set(plugin, fixed);
220
+ }
221
+ return fixed;
222
+ }
223
+
224
+ /**
225
+ * `FillStyleExtension` with image patterns, on WebGL and WebGPU. On a globe, the pattern is placed
226
+ * by the vertex's Web Mercator position: by `globePatternModule` on WebGL, and by deck.gl's own
227
+ * WGSL on WebGPU.
151
228
  */
152
229
  export class FillPatternExtension extends FillStyleExtension {
153
230
  static extensionName = 'FillPatternExtension';
@@ -161,17 +238,10 @@ export class FillPatternExtension extends FillStyleExtension {
161
238
  return (
162
239
  shaders && {
163
240
  ...shaders,
164
- modules: [...shaders.modules, globePatternModule]
241
+ plugins: isGLSLDevice(this)
242
+ ? [...(shaders.plugins ?? []), globePatternModule]
243
+ : (shaders.plugins ?? []).map(fixPatternPluginWGSL)
165
244
  }
166
245
  );
167
246
  }
168
-
169
- isEnabled(layer: Layer): boolean {
170
- return isGLSLDevice(layer) && super.isEnabled(layer);
171
- }
172
-
173
- getSubLayerProps(this: CompositeLayer, extension: this): any {
174
- const props = LayerExtension.prototype.getSubLayerProps.call(this, extension);
175
- return isGLSLDevice(this) ? props : {...props, getFillColor: [0, 0, 0, 0]};
176
- }
177
247
  }
@@ -0,0 +1,58 @@
1
+ // tangram-layers
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import type {GeoJSONVT} from '@maplibre/geojson-vt';
6
+ import type {GeoJsonWorkerRequest} from './geojson-worker';
7
+ import {createTileIndex, cutTile} from './geojson-tiler';
8
+
9
+ /** Worker-owned source indexes and not-yet-indexed feature batches. */
10
+ export type GeoJsonResourceState = {
11
+ /** Feature batches received before indexing. */
12
+ pendingFeatures: Map<number, unknown[]>;
13
+ /** Successfully constructed indexes or their construction errors. */
14
+ indexes: Map<number, GeoJSONVT | Error>;
15
+ };
16
+
17
+ /** Create the state held exclusively by one GeoJSON resource worker. */
18
+ export function createGeoJsonResourceState(): GeoJsonResourceState {
19
+ return {pendingFeatures: new Map(), indexes: new Map()};
20
+ }
21
+
22
+ /**
23
+ * Apply an ordered source operation. A tile request returns its tile, and an index request the
24
+ * number of features dropped or cut at the edges of the Web Mercator world (see
25
+ * `clipFeaturesToMercatorRange`).
26
+ */
27
+ export function runGeoJsonResource(state: GeoJsonResourceState, message: GeoJsonWorkerRequest): ReturnType<typeof cutTile> | number | null {
28
+ switch (message.type) {
29
+ case 'features': {
30
+ const features = state.pendingFeatures.get(message.source);
31
+ if (features) for (const feature of message.features) features.push(feature);
32
+ else state.pendingFeatures.set(message.source, message.features);
33
+ return null;
34
+ }
35
+ case 'index': {
36
+ const data = message.data ?? {type: 'FeatureCollection', features: state.pendingFeatures.get(message.source) || []};
37
+ state.pendingFeatures.delete(message.source);
38
+ try {
39
+ const {index, outside} = createTileIndex(data, message.options, message.clipToMercatorRange);
40
+ state.indexes.set(message.source, index);
41
+ return outside;
42
+ } catch (error) {
43
+ state.indexes.set(message.source, error instanceof Error ? error : new Error(String(error)));
44
+ return 0;
45
+ }
46
+ }
47
+ case 'tile': {
48
+ const index = state.indexes.get(message.source);
49
+ if (!index) throw new Error('GeoJSON source has no index');
50
+ if (index instanceof Error) throw index;
51
+ return cutTile(index, message.z, message.x, message.y);
52
+ }
53
+ case 'remove':
54
+ state.pendingFeatures.delete(message.source);
55
+ state.indexes.delete(message.source);
56
+ return null;
57
+ }
58
+ }
@@ -2,9 +2,13 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  // Copyright (c) vis.gl contributors
4
4
 
5
+ import {log} from '@deck.gl/core';
5
6
  import type {GeoJSONVT, GeoJSONVTOptions} from '@maplibre/geojson-vt';
7
+ import {TaskRunner, type InitializedTask} from '@math.gl/tasks';
6
8
  import {createTileIndex, cutTile, decodeTile, GEOJSON_TILE_EXTENT} from './geojson-tiler';
7
- import type {GeoJsonWorkerRequest, GeoJsonWorkerResponse} from './geojson-worker';
9
+ import type {GeoJsonWorkerRequest} from './geojson-worker';
10
+ import {GeoJsonTask} from './geojson-task';
11
+ import type {GeoJsonTaskResult} from './geojson-task';
8
12
  import type {BasemapSource} from './style-resolver';
9
13
 
10
14
  /** The size of a GeoJSON source's tiles in pixels, fixed in MapLibre GL JS. */
@@ -43,7 +47,8 @@ function getNumber(value: unknown, fallback: number): number {
43
47
  /**
44
48
  * geojson-vt options for a GeoJSON source, as MapLibre GL JS 6 sets them: `buffer` and
45
49
  * `tolerance` are given in pixels of a 512 pixel tile, and the source's `maxzoom` is the deepest
46
- * zoom tiled. Clustering is supported without `clusterProperties`.
50
+ * zoom tiled. Clustering is supported without `clusterProperties`. `lineMetrics` adds each tiled
51
+ * line's part of its whole line to its properties, as in MapLibre.
47
52
  */
48
53
  export function getGeoJsonVtOptions(source: BasemapSource): GeoJSONVTOptions {
49
54
  const maxZoom = getGeoJsonMaxZoom(source);
@@ -56,7 +61,9 @@ export function getGeoJsonVtOptions(source: BasemapSource): GeoJSONVTOptions {
56
61
  tolerance: getNumber(source.tolerance, 0.375) * TILE_UNITS_PER_PIXEL,
57
62
  generateId,
58
63
  // geojson-vt rejects `promoteId` together with `generateId`, which then wins, as in MapLibre.
59
- promoteId: generateId ? undefined : promoteId
64
+ promoteId: generateId ? undefined : promoteId,
65
+ // Each tiled line records its part of the whole line, which `line-gradient` draws by.
66
+ lineMetrics: Boolean(source.lineMetrics)
60
67
  };
61
68
  if (source.cluster) {
62
69
  const clusterMaxZoom = getNumber(source.clusterMaxZoom, maxZoom - 1);
@@ -82,6 +89,32 @@ export function getGeoJsonVtOptions(source: BasemapSource): GeoJSONVTOptions {
82
89
  */
83
90
  const POSITIONS_PER_BATCH = 100_000;
84
91
 
92
+ /** How a GeoJSON source's tiles are cut, for the view they are drawn in. */
93
+ export type GeoJsonTileOptions = {
94
+ /**
95
+ * Whether what lies past the edges of the Web Mercator world, at +-85.0511 degrees, is dropped
96
+ * and cut, and not clamped onto them as geojson-vt and MapLibre GL JS do (see
97
+ * `clipFeaturesToMercatorRange`): for views that show latitudes past them, projected views and
98
+ * globes. A Web Mercator view does not show them.
99
+ */
100
+ clipToMercatorRange?: boolean;
101
+ };
102
+
103
+ /** The sources that have warned of features past the edges of the Web Mercator world. */
104
+ const warnedSources = new WeakSet<BasemapSource>();
105
+
106
+ /** Warns, once per source, that features past the edges of the Web Mercator world are not drawn. */
107
+ function warnOutside(source: BasemapSource, outside: number | undefined): void {
108
+ if (!outside || warnedSources.has(source)) {
109
+ return;
110
+ }
111
+ warnedSources.add(source);
112
+ log.warn(
113
+ '[BasemapLayer] GeoJSON features past +-85.051129 degrees of latitude, the edge of Web ' +
114
+ `Mercator tiles, are cut at that latitude (features cut in this source: ${outside})`
115
+ )();
116
+ }
117
+
85
118
  /** Whether GeoJSON sources are tiled in a worker where workers are available. For tests. */
86
119
  let workerEnabled = true;
87
120
 
@@ -93,14 +126,6 @@ export function setGeoJsonWorkerEnabled(enabled: boolean): void {
93
126
  workerEnabled = enabled;
94
127
  }
95
128
 
96
- /** A tile request sent to the worker, and how to cut the tile here if the worker fails. */
97
- type PendingTile = {
98
- source: BasemapSource;
99
- index: {x: number; y: number; z: number};
100
- resolve: (features: Record<string, unknown>[]) => void;
101
- reject: (error: unknown) => void;
102
- };
103
-
104
129
  /**
105
130
  * The worker that indexes GeoJSON sources and cuts their tiles, shared by all of them. If it
106
131
  * cannot start (a bundle that does not emit it, a content security policy without `worker-src`)
@@ -108,67 +133,67 @@ type PendingTile = {
108
133
  */
109
134
  class GeoJsonWorker {
110
135
  failed = false;
111
- private worker: Worker;
136
+ private readonly runner = new TaskRunner();
137
+ private readonly resource: Promise<InitializedTask<typeof GeoJsonTask>>;
138
+ private queue: Promise<void> = Promise.resolve();
112
139
  private nextId = 0;
113
- private sources = new WeakMap<BasemapSource, {id: number; sent: Promise<void>}>();
114
- private requests = new Map<number, PendingTile>();
140
+ /** Each source's index in the worker, without clipping (0) and with it (1). */
141
+ private sources = [0, 1].map(
142
+ () => new WeakMap<BasemapSource, {id: number; sent: Promise<void>}>()
143
+ );
115
144
  private registry = new FinalizationRegistry<number>(id =>
116
- this.post({type: 'remove', source: id})
145
+ void this.post({type: 'remove', source: id})
117
146
  );
118
147
 
119
- constructor(worker: Worker) {
120
- this.worker = worker;
121
- worker.onmessage = ({data}: MessageEvent<GeoJsonWorkerResponse>) => {
122
- const request = this.requests.get(data.request);
123
- this.requests.delete(data.request);
124
- if (!request) {
125
- return;
126
- }
127
- if ('error' in data) {
128
- request.reject(new Error(data.error));
129
- } else {
130
- request.resolve(decodeTile(data.tile));
131
- }
132
- };
133
- worker.onerror = event => {
134
- event.preventDefault?.();
135
- this.fail();
136
- };
137
- worker.onmessageerror = () => this.fail();
148
+ constructor() {
149
+ this.resource = this.runner.initializeTask(GeoJsonTask, {}, {execution: 'worker'});
138
150
  }
139
151
 
140
152
  /** Cuts a tile of `source` in the worker, sending the source's data first if it is new. */
141
153
  async getTileFeatures(
142
154
  source: BasemapSource,
143
- index: {x: number; y: number; z: number}
155
+ index: {x: number; y: number; z: number},
156
+ clip: boolean
144
157
  ): Promise<Record<string, unknown>[]> {
145
- let entry = this.sources.get(source);
158
+ const sources = this.sources[Number(clip)];
159
+ let entry = sources.get(source);
146
160
  if (!entry) {
147
161
  const id = this.nextId++;
148
- entry = {id, sent: this.sendSource(id, source)};
149
- this.sources.set(source, entry);
162
+ entry = {id, sent: this.sendSource(id, source, clip)};
163
+ sources.set(source, entry);
150
164
  this.registry.register(source, id);
151
165
  }
152
166
  await entry.sent;
153
167
  if (this.failed) {
154
- return getMainThreadTileFeatures(source, index);
168
+ return getMainThreadTileFeatures(source, index, clip);
155
169
  }
156
170
  const request = this.nextId++;
157
- return new Promise((resolve, reject) => {
158
- this.requests.set(request, {source, index, resolve, reject});
159
- this.post({type: 'tile', source: entry.id, request, ...index});
160
- });
171
+ const result = await this.post({type: 'tile', source: entry.id, request, ...index});
172
+ if (this.failed || !result) return getMainThreadTileFeatures(source, index, clip);
173
+ if ('error' in result) throw new Error(result.error);
174
+ if (!result.tile) throw new Error('GeoJSON worker returned no tile');
175
+ return decodeTile(result.tile);
161
176
  }
162
177
 
163
178
  /**
164
179
  * Sends a source's data and options. A FeatureCollection's features go in batches, yielding to
165
180
  * the main thread between them; the worker builds the index when the last one arrives.
166
181
  */
167
- private async sendSource(id: number, source: BasemapSource): Promise<void> {
182
+ private async sendSource(id: number, source: BasemapSource, clip: boolean): Promise<void> {
168
183
  const options = getGeoJsonVtOptions(source);
169
184
  const data = source.data as {type?: string; features?: unknown};
185
+ const index = async (message: {data?: unknown}) => {
186
+ const result = await this.post({
187
+ type: 'index',
188
+ source: id,
189
+ options,
190
+ clipToMercatorRange: clip,
191
+ ...message
192
+ });
193
+ warnOutside(source, result && 'outside' in result ? result.outside : 0);
194
+ };
170
195
  if (data.type !== 'FeatureCollection' || !Array.isArray(data.features)) {
171
- this.post({type: 'index', source: id, data, options});
196
+ await index({data});
172
197
  return;
173
198
  }
174
199
  let batch: unknown[] = [];
@@ -177,7 +202,7 @@ class GeoJsonWorker {
177
202
  batch.push(feature);
178
203
  positions += countPositions((feature as {geometry?: unknown})?.geometry);
179
204
  if (positions >= POSITIONS_PER_BATCH) {
180
- this.post({type: 'features', source: id, features: batch});
205
+ await this.post({type: 'features', source: id, features: batch});
181
206
  batch = [];
182
207
  positions = 0;
183
208
  await yieldToMainThread();
@@ -186,38 +211,26 @@ class GeoJsonWorker {
186
211
  }
187
212
  }
188
213
  }
189
- this.post({type: 'features', source: id, features: batch});
190
- this.post({type: 'index', source: id, options});
191
- }
192
-
193
- private post(message: GeoJsonWorkerRequest): void {
194
- if (this.failed) {
195
- return;
196
- }
197
- try {
198
- this.worker.postMessage(message);
199
- } catch {
200
- // Data that cannot be cloned (a function in a property, say) is tiled on the main thread.
201
- this.fail();
202
- }
214
+ await this.post({type: 'features', source: id, features: batch});
215
+ await index({});
203
216
  }
204
217
 
205
- /** Stops using the worker, and cuts the tiles it still owes on the main thread. */
206
- private fail(): void {
207
- if (this.failed) {
208
- return;
209
- }
210
- this.failed = true;
211
- this.worker.terminate();
212
- const requests = [...this.requests.values()];
213
- this.requests.clear();
214
- for (const {source, index, resolve, reject} of requests) {
218
+ /** Serialize operations to avoid overflowing the resource's bounded job queue. */
219
+ private post(message: GeoJsonWorkerRequest): Promise<GeoJsonTaskResult | undefined> {
220
+ const operation = this.queue.then(async () => {
221
+ if (this.failed) return undefined;
215
222
  try {
216
- resolve(getMainThreadTileFeatures(source, index));
217
- } catch (error) {
218
- reject(error);
223
+ const resource = await this.resource;
224
+ // The tile can reference properties owned by the retained index.
225
+ return await resource.runTask(message, {inputOwnership: 'copy', outputOwnership: 'copy'});
226
+ } catch {
227
+ this.failed = true;
228
+ void this.runner.terminate().catch(() => {});
229
+ return undefined;
219
230
  }
220
- }
231
+ });
232
+ this.queue = operation.then(() => {});
233
+ return operation;
221
234
  }
222
235
  }
223
236
 
@@ -276,9 +289,7 @@ function getGeoJsonWorker(): GeoJsonWorker | null {
276
289
  // Bundlers (Vite, webpack 5, esbuild with a plugin, Parcel) emit the worker and its imports
277
290
  // from this expression, which must stay literal. The CommonJS build has no `import.meta.url`
278
291
  // and throws here.
279
- geoJsonWorker = new GeoJsonWorker(
280
- new Worker(new URL('./geojson-worker.js', import.meta.url), {type: 'module'})
281
- );
292
+ geoJsonWorker = new GeoJsonWorker();
282
293
  } catch {
283
294
  geoJsonWorker = null;
284
295
  }
@@ -286,18 +297,25 @@ function getGeoJsonWorker(): GeoJsonWorker | null {
286
297
  return geoJsonWorker?.failed ? null : geoJsonWorker;
287
298
  }
288
299
 
289
- /** Each source's tile index on the main thread, built when its first tile is requested there. */
290
- const tileIndexes = new WeakMap<BasemapSource, GeoJSONVT>();
300
+ /**
301
+ * Each source's tile index on the main thread, without clipping (0) and with it (1), built when
302
+ * its first tile is requested there.
303
+ */
304
+ const tileIndexes = [0, 1].map(() => new WeakMap<BasemapSource, GeoJSONVT>());
291
305
 
292
306
  /** Cuts a tile of a GeoJSON source on the main thread, building its index first if needed. */
293
307
  function getMainThreadTileFeatures(
294
308
  source: BasemapSource,
295
- index: {x: number; y: number; z: number}
309
+ index: {x: number; y: number; z: number},
310
+ clip: boolean
296
311
  ): Record<string, unknown>[] {
297
- let tileIndex = tileIndexes.get(source);
312
+ const indexes = tileIndexes[Number(clip)];
313
+ let tileIndex = indexes.get(source);
298
314
  if (!tileIndex) {
299
- tileIndex = createTileIndex(source.data, getGeoJsonVtOptions(source));
300
- tileIndexes.set(source, tileIndex);
315
+ const created = createTileIndex(source.data, getGeoJsonVtOptions(source), clip);
316
+ tileIndex = created.index;
317
+ indexes.set(source, tileIndex);
318
+ warnOutside(source, created.outside);
301
319
  }
302
320
  return decodeTile(cutTile(tileIndex, index.z, index.x, index.y));
303
321
  }
@@ -311,8 +329,11 @@ function getMainThreadTileFeatures(
311
329
  */
312
330
  export async function getGeoJsonTileFeatures(
313
331
  source: BasemapSource,
314
- index: {x: number; y: number; z: number}
332
+ index: {x: number; y: number; z: number},
333
+ {clipToMercatorRange = false}: GeoJsonTileOptions = {}
315
334
  ): Promise<Record<string, unknown>[]> {
316
335
  const worker = getGeoJsonWorker();
317
- return worker ? worker.getTileFeatures(source, index) : getMainThreadTileFeatures(source, index);
336
+ return worker
337
+ ? worker.getTileFeatures(source, index, clipToMercatorRange)
338
+ : getMainThreadTileFeatures(source, index, clipToMercatorRange);
318
339
  }
@@ -0,0 +1,11 @@
1
+ // tangram-layers
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import {initializeTaskWorker} from '@math.gl/tasks';
6
+ import {GeoJsonTask} from './geojson-task';
7
+
8
+ /** Install the stateful GeoJSON resource task handler on a worker global. */
9
+ export function installGeoJsonTaskHandler(): Promise<void> {
10
+ return initializeTaskWorker(GeoJsonTask);
11
+ }
@@ -0,0 +1,8 @@
1
+ // tangram-layers
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import {installGeoJsonTaskHandler} from './geojson-task-handler';
6
+
7
+ // Keep all GeoJSON source indexes inside one worker resource.
8
+ void installGeoJsonTaskHandler();
@@ -0,0 +1,34 @@
1
+ // tangram-layers
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import type {Task} from '@math.gl/tasks';
6
+ import {createGeoJsonResourceState, runGeoJsonResource, type GeoJsonResourceState} from './geojson-resource';
7
+ import type {GeoJsonWorkerRequest} from './geojson-worker';
8
+ import type {cutTile} from './geojson-tiler';
9
+
10
+ /**
11
+ * A source error is distinct from a failure of the worker transport. An index request reports how
12
+ * many features it dropped or cut at the edges of the Web Mercator world in `outside`.
13
+ */
14
+ export type GeoJsonTaskResult =
15
+ | {tile: ReturnType<typeof cutTile> | null; outside?: number}
16
+ | {error: string};
17
+
18
+ /** Stateful GeoJSON tiling resource; one worker owns all source indexes. */
19
+ export const GeoJsonTask = {
20
+ id: 'tangram-geojson',
21
+ worker: {
22
+ create: () => new Worker(new URL('./geojson-task-worker.js', import.meta.url), {type: 'module'}),
23
+ capabilities: {atomic: true, streaming: false}
24
+ },
25
+ initialize: (_input: object) => createGeoJsonResourceState(),
26
+ process: (input, _options: object, {state}): GeoJsonTaskResult => {
27
+ try {
28
+ const output = runGeoJsonResource(state, input);
29
+ return typeof output === 'number' ? {tile: null, outside: output} : {tile: output};
30
+ } catch (error) {
31
+ return {error: error instanceof Error ? error.message : String(error)};
32
+ }
33
+ }
34
+ } satisfies Task<{input: GeoJsonWorkerRequest; output: GeoJsonTaskResult; state: GeoJsonResourceState}>;