@tangram.gl/basemap-layers 0.0.1 → 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,572 @@
1
+ // tangram-layers
2
+ // SPDX-License-Identifier: MIT
3
+ // Copyright (c) vis.gl contributors
4
+
5
+ // Portions adapted from MapLibre GL JS
6
+ // SPDX-License-Identifier: BSD-3-Clause
7
+ // Copyright (c) 2023, MapLibre contributors
8
+ // Copyright (c) 2020, Mapbox
9
+
10
+ /**
11
+ * @license
12
+ * Portions of this file are adapted from MapLibre GL JS v6.13.0,
13
+ * src/shaders/glsl/color_relief.fragment.glsl and
14
+ * src/style/style_layer/color_relief_style_layer.ts,
15
+ * under these licenses (see also THIRD-PARTY-NOTICES.md):
16
+ *
17
+ * Copyright (c) 2023, MapLibre contributors
18
+ *
19
+ * All rights reserved.
20
+ *
21
+ * Redistribution and use in source and binary forms, with or without modification,
22
+ * are permitted provided that the following conditions are met:
23
+ *
24
+ * * Redistributions of source code must retain the above copyright notice,
25
+ * this list of conditions and the following disclaimer.
26
+ * * Redistributions in binary form must reproduce the above copyright notice,
27
+ * this list of conditions and the following disclaimer in the documentation
28
+ * and/or other materials provided with the distribution.
29
+ * * Neither the name of MapLibre GL JS nor the names of its contributors
30
+ * may be used to endorse or promote products derived from this software
31
+ * without specific prior written permission.
32
+ *
33
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
34
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
35
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
36
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
37
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
38
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
39
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
40
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
41
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
42
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
43
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
44
+ *
45
+ * MapLibre GL JS contains code from mapbox-gl-js v1.13 and earlier, licensed under a
46
+ * BSD-3-Clause license:
47
+ *
48
+ * Copyright (c) 2020, Mapbox
49
+ * Redistribution and use in source and binary forms, with or without modification,
50
+ * are permitted provided that the following conditions are met:
51
+ *
52
+ * * Redistributions of source code must retain the above copyright notice,
53
+ * this list of conditions and the following disclaimer.
54
+ * * Redistributions in binary form must reproduce the above copyright notice,
55
+ * this list of conditions and the following disclaimer in the documentation
56
+ * and/or other materials provided with the distribution.
57
+ * * Neither the name of Mapbox GL JS nor the names of its contributors
58
+ * may be used to endorse or promote products derived from this software
59
+ * without specific prior written permission.
60
+ *
61
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
62
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
63
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
64
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
65
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
66
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
67
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
68
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
69
+ * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
70
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
71
+ * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
72
+ */
73
+
74
+ import type {Layer, LayersList, UpdateParameters} from '@deck.gl/core';
75
+ import type {Device, Texture} from '@luma.gl/core';
76
+ import {
77
+ type DemNeighbors,
78
+ type DemTile,
79
+ type DemTileHeader,
80
+ DemTileLayer,
81
+ type DemTileLayerProps,
82
+ type DemUnpackVector,
83
+ PREMULTIPLIED_BLEND_PARAMETERS,
84
+ getBorderedElevations
85
+ } from './hillshade-layer';
86
+ import {ProjectedBitmapLayer} from './projected-bitmap-layer';
87
+ import {type ColorRampStops, getColorRampStops} from './style-expression';
88
+
89
+ /**
90
+ * `color-relief` style layers over `raster-dem` sources, drawn as MapLibre GL JS draws them.
91
+ *
92
+ * MapLibre reads the stops of the `color-relief-color` ramp, an `interpolate` expression over
93
+ * `["elevation"]`, into two textures: the stops' elevations, packed with the DEM's encoding, and
94
+ * their colors. Its fragment shader finds a pixel's elevation between two stops with a binary
95
+ * search and blends their colors linearly, whatever the interpolation type. Here the ramp is one
96
+ * float texture of the same values, and the DEM tile a texture of its elevations, with a
97
+ * one-pixel border from its neighbors, as the hillshade layers prepare theirs.
98
+ */
99
+
100
+ /** A color ramp, as MapLibre GL JS's `ColorReliefStyleLayer` makes it. */
101
+ export type ColorRamp = {
102
+ /** Elevations in meters, ascending. */
103
+ elevationStops: number[];
104
+ /** Premultiplied RGBA in 0-1, one per elevation stop. */
105
+ colorStops: [number, number, number, number][];
106
+ };
107
+
108
+ const TRANSPARENT: [number, number, number, number] = [0, 0, 0, 0];
109
+
110
+ /**
111
+ * The stops of each `color-relief-color` value, with its contents when they were read, so that a
112
+ * value edited in place is read again.
113
+ */
114
+ const stopsCache = new WeakMap<object, {snapshot: string; stops: ColorRampStops | null}>();
115
+
116
+ function getStops(value: unknown): ColorRampStops | null {
117
+ if (!value || typeof value !== 'object') {
118
+ return getColorRampStops('color-relief-color', value, 'elevation');
119
+ }
120
+ const snapshot = JSON.stringify(value);
121
+ let cached = stopsCache.get(value);
122
+ if (cached?.snapshot !== snapshot) {
123
+ cached = {snapshot, stops: getColorRampStops('color-relief-color', value, 'elevation')};
124
+ stopsCache.set(value, cached);
125
+ }
126
+ return cached.stops;
127
+ }
128
+
129
+ /**
130
+ * The color ramp of a `color-relief-color` value, at most `maxLength` stops long, as MapLibre GL JS
131
+ * creates it: the stops of an `interpolate` expression, or one transparent stop for any other
132
+ * value. A single stop is repeated one meter higher. A longer ramp is resampled to `maxLength`
133
+ * stops, which MapLibre warns may not render properly.
134
+ */
135
+ export function createColorRamp(value: unknown, maxLength: number): ColorRamp {
136
+ const stops = getStops(value);
137
+ const ramp: ColorRamp = stops
138
+ ? {elevationStops: [...stops.inputs], colorStops: [...stops.colors]}
139
+ : {elevationStops: [], colorStops: []};
140
+ if (ramp.elevationStops.length < 1) {
141
+ ramp.elevationStops = [0];
142
+ ramp.colorStops = [TRANSPARENT];
143
+ }
144
+ if (ramp.elevationStops.length < 2) {
145
+ ramp.elevationStops.push(ramp.elevationStops[0] + 1);
146
+ ramp.colorStops.push(ramp.colorStops[0]);
147
+ }
148
+ if (ramp.elevationStops.length <= maxLength) {
149
+ return ramp;
150
+ }
151
+ const remapped: ColorRamp = {elevationStops: [], colorStops: []};
152
+ const step = (ramp.elevationStops.length - 1) / (maxLength - 1);
153
+ for (let i = 0; i < ramp.elevationStops.length - 0.5; i += step) {
154
+ remapped.elevationStops.push(ramp.elevationStops[Math.round(i)]);
155
+ remapped.colorStops.push(ramp.colorStops[Math.round(i)]);
156
+ }
157
+ return remapped;
158
+ }
159
+
160
+ /** Whether a ramp draws anything: whether any of its colors is not transparent. */
161
+ export function isColorRampVisible(ramp: ColorRamp): boolean {
162
+ return ramp.colorStops.some(color => color[3] > 0);
163
+ }
164
+
165
+ /**
166
+ * An elevation as the shader reads a DEM pixel of it: rounded to the steps of the encoding
167
+ * `unpack`, `min(factors)` meters, within what its 8-bit red, green and blue hold, as MapLibre GL
168
+ * JS's `packDEMData` rounds it; then to the steps of the elevation texture (see
169
+ * `prepareColorReliefTexture`). Unlike `packDEMData`, it counts the elevation once where factors
170
+ * overlap, as in the default custom factors `[1, 1, 1, 0]`, whose pixel `[100, 0, 0]` is 100 m.
171
+ */
172
+ export function quantizeElevation(
173
+ elevation: number,
174
+ [redFactor, greenFactor, blueFactor, baseShift]: DemUnpackVector
175
+ ): number {
176
+ const factors = [redFactor, greenFactor, blueFactor].filter(factor => factor !== 0);
177
+ if (factors.length === 0) {
178
+ return getTextureElevation(-baseShift);
179
+ }
180
+ const minScale = Math.min(...factors);
181
+ const maxSteps = Math.round((255 * factors.reduce((sum, factor) => sum + factor)) / minScale);
182
+ const steps = Math.min(Math.max(Math.round((elevation + baseShift) / minScale), 0), maxSteps);
183
+ return getTextureElevation(steps * minScale - baseShift);
184
+ }
185
+
186
+ /**
187
+ * The texels of a ramp's texture, `colorStops.length` wide and 2 high, RGBA in 8 bits: the first
188
+ * row holds the colors, premultiplied and rounded to 8 bits as MapLibre GL JS uploads them, and the
189
+ * second the elevations, as the shader reads them back from the DEM encoding `unpack`, encoded as
190
+ * the elevation texture encodes them (see `prepareColorReliefTexture`). WebGPU can bind an 8-bit
191
+ * texture as a float texture without the `float32-filterable` feature; a 32-bit float one, not.
192
+ */
193
+ export function getColorRampTexels(ramp: ColorRamp, unpack: DemUnpackVector): Uint8Array {
194
+ const size = ramp.colorStops.length;
195
+ const texels = new Uint8Array(size * 2 * 4);
196
+ ramp.colorStops.forEach(([r, g, b, a], index) => {
197
+ // MapLibre stores the color unpremultiplied in 8 bits, and premultiplies it on upload.
198
+ const alpha = Math.round(a * 255);
199
+ const premultiply = (channel: number) =>
200
+ a === 0 ? 0 : Math.round((Math.round((channel * 255) / a) * alpha) / 255);
201
+ texels.set([premultiply(r), premultiply(g), premultiply(b), alpha], index * 4);
202
+ });
203
+ ramp.elevationStops.forEach((elevation, index) => {
204
+ setTextureElevation(texels, (size + index) * 4, quantizeElevation(elevation, unpack));
205
+ });
206
+ return texels;
207
+ }
208
+
209
+ /** The elevations a DEM texture holds: as terrarium, in 1/256 meter steps. */
210
+ const ELEVATION_SHIFT = 32768;
211
+ const ELEVATION_STEPS = 256;
212
+ const MAX_TEXTURE_VALUE = 2 ** 24 - 1;
213
+
214
+ /** An elevation as the elevation texture stores it, in 1/256 meter steps, 24 bits. */
215
+ function getTextureValue(elevation: number): number {
216
+ return Math.min(
217
+ Math.max(Math.round((elevation + ELEVATION_SHIFT) * ELEVATION_STEPS), 0),
218
+ MAX_TEXTURE_VALUE
219
+ );
220
+ }
221
+
222
+ /** Writes an elevation at `index` of RGBA texels, as terrarium in red, green and blue. */
223
+ function setTextureElevation(
224
+ texels: Uint8Array | Uint8ClampedArray,
225
+ index: number,
226
+ elevation: number
227
+ ): void {
228
+ const value = getTextureValue(elevation);
229
+ texels[index] = Math.floor(value / 65536);
230
+ texels[index + 1] = Math.floor(value / 256) % 256;
231
+ texels[index + 2] = value % 256;
232
+ texels[index + 3] = 255;
233
+ }
234
+
235
+ /** An elevation as the shader reads it from the elevation texture. */
236
+ function getTextureElevation(elevation: number): number {
237
+ return getTextureValue(elevation) / ELEVATION_STEPS - ELEVATION_SHIFT;
238
+ }
239
+
240
+ /**
241
+ * The elevation texture of a DEM tile, `dim + 2` pixels square: the tile and a one-pixel border
242
+ * from its loaded neighbors (see `getBorderedElevations`), RGBA. Elevations are encoded as
243
+ * terrarium: `R * 256 + G + B / 256 - 32768`, whatever the source's encoding, which keeps their
244
+ * linear filtering, and are clamped to that encoding's range.
245
+ */
246
+ export function prepareColorReliefTexture(
247
+ dem: DemTile,
248
+ getNeighbor: DemNeighbors = () => null
249
+ ): Uint8ClampedArray<ArrayBuffer> {
250
+ const getElevation = getBorderedElevations(dem, getNeighbor);
251
+ const size = dem.dim + 2;
252
+ const texture = new Uint8ClampedArray(size * size * 4);
253
+ for (let row = 0; row < size; row++) {
254
+ for (let column = 0; column < size; column++) {
255
+ setTextureElevation(texture, (row * size + column) * 4, getElevation(column - 1, row - 1));
256
+ }
257
+ }
258
+ return texture;
259
+ }
260
+
261
+ /** The `colorRelief` shader module's uniforms and bindings. */
262
+ export type ColorReliefUniforms = {
263
+ /** `color-relief-opacity`. */
264
+ opacity: number;
265
+ /** The number of stops in the ramp. */
266
+ rampSize: number;
267
+ colorReliefRamp?: Texture;
268
+ };
269
+
270
+ const colorReliefModule = {
271
+ name: 'colorRelief',
272
+ fs: /* glsl */ `\
273
+ layout(std140) uniform colorReliefUniforms {
274
+ float opacity;
275
+ float rampSize;
276
+ } colorRelief;
277
+
278
+ // Colors in the first row, elevations in the second, encoded as the DEM texture encodes them.
279
+ uniform sampler2D colorReliefRamp;
280
+
281
+ float colorRelief_getStop(int stop) {
282
+ vec3 data = floor(texelFetch(colorReliefRamp, ivec2(stop, 1), 0).rgb * 255.0 + 0.5);
283
+ return dot(data, vec3(256.0, 1.0, 1.0 / 256.0)) - 32768.0;
284
+ }
285
+
286
+ // MapLibre GL JS's color-relief fragment shader. \`uv\` is the position in the tile.
287
+ vec4 colorRelief_getColor(sampler2D dem, vec2 uv) {
288
+ // The texture has a one-pixel border around the tile.
289
+ vec2 size = vec2(textureSize(dem, 0));
290
+ vec4 data = texture(dem, (uv * (size - 2.0) + 1.0) / size) * 255.0;
291
+ data.a = -1.0;
292
+ float elevation = dot(data, vec4(256.0, 1.0, 1.0 / 256.0, 32768.0));
293
+
294
+ // Binary search for the stops around the elevation.
295
+ int count = int(colorRelief.rampSize + 0.5);
296
+ int r = count - 1;
297
+ int l = 0;
298
+ float elevationL = colorRelief_getStop(l);
299
+ float elevationR = colorRelief_getStop(r);
300
+ while (r - l > 1) {
301
+ int m = (r + l) / 2;
302
+ float elevationM = colorRelief_getStop(m);
303
+ if (elevation < elevationM) {
304
+ r = m;
305
+ elevationR = elevationM;
306
+ } else {
307
+ l = m;
308
+ elevationL = elevationM;
309
+ }
310
+ }
311
+ // Stops that round to one elevation step have no width: an elevation at or above them takes the
312
+ // upper stop's color, as the search does where equal stops are followed by another.
313
+ float t = elevationR > elevationL
314
+ ? (elevation - elevationL) / (elevationR - elevationL)
315
+ : (elevation < elevationL ? 0.0 : 1.0);
316
+ // MapLibre samples a linearly filtered texture of the colors, clamped to its edges.
317
+ float x = clamp(float(l) + t, 0.0, float(count - 1));
318
+ int i = min(int(x), count - 2);
319
+ vec4 color = mix(
320
+ texelFetch(colorReliefRamp, ivec2(i, 0), 0),
321
+ texelFetch(colorReliefRamp, ivec2(i + 1, 0), 0),
322
+ x - float(i)
323
+ );
324
+ return color * colorRelief.opacity;
325
+ }
326
+ `,
327
+ source: /* wgsl */ `\
328
+ struct ColorReliefUniforms {
329
+ opacity: f32,
330
+ rampSize: f32,
331
+ };
332
+
333
+ @group(0) @binding(auto) var<uniform> colorRelief: ColorReliefUniforms;
334
+ // Colors in the first row, elevations in the second, encoded as the DEM texture encodes them.
335
+ @group(0) @binding(auto) var colorReliefRamp: texture_2d<f32>;
336
+
337
+ // The GLSL functions above, in WGSL.
338
+ fn colorRelief_getStop(stop: i32) -> f32 {
339
+ let data = floor(textureLoad(colorReliefRamp, vec2<i32>(stop, 1), 0).rgb * 255.0 + 0.5);
340
+ return dot(data, vec3<f32>(256.0, 1.0, 1.0 / 256.0)) - 32768.0;
341
+ }
342
+
343
+ // The elevation texture is sampled from its first mip level: it has no others.
344
+ fn colorRelief_getColor(dem: texture_2d<f32>, demSampler: sampler, uv: vec2<f32>) -> vec4<f32> {
345
+ let size = vec2<f32>(textureDimensions(dem, 0));
346
+ var data = textureSampleLevel(dem, demSampler, (uv * (size - 2.0) + 1.0) / size, 0.0) * 255.0;
347
+ data.a = -1.0;
348
+ let elevation = dot(data, vec4<f32>(256.0, 1.0, 1.0 / 256.0, 32768.0));
349
+
350
+ let count = i32(colorRelief.rampSize + 0.5);
351
+ var r = count - 1;
352
+ var l = 0;
353
+ var elevationL = colorRelief_getStop(l);
354
+ var elevationR = colorRelief_getStop(r);
355
+ while (r - l > 1) {
356
+ let m = (r + l) / 2;
357
+ let elevationM = colorRelief_getStop(m);
358
+ if (elevation < elevationM) {
359
+ r = m;
360
+ elevationR = elevationM;
361
+ } else {
362
+ l = m;
363
+ elevationL = elevationM;
364
+ }
365
+ }
366
+ var t = select(1.0, 0.0, elevation < elevationL);
367
+ if (elevationR > elevationL) {
368
+ t = (elevation - elevationL) / (elevationR - elevationL);
369
+ }
370
+ let x = clamp(f32(l) + t, 0.0, f32(count - 1));
371
+ let i = min(i32(x), count - 2);
372
+ let color = mix(
373
+ textureLoad(colorReliefRamp, vec2<i32>(i, 0), 0),
374
+ textureLoad(colorReliefRamp, vec2<i32>(i + 1, 0), 0),
375
+ x - f32(i)
376
+ );
377
+ return color * colorRelief.opacity;
378
+ }
379
+ `,
380
+ uniformTypes: {
381
+ opacity: 'f32',
382
+ rampSize: 'f32'
383
+ }
384
+ } as const;
385
+
386
+ /** A ramp's texture, created by the `ColorReliefTileLayer` that owns it. */
387
+ export type ColorRampTexture = {texture: Texture; size: number};
388
+
389
+ type ColorReliefBitmapLayerProps = {
390
+ colorRampTexture: ColorRampTexture;
391
+ colorReliefOpacity: number;
392
+ };
393
+
394
+ const GLSL_INJECTION = {
395
+ // At the end of main(), where the bitmap's sampler is in scope.
396
+ 'fs:#main-end': /* glsl */ `
397
+ if (!bool(picking.isActive)) {
398
+ fragColor = colorRelief_getColor(bitmapTexture, geometry.uv) * layer.opacity;
399
+ }
400
+ `
401
+ };
402
+
403
+ const WGSL_INJECTION = {
404
+ // As in `HillshadeBitmapLayer`: deck.gl's WGSL bitmap shader has no hook after its color, and
405
+ // premultiplies the filtered color itself, so the premultiplied color is divided by its alpha
406
+ // here. In picking, the shader returns its own color and ignores this one.
407
+ 'fs:DECKGL_FILTER_COLOR': /* wgsl */ `
408
+ let colorReliefColor = colorRelief_getColor(bitmapTexture, bitmapTextureSampler, geometry.uv) *
409
+ layer.opacity;
410
+ *color = vec4<f32>(
411
+ select(vec3<f32>(0.0), colorReliefColor.rgb / colorReliefColor.a, colorReliefColor.a > 0.0),
412
+ colorReliefColor.a
413
+ );
414
+ `
415
+ };
416
+
417
+ /**
418
+ * A `BitmapLayer` whose image is a tile's elevation texture (see `prepareColorReliefTexture`),
419
+ * colored by a ramp as MapLibre GL JS colors it, on WebGL and on WebGPU.
420
+ */
421
+ class ColorReliefBitmapLayer extends ProjectedBitmapLayer<ColorReliefBitmapLayerProps> {
422
+ static layerName = 'ColorReliefBitmapLayer';
423
+
424
+ getShaders() {
425
+ const shaders = super.getShaders();
426
+ return {
427
+ ...shaders,
428
+ modules: [...shaders.modules, colorReliefModule],
429
+ inject: {
430
+ ...shaders.inject,
431
+ ...(this.context.device.type === 'webgpu' ? WGSL_INJECTION : GLSL_INJECTION)
432
+ }
433
+ };
434
+ }
435
+
436
+ draw(options: any) {
437
+ const {colorRampTexture, colorReliefOpacity} = this.props;
438
+ const colorRelief: ColorReliefUniforms = {
439
+ opacity: colorReliefOpacity,
440
+ rampSize: colorRampTexture.size,
441
+ colorReliefRamp: colorRampTexture.texture
442
+ };
443
+ for (const model of this.getModels()) {
444
+ model.shaderInputs.setProps({colorRelief});
445
+ }
446
+ super.draw(options);
447
+ }
448
+ }
449
+
450
+ /** The elevation texture of a DEM tile, with the neighbors it was prepared with. */
451
+ const preparedTextures = new WeakMap<DemTile, {key: string; image: ImageData}>();
452
+
453
+ /** Props of a `ColorReliefTileLayer`. */
454
+ export type ColorReliefTileLayerProps = DemTileLayerProps & {
455
+ /** `color-relief-color`, as the style sets it. */
456
+ colorReliefColor: unknown;
457
+ /** `color-relief-opacity`, evaluated. */
458
+ colorReliefOpacity: number;
459
+ /** The unpack vector of the source, to which MapLibre rounds the ramp's elevations. */
460
+ colorReliefUnpack: DemUnpackVector;
461
+ /** Extra props of every tile's bitmap layer, such as `parameters`. */
462
+ colorReliefSubLayerProps?: Record<string, unknown>;
463
+ };
464
+
465
+ /**
466
+ * The tiles of a `raster-dem` source, colored by elevation by one `color-relief` style layer (see
467
+ * `DemTileLayer`). The layer owns the texture of its ramp, which its tiles share.
468
+ */
469
+ export class ColorReliefTileLayer extends DemTileLayer<ColorReliefTileLayerProps> {
470
+ static layerName = 'ColorReliefTileLayer';
471
+ static defaultProps = {
472
+ ...DemTileLayer.defaultProps,
473
+ colorReliefColor: {type: 'object', value: null, compare: false},
474
+ colorReliefOpacity: {type: 'number', value: 1},
475
+ colorReliefUnpack: {type: 'array', value: [6553.6, 25.6, 0.1, 10000], compare: false},
476
+ colorReliefSubLayerProps: {type: 'object', value: null, compare: false}
477
+ };
478
+
479
+ declare state: DemTileLayer<ColorReliefTileLayerProps>['state'] & {
480
+ colorRamp?: ColorRampTexture & {key: string; device: Device};
481
+ };
482
+
483
+ updateState(params: UpdateParameters<this>): void {
484
+ super.updateState(params);
485
+ const {colorRamp} = this.state;
486
+ if (colorRamp && colorRamp.key !== this.getColorRampKey()) {
487
+ // The tiles take the new ramp.
488
+ this.state.tileLayers?.clear();
489
+ }
490
+ }
491
+
492
+ finalizeState(): void {
493
+ super.finalizeState();
494
+ this.state.colorRamp?.texture.destroy();
495
+ this.state.colorRamp = undefined;
496
+ }
497
+
498
+ private getColorRampKey(): string {
499
+ const {colorReliefColor, colorReliefUnpack} = this.props;
500
+ return JSON.stringify([colorReliefColor, colorReliefUnpack]);
501
+ }
502
+
503
+ /** The texture of the ramp, created again when the ramp or its encoding changes. */
504
+ private getColorRampTexture(): ColorRampTexture {
505
+ const {device} = this.context;
506
+ const {colorReliefColor, colorReliefUnpack} = this.props;
507
+ const key = this.getColorRampKey();
508
+ const current = this.state.colorRamp;
509
+ if (current?.key === key && current.device === device) {
510
+ return current;
511
+ }
512
+ current?.texture.destroy();
513
+ // MapLibre allows as many stops as a texture is wide.
514
+ const ramp = createColorRamp(colorReliefColor, device.limits.maxTextureDimension2D);
515
+ const size = ramp.colorStops.length;
516
+ const texture = device.createTexture({
517
+ format: 'rgba8unorm',
518
+ width: size,
519
+ height: 2,
520
+ mipLevels: 1,
521
+ // The shader reads exact texels.
522
+ sampler: {minFilter: 'nearest', magFilter: 'nearest'}
523
+ });
524
+ texture.writeData(getColorRampTexels(ramp, colorReliefUnpack));
525
+ this.state.colorRamp = {texture, size, key, device};
526
+ return this.state.colorRamp;
527
+ }
528
+
529
+ renderSubLayers(props: any): Layer | null | LayersList {
530
+ const dem = props.data as DemTile | null;
531
+ const tile = props.tile as DemTileHeader;
532
+ if (!dem || typeof ImageData === 'undefined') {
533
+ return null;
534
+ }
535
+ const {getNeighbor, key} = this.getDemNeighbors(tile);
536
+ // Kept with the decoded tile, so the source's color-relief layers prepare it once.
537
+ let prepared = preparedTextures.get(dem);
538
+ if (prepared?.key !== key) {
539
+ const size = dem.dim + 2;
540
+ prepared = {key, image: new ImageData(prepareColorReliefTexture(dem, getNeighbor), size, size)};
541
+ preparedTextures.set(dem, prepared);
542
+ }
543
+
544
+ const {west, south, east, north} = tile.bbox as {
545
+ west: number;
546
+ south: number;
547
+ east: number;
548
+ north: number;
549
+ };
550
+ const {colorReliefOpacity, colorReliefSubLayerProps} = this.props;
551
+ const textureParameters = colorReliefSubLayerProps?.textureParameters as
552
+ | {magFilter?: string}
553
+ | undefined;
554
+ return new ColorReliefBitmapLayer({
555
+ ...props,
556
+ ...colorReliefSubLayerProps,
557
+ // A texture keeps the filter it was created with, so a filter change needs a new layer.
558
+ id: textureParameters?.magFilter === 'nearest' ? `${props.id}-nearest` : props.id,
559
+ parameters: {
560
+ ...(colorReliefSubLayerProps?.parameters as object),
561
+ ...PREMULTIPLIED_BLEND_PARAMETERS
562
+ },
563
+ data: null,
564
+ // Positions in the tile are Web Mercator, also on a globe.
565
+ _imageCoordinateSystem: 'cartesian',
566
+ image: prepared.image,
567
+ bounds: [west, south, east, north],
568
+ colorRampTexture: this.getColorRampTexture(),
569
+ colorReliefOpacity
570
+ } as any);
571
+ }
572
+ }