@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
@@ -0,0 +1,174 @@
1
+ // tangram-layers
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ /** An image whose pixels can be read: a decoded tile, or a canvas. */
6
+ export type DemPixelSource = ImageBitmap | HTMLCanvasElement | OffscreenCanvas;
7
+
8
+ /** Reads the exact RGBA bytes of an image, row by row from the top-left pixel. */
9
+ export type DemPixelReader = (image: DemPixelSource) => Promise<Uint8ClampedArray>;
10
+
11
+ /** How the pixels of a DEM tile are read exactly. */
12
+ export type DemPixelReadMethod = 'canvas' | 'video-frame';
13
+
14
+ /**
15
+ * Thrown when this browser gives no exact pixels of an image. Some browsers add noise to canvas
16
+ * reads to resist fingerprinting (Firefox `privacy.resistFingerprinting`, Brave, Safari), and
17
+ * some of them also turn `VideoFrame` off. One changed byte moves a Terrarium elevation by up to
18
+ * 256 m, so the tile fails instead of drawing wrong heights.
19
+ */
20
+ export class DemPixelReadError extends Error {
21
+ constructor(reason: string, options?: {cause?: unknown}) {
22
+ super(
23
+ 'This browser changes the pixels that a canvas reads back, so DEM tiles cannot be ' +
24
+ `decoded exactly: ${reason}`,
25
+ options
26
+ );
27
+ this.name = 'DemPixelReadError';
28
+ }
29
+ }
30
+
31
+ /** The side of the square test image. */
32
+ const TEST_SIZE = 256;
33
+
34
+ /**
35
+ * An opaque test image whose color bytes count up 0, 1, 2… and repeat through every byte value.
36
+ * Opaque pixels keep their bytes through a premultiplied canvas.
37
+ */
38
+ function getTestPixels(): Uint8ClampedArray<ArrayBuffer> {
39
+ const pixels = new Uint8ClampedArray(TEST_SIZE * TEST_SIZE * 4);
40
+ for (let pixel = 0; pixel < TEST_SIZE * TEST_SIZE; pixel++) {
41
+ for (let channel = 0; channel < 3; channel++) {
42
+ pixels[pixel * 4 + channel] = (pixel * 3 + channel) % 256;
43
+ }
44
+ pixels[pixel * 4 + 3] = 255;
45
+ }
46
+ return pixels;
47
+ }
48
+
49
+ /** Creates a DEM bitmap with its color and alpha bytes preserved. */
50
+ export function createDemImageBitmap(image: Blob | ImageData): Promise<ImageBitmap> {
51
+ return createImageBitmap(image, {premultiplyAlpha: 'none', colorSpaceConversion: 'none'});
52
+ }
53
+
54
+ function createCanvas(width: number, height: number): HTMLCanvasElement | OffscreenCanvas {
55
+ return typeof OffscreenCanvas === 'undefined'
56
+ ? Object.assign(document.createElement('canvas'), {width, height})
57
+ : new OffscreenCanvas(width, height);
58
+ }
59
+
60
+ function get2DContext(
61
+ canvas: HTMLCanvasElement | OffscreenCanvas
62
+ ): CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D {
63
+ const context = canvas.getContext('2d', {willReadFrequently: true}) as
64
+ | CanvasRenderingContext2D
65
+ | OffscreenCanvasRenderingContext2D
66
+ | null;
67
+ if (!context) {
68
+ throw new Error('DEM tiles need a 2D canvas context to read their pixels');
69
+ }
70
+ return context;
71
+ }
72
+
73
+ /** Reads the pixels of an image through a 2D canvas. */
74
+ export function readPixelsWithCanvas(image: DemPixelSource): Promise<Uint8ClampedArray> {
75
+ const {width, height} = image;
76
+ const context = get2DContext(createCanvas(width, height));
77
+ context.drawImage(image, 0, 0);
78
+ return Promise.resolve(context.getImageData(0, 0, width, height).data);
79
+ }
80
+
81
+ /**
82
+ * Reads the pixels of an image through WebCodecs, which canvas noise does not reach. The frame
83
+ * is copied in its own pixel format, so no color conversion runs; blue-first formats are
84
+ * reordered to RGBA, and formats without alpha (`RGBX`, `BGRX`) get opaque pixels.
85
+ */
86
+ export async function readPixelsWithVideoFrame(image: DemPixelSource): Promise<Uint8ClampedArray> {
87
+ const {width, height} = image;
88
+ const frame = new VideoFrame(image, {timestamp: 0, alpha: 'keep'});
89
+ try {
90
+ const {format} = frame;
91
+ if (format !== 'RGBA' && format !== 'RGBX' && format !== 'BGRA' && format !== 'BGRX') {
92
+ throw new Error(`VideoFrame has the pixel format ${format}, not an RGB one`);
93
+ }
94
+ const pixels = new Uint8ClampedArray(width * height * 4);
95
+ await frame.copyTo(pixels, {
96
+ rect: {x: 0, y: 0, width, height},
97
+ layout: [{offset: 0, stride: width * 4}]
98
+ });
99
+ const blueFirst = format.startsWith('B');
100
+ const opaque = format.endsWith('X');
101
+ if (blueFirst || opaque) {
102
+ for (let i = 0; i < pixels.length; i += 4) {
103
+ if (blueFirst) {
104
+ const blue = pixels[i];
105
+ pixels[i] = pixels[i + 2];
106
+ pixels[i + 2] = blue;
107
+ }
108
+ if (opaque) {
109
+ pixels[i + 3] = 255;
110
+ }
111
+ }
112
+ }
113
+ return pixels;
114
+ } finally {
115
+ frame.close();
116
+ }
117
+ }
118
+
119
+ /** Whether `read` gives the test image's bytes back unchanged. */
120
+ async function readsExactly(
121
+ read: DemPixelReader,
122
+ image: ImageBitmap,
123
+ expected: Uint8ClampedArray
124
+ ): Promise<boolean> {
125
+ const actual = await read(image);
126
+ return actual.length === expected.length && actual.every((byte, i) => byte === expected[i]);
127
+ }
128
+
129
+ /**
130
+ * Chooses how to read DEM pixels exactly: through a canvas, which is what MapLibre GL JS and most
131
+ * browsers use; through `VideoFrame` where canvas reads are changed; or neither, which rejects
132
+ * with a {@link DemPixelReadError}. Each method is tested on a known image before it is chosen.
133
+ */
134
+ export async function chooseDemPixelReadMethod(): Promise<DemPixelReadMethod> {
135
+ const expected = getTestPixels();
136
+ const image = await createDemImageBitmap(new ImageData(expected, TEST_SIZE, TEST_SIZE));
137
+ try {
138
+ if (await readsExactly(readPixelsWithCanvas, image, expected)) {
139
+ return 'canvas';
140
+ }
141
+ if (typeof VideoFrame === 'undefined') {
142
+ throw new DemPixelReadError('VideoFrame is not available');
143
+ }
144
+ if (!(await readsExactly(readPixelsWithVideoFrame, image, expected))) {
145
+ throw new DemPixelReadError('VideoFrame also changes the pixels');
146
+ }
147
+ return 'video-frame';
148
+ } finally {
149
+ image.close();
150
+ }
151
+ }
152
+
153
+ /**
154
+ * A reader of exact DEM pixels. Later reads reuse the chosen method or a definitive exactness
155
+ * failure. An interrupted probe can be retried by the next read.
156
+ */
157
+ export function createDemPixelReader(): DemPixelReader {
158
+ let method: Promise<DemPixelReadMethod> | undefined;
159
+ return async image => {
160
+ method ||= chooseDemPixelReadMethod().catch((error: unknown) => {
161
+ if (!(error instanceof DemPixelReadError)) {
162
+ method = undefined;
163
+ }
164
+ throw error;
165
+ });
166
+ if ((await method) === 'canvas') {
167
+ return readPixelsWithCanvas(image);
168
+ }
169
+ return readPixelsWithVideoFrame(image);
170
+ };
171
+ }
172
+
173
+ /** Reads exact DEM tile pixels and shares the method selection across the page. */
174
+ export const readDemPixels: DemPixelReader = createDemPixelReader();
@@ -0,0 +1,164 @@
1
+ // tangram-layers
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ import {getCompiledStyleProperty, type StyleFeature} from './style-expression';
6
+ import type {BasemapSource, ResolvedBasemapStyleLayer} from './style-resolver';
7
+
8
+ /** The state of one feature, which `["feature-state", key]` reads. */
9
+ export type FeatureState = Readonly<Record<string, unknown>>;
10
+
11
+ /** The states of features, by feature id. */
12
+ export type FeatureStates = Readonly<Record<string, FeatureState>>;
13
+
14
+ /**
15
+ * The states of a style's features, by source id. A `vector` source's states are by source layer
16
+ * and then by feature id; a `geojson` source's are by feature id, as MapLibre GL JS's
17
+ * `setFeatureState` addresses them. Pass a new object to change a state: objects are compared by
18
+ * identity.
19
+ */
20
+ export type BasemapFeatureState = Readonly<
21
+ Record<string, FeatureStates | Readonly<Record<string, FeatureStates>>>
22
+ >;
23
+
24
+ /** The state of a feature of one style layer, for its paint accessors. */
25
+ export type FeatureStateLookup = {
26
+ /** The feature's state, or undefined for a feature without one. */
27
+ get: (feature: StyleFeature) => FeatureState | undefined;
28
+ /** Changes when the states of the style layer's features change. */
29
+ token: number;
30
+ };
31
+
32
+ /**
33
+ * The id a feature's state is kept under, as MapLibre GL JS reads it: the `promoteId` property of a
34
+ * vector source (none for a source layer that an object `promoteId` does not name), or the
35
+ * feature's id. A GeoJSON source's `promoteId` is already the id of its tile features.
36
+ */
37
+ export function getFeatureStateId(
38
+ feature: StyleFeature,
39
+ source: BasemapSource | undefined,
40
+ sourceLayer: string | undefined
41
+ ): string | number | undefined {
42
+ const promoteId = source?.type === 'vector' ? source.promoteId : undefined;
43
+ let id: unknown = feature.id;
44
+ if (promoteId !== undefined && promoteId !== null) {
45
+ const property =
46
+ typeof promoteId === 'string'
47
+ ? promoteId
48
+ : sourceLayer && typeof promoteId === 'object'
49
+ ? (promoteId as Record<string, unknown>)[sourceLayer]
50
+ : undefined;
51
+ id = typeof property === 'string' ? feature.properties?.[property] : undefined;
52
+ }
53
+ if (typeof id === 'boolean') {
54
+ id = Number(id);
55
+ }
56
+ return typeof id === 'string' || typeof id === 'number' ? id : undefined;
57
+ }
58
+
59
+ /** The states of the features of a style layer's source and source layer. */
60
+ export function getStyleLayerFeatureStates(
61
+ featureState: BasemapFeatureState | null | undefined,
62
+ sourceId: string,
63
+ source: BasemapSource | undefined,
64
+ styleLayer: ResolvedBasemapStyleLayer
65
+ ): FeatureStates | undefined {
66
+ const sourceStates = featureState?.[sourceId];
67
+ if (!sourceStates) {
68
+ return undefined;
69
+ }
70
+ if (source?.type === 'vector') {
71
+ const sourceLayer = styleLayer['source-layer'];
72
+ return typeof sourceLayer === 'string'
73
+ ? (sourceStates as Readonly<Record<string, FeatureStates>>)[sourceLayer]
74
+ : undefined;
75
+ }
76
+ return sourceStates as FeatureStates;
77
+ }
78
+
79
+ /** Whether a style layer's paint reads `["feature-state", ...]`. */
80
+ export function isStyleLayerStateDependent(styleLayer: ResolvedBasemapStyleLayer): boolean {
81
+ return Object.keys(styleLayer.paint || {}).some(
82
+ name => getCompiledStyleProperty(styleLayer, name)?.isStateDependent
83
+ );
84
+ }
85
+
86
+ const stateTokens = new WeakMap<object, number>();
87
+ let nextStateToken = 1;
88
+
89
+ /** A number per states object, 0 for none: a new object, a new number. */
90
+ export function getFeatureStatesToken(states: FeatureStates | undefined): number {
91
+ if (!states) {
92
+ return 0;
93
+ }
94
+ let token = stateTokens.get(states);
95
+ if (token === undefined) {
96
+ token = nextStateToken++;
97
+ stateTokens.set(states, token);
98
+ }
99
+ return token;
100
+ }
101
+
102
+ /**
103
+ * The feature states of a style layer whose paint reads them, or undefined for a style layer whose
104
+ * paint does not: its accessors and update triggers then stay as they are.
105
+ */
106
+ export function getFeatureStateLookup(
107
+ featureState: BasemapFeatureState | null | undefined,
108
+ sourceId: string,
109
+ source: BasemapSource | undefined,
110
+ styleLayer: ResolvedBasemapStyleLayer
111
+ ): FeatureStateLookup | undefined {
112
+ if (!isStyleLayerStateDependent(styleLayer)) {
113
+ return undefined;
114
+ }
115
+ const states = getStyleLayerFeatureStates(featureState, sourceId, source, styleLayer);
116
+ const sourceLayer = styleLayer['source-layer'];
117
+ return {
118
+ get: feature => {
119
+ if (!states) {
120
+ return undefined;
121
+ }
122
+ const id = getFeatureStateId(feature, source, sourceLayer);
123
+ return id === undefined ? undefined : states[id];
124
+ },
125
+ token: getFeatureStatesToken(states)
126
+ };
127
+ }
128
+
129
+ /**
130
+ * A picked feature of a vector or GeoJSON source, named as MapLibre GL JS's `queryRenderedFeatures`
131
+ * names it. `BasemapLayer` adds it to deck.gl's picking info as `basemapFeature`.
132
+ */
133
+ export type BasemapPickedFeature = {
134
+ /** The feature's id (a vector source's `promoteId` property), or undefined without one. */
135
+ id: string | number | undefined;
136
+ /** The id of the feature's source in the style. */
137
+ source: string;
138
+ /** The feature's source layer, for a vector source. */
139
+ sourceLayer: string | undefined;
140
+ /** The id of the style layer that drew the feature. */
141
+ styleLayerId: string;
142
+ /** The feature's properties. */
143
+ properties: Record<string, unknown>;
144
+ };
145
+
146
+ /** The picked feature of a style layer, for a feature of `source`. */
147
+ export function getPickedFeature(
148
+ feature: StyleFeature,
149
+ sourceId: string,
150
+ source: BasemapSource | undefined,
151
+ styleLayerId: string
152
+ ): BasemapPickedFeature {
153
+ const {layerName, ...vectorProperties} = feature.properties || {};
154
+ // Vector tile features carry their source layer as `layerName` (see `getSourceLayerFeatures`).
155
+ const isVector = source?.type === 'vector';
156
+ const sourceLayer = isVector && typeof layerName === 'string' ? layerName : undefined;
157
+ return {
158
+ id: getFeatureStateId(feature, source, sourceLayer),
159
+ source: sourceId,
160
+ sourceLayer,
161
+ styleLayerId,
162
+ properties: isVector ? vectorProperties : feature.properties || {}
163
+ };
164
+ }
@@ -8,7 +8,8 @@
8
8
 
