-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Expand file tree
/
Copy pathterrain-layer.ts
More file actions
472 lines (420 loc) · 13.4 KB
/
Copy pathterrain-layer.ts
File metadata and controls
472 lines (420 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
// deck.gl
// SPDX-License-Identifier: MIT
// Copyright (c) vis.gl contributors
import {
Color,
CompositeLayer,
CompositeLayerProps,
DefaultProps,
Layer,
LayersList,
log,
Material,
TextureSource,
UpdateParameters
} from '@deck.gl/core';
import {SimpleMeshLayer} from '@deck.gl/mesh-layers';
import {COORDINATE_SYSTEM} from '@deck.gl/core';
import type {Mesh} from '@loaders.gl/schema';
import {TerrainWorkerLoader} from '@loaders.gl/terrain';
import {
MAX_LATITUDE as MAX_WEB_MERCATOR_LATITUDE,
lngLatToWorld,
worldToLngLat
} from '@math.gl/web-mercator';
import TileLayer, {TileLayerProps} from '../tile-layer/tile-layer';
import type {
Bounds,
GeoBoundingBox,
TileBoundingBox,
TileLoadProps,
ZRange
} from '../tileset-2d/index';
import {Tile2DHeader, urlType, getURLFromTemplate, URLTemplate} from '../tileset-2d/index';
const DUMMY_DATA = [1];
const TILE_OVERLAP_PIXELS = 1;
const MIN_TERRAIN_MESH_MAX_ERROR = 1;
const MAX_LATITUDE = 90;
const MAX_LONGITUDE = 180;
const defaultProps: DefaultProps<TerrainLayerProps> = {
...TileLayer.defaultProps,
// Image url that encodes height data
elevationData: urlType,
// Image url to use as texture
texture: {...urlType, optional: true},
// Martini error tolerance in meters, smaller number -> more detailed mesh
meshMaxError: {type: 'number', value: 4.0},
// Bounding box of the terrain image, [minX, minY, maxX, maxY] in world coordinates
bounds: {type: 'array', value: null, optional: true, compare: true},
// Color to use if texture is unavailable
color: {type: 'color', value: [255, 255, 255]},
// Object to decode height data, from (r, g, b) to height in meters
elevationDecoder: {
type: 'object',
value: {
rScaler: 1,
gScaler: 0,
bScaler: 0,
offset: 0
}
},
// Supply url to local terrain worker bundle. Only required if running offline and cannot access CDN.
workerUrl: '',
// Same as SimpleMeshLayer wireframe
wireframe: false,
material: true,
loaders: [TerrainWorkerLoader]
};
// Turns array of templates into a single string to work around shallow change
function urlTemplateToUpdateTrigger(template: URLTemplate): string {
if (Array.isArray(template)) {
return template.join(';');
}
return template || '';
}
function getOverlappedBounds(bounds: Bounds, tileSize: number, clampLngLat: boolean): Bounds {
const xPad = ((bounds[2] - bounds[0]) / tileSize) * TILE_OVERLAP_PIXELS;
const yPad = ((bounds[3] - bounds[1]) / tileSize) * TILE_OVERLAP_PIXELS;
const overlappedBounds: Bounds = [
bounds[0] - xPad,
bounds[1] - yPad,
bounds[2] + xPad,
bounds[3] + yPad
];
if (!clampLngLat) {
return overlappedBounds;
}
return [
Math.max(overlappedBounds[0], -MAX_LONGITUDE),
Math.max(overlappedBounds[1], -MAX_LATITUDE),
Math.min(overlappedBounds[2], MAX_LONGITUDE),
Math.min(overlappedBounds[3], MAX_LATITUDE)
];
}
function getEffectiveMeshMaxError(meshMaxError: number): number {
if (!Number.isFinite(meshMaxError) || meshMaxError <= 0) {
return MIN_TERRAIN_MESH_MAX_ERROR;
}
return Math.max(meshMaxError, MIN_TERRAIN_MESH_MAX_ERROR);
}
type ElevationDecoder = {rScaler: number; gScaler: number; bScaler: number; offset: number};
type TerrainLoadProps = {
bounds: Bounds;
elevationData: string | null;
elevationDecoder: ElevationDecoder;
meshMaxError: number;
remapToWebMercatorTile?: boolean;
signal?: AbortSignal;
};
type MeshAndTexture = [Mesh | null, TextureSource | null];
type MeshBoundingBox = [min: number[], max: number[]];
type MeshWithBoundingBox = Mesh & {
header?: {
boundingBox?: MeshBoundingBox;
};
};
/** All properties supported by TerrainLayer */
export type TerrainLayerProps = _TerrainLayerProps &
TileLayerProps<MeshAndTexture> &
CompositeLayerProps;
/** Props added by the TerrainLayer */
type _TerrainLayerProps = {
/** Image url that encodes height data. **/
elevationData: URLTemplate;
/** Image url to use as texture. **/
texture?: URLTemplate;
/** Martini error tolerance in meters, smaller number -> more detailed mesh. **/
meshMaxError?: number;
/** Bounding box of the terrain image, [minX, minY, maxX, maxY] in world coordinates. **/
bounds?: Bounds | null;
/** Color to use if texture is unavailable. **/
color?: Color;
/** Object to decode height data, from (r, g, b) to height in meters. **/
elevationDecoder?: ElevationDecoder;
/** Whether to render the mesh in wireframe mode. **/
wireframe?: boolean;
/** Material props for lighting effect. **/
material?: Material;
/**
* @deprecated Use `loadOptions.terrain.workerUrl` instead
*/
workerUrl?: string;
};
/** Render mesh surfaces from height map images. */
export default class TerrainLayer<ExtraPropsT extends {} = {}> extends CompositeLayer<
ExtraPropsT & Required<_TerrainLayerProps & Required<TileLayerProps<MeshAndTexture>>>
> {
static defaultProps = defaultProps;
static layerName = 'TerrainLayer';
state!: {
isTiled?: boolean;
terrain?: Mesh;
zRange?: ZRange | null;
};
updateState({props, oldProps}: UpdateParameters<this>): void {
const elevationDataChanged = props.elevationData !== oldProps.elevationData;
if (elevationDataChanged) {
const {elevationData} = props;
const isTiled =
elevationData && (Array.isArray(elevationData) || isTileSetURL(elevationData));
this.setState({isTiled});
}
// Reloading for single terrain mesh
const shouldReload =
elevationDataChanged ||
props.meshMaxError !== oldProps.meshMaxError ||
props.elevationDecoder !== oldProps.elevationDecoder ||
props.bounds !== oldProps.bounds;
if (!this.state.isTiled && shouldReload) {
// When state.isTiled, elevationData cannot be an array
const terrain = this.loadTerrain(props as TerrainLoadProps);
this.setState({terrain});
}
// TODO - remove in v9
// @ts-ignore
if (props.workerUrl) {
log.removed('workerUrl', 'loadOptions.terrain.workerUrl')();
}
}
loadTerrain({
elevationData,
bounds,
elevationDecoder,
meshMaxError,
remapToWebMercatorTile,
signal
}: TerrainLoadProps): Promise<Mesh> | null {
if (!elevationData) {
return null;
}
const effectiveMeshMaxError = getEffectiveMeshMaxError(meshMaxError);
let loadOptions = this.getLoadOptions();
loadOptions = {
...loadOptions,
terrain: {
skirtHeight: this.state.isTiled ? effectiveMeshMaxError * 2 : 0,
...loadOptions?.terrain,
bounds,
meshMaxError: effectiveMeshMaxError,
elevationDecoder
}
};
const {fetch} = this.props;
const terrain = fetch(elevationData, {
propName: 'elevationData',
layer: this,
loadOptions,
signal
});
return remapToWebMercatorTile
? terrain.then(mesh => (mesh ? remapMeshToWebMercatorTile(mesh, bounds) : mesh))
: terrain;
}
getTiledTerrainData(tile: TileLoadProps): Promise<MeshAndTexture> {
const {elevationData, fetch, texture, elevationDecoder, meshMaxError} = this.props;
const {viewport} = this.context;
const dataUrl = getURLFromTemplate(elevationData, tile);
const textureUrl = texture && getURLFromTemplate(texture, tile);
const {signal} = tile;
let bottomLeft = [0, 0] as [number, number];
let topRight = [0, 0] as [number, number];
if (viewport.isGeospatial) {
const bbox = tile.bbox as GeoBoundingBox;
bottomLeft = viewport.projectFlat([bbox.west, bbox.south]);
topRight = viewport.projectFlat([bbox.east, bbox.north]);
} else {
const bbox = tile.bbox as Exclude<TileBoundingBox, GeoBoundingBox>;
bottomLeft = [bbox.left, bbox.bottom];
topRight = [bbox.right, bbox.top];
}
const bounds: Bounds = [bottomLeft[0], bottomLeft[1], topRight[0], topRight[1]];
const isGlobe = Boolean(viewport.resolution && viewport.resolution > 0);
const overlappedBounds = getOverlappedBounds(bounds, this.props.tileSize, isGlobe);
const terrain =
this.loadTerrain({
elevationData: dataUrl,
bounds: overlappedBounds,
elevationDecoder,
meshMaxError,
remapToWebMercatorTile: isGlobe,
signal
}) ?? Promise.resolve(null);
const surface = textureUrl
? // If surface image fails to load, the tile should still be displayed
fetch(textureUrl, {propName: 'texture', layer: this, loaders: [], signal}).catch(_ => null)
: Promise.resolve(null);
return Promise.all([terrain, surface]);
}
renderSubLayers(
props: TileLayerProps<MeshAndTexture> & {
id: string;
data: MeshAndTexture;
tile: Tile2DHeader<MeshAndTexture>;
}
) {
const SubLayerClass = this.getSubLayerClass('mesh', SimpleMeshLayer);
const {color, wireframe, material} = this.props;
const {data} = props;
if (!data) {
return null;
}
const [mesh, texture] = data;
const {viewport} = this.context;
// Bounds are baked with projectFlat. In GlobeView projectFlat is identity,
// so tiled terrain meshes are in lng/lat degrees instead of common-space
// web-mercator units.
const isGlobe = Boolean(viewport.resolution && viewport.resolution > 0);
const boundingBox = (mesh as MeshWithBoundingBox | null)?.header?.boundingBox;
const hasLngLatBounds =
boundingBox &&
boundingBox.every(
([x, y]) =>
x >= -MAX_LONGITUDE && x <= MAX_LONGITUDE && y >= -MAX_LATITUDE && y <= MAX_LATITUDE
);
const coordinateSystem =
isGlobe && hasLngLatBounds ? COORDINATE_SYSTEM.LNGLAT : COORDINATE_SYSTEM.CARTESIAN;
return new SubLayerClass(props, {
data: DUMMY_DATA,
mesh,
texture,
_instanced: false,
coordinateSystem,
getPosition: d => [0, 0, 0],
getColor: color,
wireframe,
material
});
}
// Update zRange of viewport
onViewportLoad(tiles?: Tile2DHeader<MeshAndTexture>[]): void {
if (!tiles) {
return;
}
const {zRange} = this.state;
const ranges = tiles
.map(tile => tile.content)
.flatMap(arr => {
const bounds = arr?.[0]?.header?.boundingBox;
return bounds ? [bounds.map(bound => bound[2])] : [];
});
if (ranges.length === 0) {
return;
}
const minZ = Math.min(...ranges.map(x => x[0]));
const maxZ = Math.max(...ranges.map(x => x[1]));
if (!zRange || minZ < zRange[0] || maxZ > zRange[1]) {
this.setState({zRange: [minZ, maxZ]});
}
}
renderLayers(): Layer | null | LayersList {
const {
color,
material,
elevationData,
texture,
wireframe,
meshMaxError,
elevationDecoder,
tileSize,
maxZoom,
minZoom,
extent,
maxRequests,
onTileLoad,
onTileUnload,
onTileError,
maxCacheSize,
maxCacheByteSize,
refinementStrategy
} = this.props;
if (this.state.isTiled) {
return new TileLayer<MeshAndTexture>(
this.getSubLayerProps({
id: 'tiles'
}),
{
getTileData: this.getTiledTerrainData.bind(this),
renderSubLayers: this.renderSubLayers.bind(this),
updateTriggers: {
getTileData: {
elevationData: urlTemplateToUpdateTrigger(elevationData),
texture: urlTemplateToUpdateTrigger(texture),
meshMaxError,
elevationDecoder,
projectionMode: this.context.viewport.projectionMode
}
},
onViewportLoad: this.onViewportLoad.bind(this),
zRange: this.state.zRange || null,
tileSize,
maxZoom,
minZoom,
extent,
maxRequests,
onTileLoad,
onTileUnload,
onTileError,
maxCacheSize,
maxCacheByteSize,
refinementStrategy
}
);
}
if (!elevationData) {
return null;
}
const SubLayerClass = this.getSubLayerClass('mesh', SimpleMeshLayer);
return new SubLayerClass(
this.getSubLayerProps({
id: 'mesh'
}),
{
data: DUMMY_DATA,
mesh: this.state.terrain,
texture,
_instanced: false,
getPosition: d => [0, 0, 0],
getColor: color,
material,
wireframe
}
);
}
}
const isTileSetURL = (url: string): boolean =>
url.includes('{x}') && (url.includes('{y}') || url.includes('{-y}'));
function remapMeshToWebMercatorTile(mesh: Mesh, bounds: Bounds): Mesh {
const positionAttribute = mesh.attributes.POSITION;
const texCoordAttribute = mesh.attributes.TEXCOORD_0;
const positions = positionAttribute?.value;
const texCoords = texCoordAttribute?.value;
if (!positions || !texCoords) {
return mesh;
}
const [, south, , north] = bounds;
const northY = lngLatToMercatorWorldY(north);
const southY = lngLatToMercatorWorldY(south);
const remappedPositions = new Float32Array(positions);
for (let i = 0; i < texCoords.length / 2; i++) {
const v = texCoords[i * 2 + 1];
const mercatorY = northY + (southY - northY) * v;
remappedPositions[i * 3 + 1] = worldToLngLat([0, mercatorY])[1];
}
return {
...mesh,
attributes: {
...mesh.attributes,
POSITION: {
...positionAttribute,
value: remappedPositions
}
}
};
}
function lngLatToMercatorWorldY(latitude: number): number {
const clampedLatitude = Math.max(
-MAX_WEB_MERCATOR_LATITUDE,
Math.min(MAX_WEB_MERCATOR_LATITUDE, latitude)
);
return lngLatToWorld([0, clampedLatitude])[1];
}