9
9
  import {LayerExtension} from '@deck.gl/core';
10
10
  import type {Layer} from '@deck.gl/core';
11
- import type {ShaderModule} from '@luma.gl/shadertools';
11
+ import type {ShaderPlugin} from '@luma.gl/shaders';
12
+ import {createShaderInjectionPlugin} from './shader-injection-plugin';
12
13
 
13
14
  /** A style's `light`, evaluated at one zoom. */
14
15
  export type FillExtrusionLight = {
@@ -102,7 +103,7 @@ vec3 fillExtrusionLighting_shade(vec3 color, vec3 normal, bool isWall, float t,
102
103
  }
103
104
  `;
104
105
 
105
- const fillExtrusionLighting: ShaderModule<FillExtrusionLightingProps> = {
106
+ const fillExtrusionLighting = createShaderInjectionPlugin({
106
107
  name: 'fillExtrusionLighting',
107
108
  inject: {
108
109
  'vs:#decl': `${UNIFORMS}${SHADE}
@@ -144,6 +145,119 @@ float fillExtrusionLighting_height;
144
145
  `
145
146
  },
146
147
  uniformTypes: {lightDirectionIntensity: 'vec4<f32>', lightColorGradient: 'vec4<f32>'}
148
+ });
149
+
150
+ /**
151
+ * The WGSL of `fillExtrusionLighting`. deck.gl's WGSL extrusions have no vertex color hook, so the
152
+ * color is shaded in the fragment stage, with MapLibre's per-vertex result: the vertex stage passes
153
+ * the light's angle to the face and the wall gradient at the bottom and top of the wall, and the
154
+ * fragment stage shades the color at both and interpolates between them by the height up the wall,
155
+ * as the vertex colors of a wall are interpolated. A face has one color and one normal.
156
+ */
157
+ const fillExtrusionLightingWGSL: ShaderPlugin = {
158
+ name: 'fillExtrusionLighting',
159
+ module: {
160
+ name: 'fillExtrusionLighting',
161
+ source: /* wgsl */ `\
162
+ struct FillExtrusionLightingUniforms {
163
+ lightDirectionIntensity: vec4<f32>,
164
+ lightColorGradient: vec4<f32>,
165
+ };
166
+
167
+ @group(0) @binding(auto) var<uniform> fillExtrusionLighting: FillExtrusionLightingUniforms;
168
+
169
+ var<private> fillExtrusionLighting_isWall: bool;
170
+ var<private> fillExtrusionLighting_base: f32;
171
+ var<private> fillExtrusionLighting_height: f32;
172
+
173
+ // The vertical gradient factor of the GLSL shade function, at a height t up the wall.
174
+ fn fillExtrusionLighting_gradient(t: f32) -> f32 {
175
+ let intensity = fillExtrusionLighting.lightDirectionIntensity.w;
176
+ let verticalGradient = fillExtrusionLighting.lightColorGradient.a;
177
+ let gradient = clamp(
178
+ (t + max(0.0, fillExtrusionLighting_base)) * pow(max(0.0, fillExtrusionLighting_height) / 150.0, 0.5),
179
+ mix(0.7, 0.98, 1.0 - intensity),
180
+ 1.0
181
+ );
182
+ return (1.0 - verticalGradient) + verticalGradient * gradient;
183
+ }
184
+
185
+ // The GLSL shade function, for the light's angle to the face and a gradient factor.
186
+ fn fillExtrusionLighting_shade(color: vec3<f32>, directionalAngle: f32, gradient: f32) -> vec3<f32> {
187
+ let intensity = fillExtrusionLighting.lightDirectionIntensity.w;
188
+ let lightColor = fillExtrusionLighting.lightColorGradient.rgb;
189
+ let colorValue = color.r * 0.2126 + color.g * 0.7152 + color.b * 0.0722;
190
+ var directional = mix(1.0 - intensity, max(1.0 - colorValue + intensity, 1.0), directionalAngle);
191
+ directional *= gradient;
192
+ return clamp(
193
+ (color + vec3<f32>(0.03)) * directional * lightColor,
194
+ mix(vec3<f32>(0.0), vec3<f32>(0.3), 1.0 - lightColor),
195
+ vec3<f32>(1.0)
196
+ );
197
+ }
198
+ `,
199
+ uniformTypes: {lightDirectionIntensity: 'vec4<f32>', lightColorGradient: 'vec4<f32>'}
200
+ },
201
+ interStageVariables: {
202
+ // The light's angle to the face: clamp(dot(normal, light direction), 0, 1).
203
+ fillExtrusionLighting_directional: {type: 'f32'},
204
+ // The gradient factors at the bottom (x) and top (y) of the face, and the height up it (z).
205
+ fillExtrusionLighting_gradients: {type: 'vec3<f32>'}
206
+ },
207
+ injections: [
208
+ {
209
+ stage: 'vertex',
210
+ target: '#main-start',
211
+ // The attributes are the entry point's, as in the GLSL injection.
212
+ wgsl: /* wgsl */ `
213
+ #ifdef NON_INSTANCED_MODEL
214
+ fillExtrusionLighting_isWall = false;
215
+ fillExtrusionLighting_gradients = vec3<f32>(1.0, 1.0, 1.0);
216
+ #else
217
+ fillExtrusionLighting_isWall = true;
218
+ fillExtrusionLighting_gradients.z = attributes.positions.y;
219
+ #endif
220
+ // Polygons are raised to fill-extrusion-base, and extruded from there by the rest of the height.
221
+ fillExtrusionLighting_base = attributes.vertexPositions.z;
222
+ fillExtrusionLighting_height = attributes.vertexPositions.z + attributes.elevations;
223
+ `
224
+ },
225
+ {
226
+ stage: 'vertex',
227
+ target: 'DECKGL_FILTER_GL_POSITION',
228
+ wgsl: /* wgsl */ `
229
+ // As in the GLSL injection: on a globe, a roof faces up.
230
+ var fillExtrusionLighting_normal = geometry.normal;
231
+ if (project.projectionMode == PROJECTION_MODE_GLOBE && !fillExtrusionLighting_isWall) {
232
+ fillExtrusionLighting_normal = vec3<f32>(0.0, 0.0, 1.0);
233
+ }
234
+ fillExtrusionLighting_directional = clamp(
235
+ dot(fillExtrusionLighting_normal, fillExtrusionLighting.lightDirectionIntensity.xyz),
236
+ 0.0,
237
+ 1.0
238
+ );
239
+ if (fillExtrusionLighting_isWall) {
240
+ fillExtrusionLighting_gradients.x = fillExtrusionLighting_gradient(0.0);
241
+ fillExtrusionLighting_gradients.y = fillExtrusionLighting_gradient(1.0);
242
+ }
243
+ `
244
+ },
245
+ {
246
+ stage: 'fragment',
247
+ target: 'DECKGL_FILTER_COLOR',
248
+ // The layer is drawn unlit (see `draw`), so color is the extrusion's own.
249
+ wgsl: /* wgsl */ `
250
+ *color = vec4<f32>(
251
+ mix(
252
+ fillExtrusionLighting_shade((*color).rgb, fillExtrusionLighting_directional, fillExtrusionLighting_gradients.x),
253
+ fillExtrusionLighting_shade((*color).rgb, fillExtrusionLighting_directional, fillExtrusionLighting_gradients.y),
254
+ fillExtrusionLighting_gradients.z
255
+ ),
256
+ (*color).a
257
+ );
258
+ `
259
+ }
260
+ ]
147
261
  };
148
262
 
149
263
  /**
@@ -154,10 +268,7 @@ const UNLIT_MATERIAL = {unlit: true};
154
268
 
155
269
  function isExtrudedPolygonLayer(layer: Layer): boolean {
156
270
  const state = layer.state as Record<string, unknown> | undefined;
157
- return (
158
- layer.context.device.type !== 'webgpu' &&
159
- Boolean(state && 'polygonTesselator' in state && (layer.props as any).extruded)
160
- );
271
+ return Boolean(state && 'polygonTesselator' in state && (layer.props as any).extruded);
161
272
  }
162
273
 
163
274
  /**
@@ -167,8 +278,7 @@ function isExtrudedPolygonLayer(layer: Layer): boolean {
167
278
  * layer at every draw. A light anchored to the viewport turns with the viewport's bearing, which is
168
279
  * read at every draw. On a globe, the light is placed relative to
169
280
  * the ground under each building. Polygons must lie at `fill-extrusion-base` and be extruded by
170
- * the rest of the height. WebGL only: on WebGPU the extension adds no shader code, and buildings
171
- * keep deck.gl's lights.
281
+ * the rest of the height. On WebGL and WebGPU.
172
282
  */
173
283
  export class FillExtrusionLightingExtension extends LayerExtension {
174
284
  static extensionName = 'FillExtrusionLightingExtension';
@@ -182,7 +292,14 @@ export class FillExtrusionLightingExtension extends LayerExtension {
182
292
  }
183
293
 
184
294
  getShaders(this: Layer, extension: this): any {
185
- return extension.isEnabled(this) ? {modules: [fillExtrusionLighting]} : null;
295
+ if (!extension.isEnabled(this)) {
296
+ return null;
297
+ }
298
+ return {
299
+ plugins: [
300
+ this.context.device.type === 'webgpu' ? fillExtrusionLightingWGSL : fillExtrusionLighting
301
+ ]
302
+ };
186
303
  }
187
304
 
188
305
  draw(this: Layer<any>, params: any, extension: this) {
@@ -8,7 +8,7 @@
8
8
 
9
9
  import {LayerExtension} from '@deck.gl/core';
10
10
  import type {Layer} from '@deck.gl/core';
11
- import type {ShaderModule} from '@luma.gl/shadertools';
11
+ import {createShaderInjectionPlugin} from './shader-injection-plugin';
12
12
 
13
13
  /**
14
14
  * Draws the `PathLayer`s of a fill's outline (`fill-outline-color`) as MapLibre GL JS draws it: as
@@ -31,7 +31,7 @@ export class FillOutlineExtension extends LayerExtension {
31
31
  // `vPathPosition.x` runs from -1 to 1 across the stroke. Its screen gradient gives the
32
32
  // distance to the path in device pixels, and the direction across the line; the gradient is
33
33
  // taken before any fragment of the quad is discarded. Picking draws the same pixels.
34
- const fillOutline: ShaderModule = {
34
+ const fillOutline = createShaderInjectionPlugin({
35
35
  name: 'fillOutline',
36
36
  inject: {
37
37
  // Drawn 1.5 device pixels to each side of the path, so that with multisampling every pixel
@@ -60,8 +60,8 @@ export class FillOutlineExtension extends LayerExtension {
60
60
  }
61
61
  `
62
62
  }
63
- };
64
- return {modules: [fillOutline]};
63
+ });
64
+ return {plugins: [fillOutline]};
65
65
  }
66
66
  }
67
67
 
@@ -39,10 +39,11 @@ export type FillPatternGroup = {
39
39
 
40
40
  const warnedMissingPatterns = new Set<string>();
41
41
 
42
- function warnMissingPattern(name: string): void {
43
- if (!warnedMissingPatterns.has(name)) {
44
- warnedMissingPatterns.add(name);
45
- log.warn(`[BasemapLayer] fill-pattern "${name}" is not in the style's sprite; skipped`)();
42
+ function warnMissingPattern(propertyName: string, name: string): void {
43
+ const key = `${propertyName}:${name}`;
44
+ if (!warnedMissingPatterns.has(key)) {
45
+ warnedMissingPatterns.add(key);
46
+ log.warn(`[BasemapLayer] ${propertyName} "${name}" is not in the style's sprite; skipped`)();
46
47
  }
47
48
  }
48
49
 
@@ -60,15 +61,18 @@ const patternGroupCache = new WeakMap<
60
61
  * Returns no groups while the sprites load (`null`) or when the layer has no `fill-pattern`. A
61
62
  * pattern that does not depend on feature data keeps the tile's feature array, so deck.gl does not
62
63
  * re-tessellate the features at a new zoom step; per-feature groups are cached per tile, style
63
- * layer, sprite list and zoom.
64
+ * layer, sprite list and zoom. `propertyName` is `line-pattern` for a patterned line, which is
65
+ * grouped the same way, and `background-pattern` for a patterned background, whose features are the
66
+ * polygons that cover the map.
64
67
  */
65
68
  export function getFillPatternGroups(
66
69
  features: any[],
67
70
  styleLayer: StyleLayerLike,
68
71
  zoom: number,
69
- spriteAtlases: SpriteAtlas[] | null | undefined
72
+ spriteAtlases: SpriteAtlas[] | null | undefined,
73
+ propertyName: 'fill-pattern' | 'line-pattern' | 'background-pattern' = 'fill-pattern'
70
74
  ): FillPatternGroup[] {
71
- const property = getCompiledStyleProperty(styleLayer, 'fill-pattern');
75
+ const property = getCompiledStyleProperty(styleLayer, propertyName);
72
76
  if (!property || !spriteAtlases?.length) {
73
77
  return [];
74
78
  }
@@ -82,7 +86,7 @@ export function getFillPatternGroups(
82
86
  }
83
87
  const icon = resolveSpriteIcon(spriteAtlases, name);
84
88
  if (!icon) {
85
- warnMissingPattern(name);
89
+ warnMissingPattern(propertyName, name);
86
90
  }
87
91
  return icon;
88
92
  };
@@ -155,7 +159,9 @@ export function getFillPatternGroups(
155
159
  return result;
156
160
  }
157
161
 
158
- const PATTERN_TEXTURE_PARAMETERS = {mipmapFilter: 'none'} as const;
162
+ // luma.gl's WebGPU sampler leaves `mipmapFilter: 'none'` out, which samples the nearest mipmap
163
+ // level: the level of detail is clamped to the full-size image instead.
164
+ const PATTERN_TEXTURE_PARAMETERS = {mipmapFilter: 'none', lodMaxClamp: 0} as const;
159
165
 
160
166
  type PatternAtlas = {
161
167
  image: SpriteAtlas['image'] | OffscreenCanvas | HTMLCanvasElement | ImageData;
@@ -350,6 +356,61 @@ export function bleedIntoTransparentPixels(
350
356
  }
351
357
  }
352
358
 
359
+ /** Consecutive features, in draw order, whose images are in one group's atlas. */
360
+ export type PatternRun = {
361
+ group: FillPatternGroup;
362
+ features: any[];
363
+ /** Unique among the runs of one list of groups, and the same while the groups are reused. */
364
+ key: string;
365
+ };
366
+
367
+ /** The runs per list of groups. */
368
+ const patternRunCache = new WeakMap<FillPatternGroup[], PatternRun[]>();
369
+
370
+ /**
371
+ * Splits groups into runs of consecutive `features` with the same atlas, so that sublayers drawn
372
+ * run after run keep the features' draw order, such as `line-sort-key`'s, across atlases. A group
373
+ * whose features are consecutive stays one run. The runs of a group share its pattern atlas.
374
+ * Cached per list of groups, which `getFillPatternGroups` reuses while its inputs are unchanged.
375
+ */
376
+ export function getPatternRuns(features: any[], groups: FillPatternGroup[]): PatternRun[] {
377
+ const cached = patternRunCache.get(groups);
378
+ if (cached) {
379
+ return cached;
380
+ }
381
+ const groupOf = new Map<any, FillPatternGroup>();
382
+ for (const group of groups) {
383
+ for (const feature of group.features) {
384
+ groupOf.set(feature, group);
385
+ }
386
+ }
387
+ const result: PatternRun[] = [];
388
+ const runCounts = new Map<FillPatternGroup, number>();
389
+ for (const feature of features) {
390
+ const group = groupOf.get(feature);
391
+ if (!group) {
392
+ continue;
393
+ }
394
+ let run = result[result.length - 1];
395
+ if (run?.group !== group) {
396
+ const count = runCounts.get(group) ?? 0;
397
+ runCounts.set(group, count + 1);
398
+ const key = count ? `${group.atlasIndex}-${count}` : `${group.atlasIndex}`;
399
+ run = {group, features: [], key};
400
+ result.push(run);
401
+ }
402
+ run.features.push(feature);
403
+ }
404
+ // A group of one run keeps its feature array, so deck.gl does not re-tessellate its features.
405
+ for (const run of result) {
406
+ if (runCounts.get(run.group) === 1) {
407
+ run.features = run.group.features;
408
+ }
409
+ }
410
+ patternRunCache.set(groups, result);
411
+ return result;
412
+ }
413
+
353
414
  /** The features without an image per list of groups. */
354
415
  const unpatternedCache = new WeakMap<FillPatternGroup[], any[]>();
355
416
 
@@ -398,3 +459,20 @@ export function getFillPatternProps(group: FillPatternGroup, zoom: number) {
398
459
  : unitScale / getPixelRatio
399
460
  };
400
461
  }
462
+
463
+ /**
464
+ * `LinePatternExtension` props for a group of patterned lines: the pattern atlas, which its
465
+ * shader reads as MapLibre GL JS's does, and pixels per common unit at the integer zoom, which
466
+ * the pattern's repeats are measured in.
467
+ */
468
+ export function getLinePatternProps(group: FillPatternGroup, zoom: number) {
469
+ group.patternAtlas ??= getPatternAtlas(group.atlas, group.names);
470
+ const {image, mapping} = group.patternAtlas;
471
+ return {
472
+ linePatternAtlas: image,
473
+ linePatternMapping: mapping,
474
+ linePatternPixelsPerUnit: 2 ** Math.floor(zoom),
475
+ textureParameters: PATTERN_TEXTURE_PARAMETERS,
476
+ getLinePattern: group.getFillPattern
477
+ };
478
+ }