@math.gl/geospatial 5.0.0-beta.2 → 5.0.0-beta.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 (99) hide show
  1. package/dist/index.cjs +374 -0
  2. package/dist/index.cjs.map +3 -3
  3. package/dist/index.d.ts +12 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +7 -0
  6. package/dist/index.js.map +1 -1
  7. package/dist/tasks/definitions.d.ts +90 -0
  8. package/dist/tasks/definitions.d.ts.map +1 -0
  9. package/dist/tasks/definitions.js +54 -0
  10. package/dist/tasks/definitions.js.map +1 -0
  11. package/dist/{workers → tasks}/index.cjs +158 -122
  12. package/dist/tasks/index.cjs.map +6 -0
  13. package/dist/tasks/index.d.ts +12 -0
  14. package/dist/tasks/index.d.ts.map +1 -0
  15. package/dist/tasks/index.js +30 -0
  16. package/dist/tasks/index.js.map +1 -0
  17. package/dist/{workers → tasks}/map-worker.d.ts.map +1 -1
  18. package/dist/tasks/map-worker.js +7 -0
  19. package/dist/tasks/map-worker.js.map +1 -0
  20. package/dist/{workers → tasks}/operations.d.ts +6 -4
  21. package/dist/tasks/operations.d.ts.map +1 -0
  22. package/dist/{workers → tasks}/operations.js +3 -5
  23. package/dist/tasks/operations.js.map +1 -0
  24. package/dist/tasks/projection-worker.d.ts.map +1 -0
  25. package/dist/tasks/projection-worker.js +7 -0
  26. package/dist/tasks/projection-worker.js.map +1 -0
  27. package/dist/terrain/filtered-pyramid.d.ts +22 -0
  28. package/dist/terrain/filtered-pyramid.d.ts.map +1 -0
  29. package/dist/terrain/filtered-pyramid.js +71 -0
  30. package/dist/terrain/filtered-pyramid.js.map +1 -0
  31. package/dist/terrain/index.cjs +375 -1
  32. package/dist/terrain/index.cjs.map +2 -2
  33. package/dist/terrain/index.d.ts +12 -0
  34. package/dist/terrain/index.d.ts.map +1 -1
  35. package/dist/terrain/index.js +7 -0
  36. package/dist/terrain/index.js.map +1 -1
  37. package/dist/terrain/profile-horizon.d.ts +20 -0
  38. package/dist/terrain/profile-horizon.d.ts.map +1 -0
  39. package/dist/terrain/profile-horizon.js +69 -0
  40. package/dist/terrain/profile-horizon.js.map +1 -0
  41. package/dist/terrain/profile-slope.d.ts +3 -0
  42. package/dist/terrain/profile-slope.d.ts.map +1 -0
  43. package/dist/terrain/profile-slope.js +35 -0
  44. package/dist/terrain/profile-slope.js.map +1 -0
  45. package/dist/terrain/profile-viewshed.d.ts +17 -0
  46. package/dist/terrain/profile-viewshed.d.ts.map +1 -0
  47. package/dist/terrain/profile-viewshed.js +51 -0
  48. package/dist/terrain/profile-viewshed.js.map +1 -0
  49. package/dist/terrain/profile-visibility.d.ts +21 -0
  50. package/dist/terrain/profile-visibility.d.ts.map +1 -0
  51. package/dist/terrain/profile-visibility.js +61 -0
  52. package/dist/terrain/profile-visibility.js.map +1 -0
  53. package/dist/terrain/vertex-halo-invalidation.d.ts +16 -0
  54. package/dist/terrain/vertex-halo-invalidation.d.ts.map +1 -0
  55. package/dist/terrain/vertex-halo-invalidation.js +50 -0
  56. package/dist/terrain/vertex-halo-invalidation.js.map +1 -0
  57. package/dist/terrain/vertex-halo-update.d.ts +18 -0
  58. package/dist/terrain/vertex-halo-update.d.ts.map +1 -0
  59. package/dist/terrain/vertex-halo-update.js +76 -0
  60. package/dist/terrain/vertex-halo-update.js.map +1 -0
  61. package/dist/terrain/vertex-halos.d.ts +26 -0
  62. package/dist/terrain/vertex-halos.d.ts.map +1 -0
  63. package/dist/terrain/vertex-halos.js +80 -0
  64. package/dist/terrain/vertex-halos.js.map +1 -0
  65. package/package.json +10 -15
  66. package/src/index.ts +12 -0
  67. package/src/tasks/definitions.ts +89 -0
  68. package/src/tasks/index.ts +39 -0
  69. package/src/tasks/map-worker.ts +6 -0
  70. package/src/{workers → tasks}/operations.ts +11 -7
  71. package/src/tasks/projection-worker.ts +6 -0
  72. package/src/terrain/filtered-pyramid.ts +95 -0
  73. package/src/terrain/index.ts +12 -0
  74. package/src/terrain/profile-horizon.ts +86 -0
  75. package/src/terrain/profile-slope.ts +32 -0
  76. package/src/terrain/profile-viewshed.ts +57 -0
  77. package/src/terrain/profile-visibility.ts +81 -0
  78. package/src/terrain/vertex-halo-invalidation.ts +57 -0
  79. package/src/terrain/vertex-halo-update.ts +91 -0
  80. package/src/terrain/vertex-halos.ts +101 -0
  81. package/dist/workers/index.cjs.map +0 -6
  82. package/dist/workers/index.d.ts +0 -12
  83. package/dist/workers/index.d.ts.map +0 -1
  84. package/dist/workers/index.js +0 -41
  85. package/dist/workers/index.js.map +0 -1
  86. package/dist/workers/map-worker.js +0 -7
  87. package/dist/workers/map-worker.js.map +0 -1
  88. package/dist/workers/operations.cjs +0 -21008
  89. package/dist/workers/operations.cjs.map +0 -6
  90. package/dist/workers/operations.d.ts.map +0 -1
  91. package/dist/workers/operations.js.map +0 -1
  92. package/dist/workers/projection-worker.d.ts.map +0 -1
  93. package/dist/workers/projection-worker.js +0 -7
  94. package/dist/workers/projection-worker.js.map +0 -1
  95. package/src/workers/index.ts +0 -59
  96. package/src/workers/map-worker.ts +0 -7
  97. package/src/workers/projection-worker.ts +0 -7
  98. /package/dist/{workers → tasks}/map-worker.d.ts +0 -0
  99. /package/dist/{workers → tasks}/projection-worker.d.ts +0 -0
package/package.json CHANGED
@@ -6,7 +6,7 @@
6
6
  "publishConfig": {
7
7
  "access": "public"
8
8
  },
9
- "version": "5.0.0-beta.2",
9
+ "version": "5.0.0-beta.3",
10
10
  "keywords": [
11
11
  "webgl",
12
12
  "javascript",
@@ -33,6 +33,11 @@
33
33
  "import": "./dist/index.js",
34
34
  "require": "./dist/index.cjs"
35
35
  },
36
+ "./tasks": {
37
+ "types": "./dist/tasks/index.d.ts",
38
+ "import": "./dist/tasks/index.js",
39
+ "require": "./dist/tasks/index.cjs"
40
+ },
36
41
  "./crs": {
37
42
  "types": "./dist/crs/index.d.ts",
38
43
  "import": "./dist/crs/index.js",
@@ -1015,16 +1020,6 @@
1015
1020
  "import": "./dist/terrain/index.js",
1016
1021
  "require": "./dist/terrain/index.cjs"
1017
1022
  },
1018
- "./workers": {
1019
- "types": "./dist/workers/index.d.ts",
1020
- "import": "./dist/workers/index.js",
1021
- "require": "./dist/workers/index.cjs"
1022
- },
1023
- "./workers/operations": {
1024
- "types": "./dist/workers/operations.d.ts",
1025
- "import": "./dist/workers/operations.js",
1026
- "require": "./dist/workers/operations.cjs"
1027
- },
1028
1023
  "./turf": {
1029
1024
  "types": "./dist/turf.d.ts",
1030
1025
  "import": "./dist/turf.js",
@@ -1046,9 +1041,9 @@
1046
1041
  ],
1047
1042
  "dependencies": {
1048
1043
  "@mapbox/martini": "0.2.0",
1049
- "@math.gl/core": "5.0.0-beta.2",
1050
- "@math.gl/geometry": "5.0.0-beta.2",
1051
- "@math.gl/web-mercator": "5.0.0-beta.2",
1044
+ "@math.gl/core": "5.0.0-beta.3",
1045
+ "@math.gl/geometry": "5.0.0-beta.3",
1046
+ "@math.gl/web-mercator": "5.0.0-beta.3",
1052
1047
  "polygon-clipping": "0.15.7"
1053
1048
  },
1054
1049
  "devDependencies": {
@@ -1060,5 +1055,5 @@
1060
1055
  "proj4": "2.22.0"
1061
1056
  },
1062
1057
  "sideEffects": false,
1063
- "gitHead": "f5c7bfdb4d9232e793237f08a86b513aedccc0a0"
1058
+ "gitHead": "5b20f706e26c9c5cfb252202e503fb98517a7350"
1064
1059
  }
package/src/index.ts CHANGED
@@ -377,8 +377,20 @@ export type {TerrainContourPaths, TerrainContourPathLimits} from './terrain/cont
377
377
  export {simplifyTerrainContourPaths} from './terrain/contour-simplify';
378
378
  export type {TerrainSimplifiedContourPaths} from './terrain/contour-simplify';
379
379
  export {measureTerrainProfile} from './terrain/profile-measure';
380
+ export {getTerrainProfileVisibility} from './terrain/profile-visibility';
381
+ export type {TerrainProfileVisibility} from './terrain/profile-visibility';
382
+ export {getTerrainProfileHorizon} from './terrain/profile-horizon';
383
+ export type {TerrainProfileHorizon, TerrainProfileHorizonOptions} from './terrain/profile-horizon';
384
+ export {getTerrainProfileViewshed, TerrainProfileViewStatus} from './terrain/profile-viewshed';
380
385
  export type {TerrainProfileMeasurements} from './terrain/profile-measure';
381
386
  export {reconcileTerrainVertexTiles} from './terrain/vertex-tiles';
387
+ export {createTerrainVertexTileHalos, TerrainVertexHaloStatus} from './terrain/vertex-halos';
388
+ export type {TerrainVertexHaloTile} from './terrain/vertex-halos';
389
+ export {getTerrainVertexHaloAffectedTiles} from './terrain/vertex-halo-invalidation';
390
+ export type {TerrainVertexTileAddress} from './terrain/vertex-halo-invalidation';
391
+ export {updateTerrainVertexTileHalos} from './terrain/vertex-halo-update';
392
+ export {createTerrainFilteredPyramid} from './terrain/filtered-pyramid';
393
+ export type {TerrainFilteredLevel} from './terrain/filtered-pyramid';
382
394
  export type {
383
395
  TerrainVertexTile,
384
396
  TerrainVertexTileOptions,
@@ -0,0 +1,89 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import type {Task} from '@math.gl/core/tasks';
5
+ import type {CreateProjectionOptions, Projection, ProjectionArray} from '../projection/types';
6
+ import type {MapDescription, PreparedMap} from '../discontinuous/map-engine';
7
+ export type ProjectCoordinatesTypes = {
8
+ initialization: {projection?: CreateProjectionOptions};
9
+ state: {projection?: Projection; key?: string; defaultOptions?: CreateProjectionOptions};
10
+ input: {
11
+ projection?: CreateProjectionOptions;
12
+ coordinates: ProjectionArray;
13
+ dimension?: number;
14
+ inverse?: boolean;
15
+ };
16
+ output: {coordinates: ProjectionArray};
17
+ options: {chunkSize?: number};
18
+ };
19
+
20
+ const processCoordinates: NonNullable<Task<ProjectCoordinatesTypes>['process']> = async (
21
+ input,
22
+ options,
23
+ context
24
+ ) => {
25
+ const projection = input.projection ?? context.state.defaultOptions;
26
+ if (!projection) throw new Error('Provide projection in the input or initializeTask');
27
+ await prepareProjection(context.state, projection);
28
+ const {projectBulk} = await import('./operations');
29
+ const coordinates = await projectBulk(
30
+ {...input, projection, chunkSize: options.chunkSize},
31
+ context,
32
+ context.state.projection
33
+ );
34
+ return {coordinates};
35
+ };
36
+
37
+ /** Reproject packed coordinates, retaining the prepared projection for each task lifetime. */
38
+ export const ProjectCoordinatesTask = {
39
+ id: 'project-coordinates',
40
+ async preload() {
41
+ await Promise.all([import('./operations'), import('../projection/lib/projection')]);
42
+ },
43
+ async initialize({projection}) {
44
+ const state: ProjectCoordinatesTypes['state'] = {defaultOptions: projection};
45
+ if (projection) await prepareProjection(state, projection);
46
+ return state;
47
+ },
48
+ destroy(state) {
49
+ state.projection = undefined;
50
+ state.defaultOptions = undefined;
51
+ state.key = undefined;
52
+ },
53
+ process: processCoordinates,
54
+ async *processInBatches(inputs, options, context) {
55
+ for await (const input of inputs) {
56
+ yield await processCoordinates(input, options, context);
57
+ }
58
+ }
59
+ } satisfies Task<ProjectCoordinatesTypes>;
60
+
61
+ export type PrepareMapTypes = {
62
+ input: {description: MapDescription};
63
+ output: {map: PreparedMap};
64
+ };
65
+
66
+ /** Build a portable map snapshot for MapEngine.fromPrepared without blocking the UI. */
67
+ export const PrepareMapTask = {
68
+ id: 'prepare-map',
69
+ async preload() {
70
+ await import('./operations');
71
+ },
72
+ async process({description}, _options, context) {
73
+ const {setupMap} = await import('./operations');
74
+ return {map: setupMap(description, context).toPrepared()};
75
+ }
76
+ } satisfies Task<PrepareMapTypes>;
77
+
78
+ async function prepareProjection(
79
+ state: ProjectCoordinatesTypes['state'],
80
+ options: CreateProjectionOptions
81
+ ): Promise<void> {
82
+ const key = JSON.stringify(options);
83
+ if (!state.projection || state.key !== key) {
84
+ const {FullProjectionEngine} = await import('../projection/lib/projection');
85
+ const projection = new FullProjectionEngine().createProjection(options);
86
+ state.projection = projection;
87
+ state.key = key;
88
+ }
89
+ }
@@ -0,0 +1,39 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import type {TaskWorker} from '@math.gl/core/tasks';
5
+ import {ProjectCoordinatesTask as projectionTask, PrepareMapTask as mapTask} from './definitions';
6
+ export type {ProjectCoordinatesTypes, PrepareMapTypes} from './definitions';
7
+ declare const __filename: string;
8
+
9
+ // Resolve compiled worker modules in both ESM and CommonJS package entries.
10
+ const isBrowser = !(globalThis as {process?: {versions?: {node?: string}}}).process?.versions?.node;
11
+ const path = typeof __filename === 'string' ? __filename.replace(/\\/g, '/') : '';
12
+ const moduleUrl = path
13
+ ? `file://${path.startsWith('/') ? '' : '/'}${encodeURI(path).replace(/#/g, '%23').replace(/\?/g, '%3F')}`
14
+ : import.meta.url;
15
+
16
+ /** Reproject coordinates with an automatic or explicitly retained worker. */
17
+ export const ProjectCoordinatesTask: typeof projectionTask & {worker: TaskWorker} = {
18
+ ...projectionTask,
19
+ worker: {
20
+ ...(!isBrowser
21
+ ? {url: /* @__PURE__ */ (() => new URL('./projection-worker.js', moduleUrl).href)()}
22
+ : {
23
+ create: () =>
24
+ new Worker(new URL('./projection-worker.js', import.meta.url), {type: 'module'})
25
+ }),
26
+ capabilities: {atomic: true, streaming: true}
27
+ }
28
+ };
29
+
30
+ /** Prepare a portable map snapshot in a worker. */
31
+ export const PrepareMapTask: typeof mapTask & {worker: TaskWorker} = {
32
+ ...mapTask,
33
+ worker: {
34
+ ...(!isBrowser
35
+ ? {url: /* @__PURE__ */ (() => new URL('./map-worker.js', moduleUrl).href)()}
36
+ : {create: () => new Worker(new URL('./map-worker.js', import.meta.url), {type: 'module'})}),
37
+ capabilities: {atomic: true, streaming: false}
38
+ }
39
+ };
@@ -0,0 +1,6 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import {initializeTaskWorker} from '@math.gl/core/tasks';
5
+ import {PrepareMapTask} from './definitions';
6
+ void initializeTaskWorker(PrepareMapTask);
@@ -2,8 +2,9 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
4
  import {MapEngine, type MapDescription, type MapEngineOptions} from '../discontinuous/map-engine';
5
- import type {CreateProjectionOptions, ProjectionArray} from '../projection/types';
6
- import type {WorkerContext} from '@math.gl/core/worker-utils';
5
+ import type {CreateProjectionOptions, ProjectionArray, Projection} from '../projection/types';
6
+ import type {TaskContext} from '@math.gl/core/tasks';
7
+ type OperationContext = Partial<Omit<TaskContext<unknown>, 'state'>>;
7
8
 
8
9
  export type BulkProjectionTask = {
9
10
  projection: CreateProjectionOptions;
@@ -16,7 +17,7 @@ export type BulkProjectionTask = {
16
17
  /** Setup callbacks belong in the worker and cannot be sent in a request. */
17
18
  export function setupMap(
18
19
  description: MapDescription,
19
- context: WorkerContext,
20
+ context: OperationContext,
20
21
  options?: MapEngineOptions
21
22
  ): MapEngine {
22
23
  context.reportProgress?.({phase: 'map-setup', completed: 0, total: 1, unit: 'tasks'});
@@ -29,7 +30,8 @@ export function setupMap(
29
30
  /** Process worker-owned storage in chunks. Failed jobs return no partial result. */
30
31
  export async function projectBulk(
31
32
  input: BulkProjectionTask,
32
- context: WorkerContext
33
+ context: OperationContext,
34
+ preparedProjection?: Projection
33
35
  ): Promise<ProjectionArray> {
34
36
  const {coordinates, dimension = 2, chunkSize = 4096} = input;
35
37
  if (
@@ -45,8 +47,11 @@ export async function projectBulk(
45
47
  'Expected ordinary floating-point buffers, complete records and positive chunk size'
46
48
  );
47
49
  context.reportProgress?.({phase: 'projection-setup', completed: 0, total: 1, unit: 'tasks'});
48
- const {FullProjectionEngine} = await import('../projection/lib/projection');
49
- const projection = new FullProjectionEngine().createProjection(input.projection);
50
+ const projection =
51
+ preparedProjection ??
52
+ new (await import('../projection/lib/projection')).FullProjectionEngine().createProjection(
53
+ input.projection
54
+ );
50
55
  context.reportProgress?.({phase: 'projection-setup', completed: 1, total: 1, unit: 'tasks'});
51
56
  const total = coordinates.length / dimension;
52
57
  context.reportProgress?.({phase: 'bulk-projection', completed: 0, total, unit: 'records'});
@@ -57,7 +62,6 @@ export async function projectBulk(
57
62
  const chunk = coordinates.subarray(start * dimension, end * dimension);
58
63
  if (input.inverse) projection.unprojectFlatSync(chunk, dimension);
59
64
  else projection.projectFlatSync(chunk, dimension);
60
- if (total <= 0x7fffffff) context.sharedState?.setProgress(end, total);
61
65
  context.reportProgress?.({phase: 'bulk-projection', completed: end, total, unit: 'records'});
62
66
  await new Promise(resolve => setTimeout(resolve, 0));
63
67
  }
@@ -0,0 +1,6 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+ import {initializeTaskWorker} from '@math.gl/core/tasks';
5
+ import {ProjectCoordinatesTask} from './definitions';
6
+ void initializeTaskWorker(ProjectCoordinatesTask);
@@ -0,0 +1,95 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ export type TerrainFilteredLevel = {
6
+ width: number;
7
+ height: number;
8
+ /** Mean of valid original samples, or zero when validCounts is zero. */
9
+ heights: Float64Array;
10
+ validCounts: Uint32Array;
11
+ /** Original sample count represented, including missing samples. */
12
+ sampleCounts: Uint32Array;
13
+ };
14
+
15
+ /** Box-filter a cell raster into a weighted pyramid. Odd edges retain their true
16
+ * source counts. Missing data is excluded from means but remains visible in counts.
17
+ * These averages are not conservative collision bounds or vertex-registered meshes.
18
+ */
19
+ export function createTerrainFilteredPyramid(
20
+ input: {
21
+ width: number;
22
+ height: number;
23
+ heights: Float32Array | Float64Array;
24
+ validity?: Uint8Array;
25
+ },
26
+ options: {maxSamples?: number} = {}
27
+ ): TerrainFilteredLevel[] {
28
+ const {width, height, heights, validity} = input;
29
+ const count = width * height;
30
+ const limit = options.maxSamples ?? 4_000_000;
31
+ if (
32
+ !Number.isSafeInteger(width) ||
33
+ width < 1 ||
34
+ !Number.isSafeInteger(height) ||
35
+ height < 1 ||
36
+ !Number.isSafeInteger(count) ||
37
+ count > 0xffffffff ||
38
+ !Number.isSafeInteger(limit) ||
39
+ limit < count ||
40
+ !(heights instanceof Float32Array || heights instanceof Float64Array) ||
41
+ heights.length !== count ||
42
+ (validity !== undefined && (!(validity instanceof Uint8Array) || validity.length !== count))
43
+ )
44
+ throw new Error('Invalid terrain filtered pyramid input or capacity');
45
+ const base: TerrainFilteredLevel = {
46
+ width,
47
+ height,
48
+ heights: new Float64Array(count),
49
+ validCounts: new Uint32Array(count),
50
+ sampleCounts: new Uint32Array(count).fill(1)
51
+ };
52
+ for (let i = 0; i < count; i++)
53
+ if ((!validity || validity[i] !== 0) && Number.isFinite(heights[i])) {
54
+ base.heights[i] = heights[i];
55
+ base.validCounts[i] = 1;
56
+ }
57
+ const levels = [base];
58
+ let source = base;
59
+ while (source.width > 1 || source.height > 1) {
60
+ const w = Math.ceil(source.width / 2),
61
+ h = Math.ceil(source.height / 2);
62
+ const next: TerrainFilteredLevel = {
63
+ width: w,
64
+ height: h,
65
+ heights: new Float64Array(w * h),
66
+ validCounts: new Uint32Array(w * h),
67
+ sampleCounts: new Uint32Array(w * h)
68
+ };
69
+ for (let y = 0; y < h; y++)
70
+ for (let x = 0; x < w; x++) {
71
+ const out = y * w + x;
72
+ for (let dy = 0; dy < 2; dy++)
73
+ for (let dx = 0; dx < 2; dx++) {
74
+ const sx = x * 2 + dx,
75
+ sy = y * 2 + dy;
76
+ if (sx >= source.width || sy >= source.height) continue;
77
+ const index = sy * source.width + sx;
78
+ const n = source.validCounts[index],
79
+ old = next.validCounts[out];
80
+ next.sampleCounts[out] += source.sampleCounts[index];
81
+ if (n) {
82
+ const total = old + n,
83
+ a = next.heights[out],
84
+ b = source.heights[index];
85
+ // Convex combination avoids overflow when values have opposite signs.
86
+ next.heights[out] = old ? a * (old / total) + b * (n / total) : b;
87
+ next.validCounts[out] = total;
88
+ }
89
+ }
90
+ }
91
+ levels.push(next);
92
+ source = next;
93
+ }
94
+ return levels;
95
+ }
@@ -71,8 +71,20 @@ export type {TerrainContourPaths, TerrainContourPathLimits} from './contour-path
71
71
  export {simplifyTerrainContourPaths} from './contour-simplify';
72
72
  export type {TerrainSimplifiedContourPaths} from './contour-simplify';
73
73
  export {measureTerrainProfile} from './profile-measure';
74
+ export {getTerrainProfileVisibility} from './profile-visibility';
75
+ export type {TerrainProfileVisibility} from './profile-visibility';
76
+ export {getTerrainProfileHorizon} from './profile-horizon';
77
+ export type {TerrainProfileHorizon, TerrainProfileHorizonOptions} from './profile-horizon';
78
+ export {getTerrainProfileViewshed, TerrainProfileViewStatus} from './profile-viewshed';
74
79
  export type {TerrainProfileMeasurements} from './profile-measure';
75
80
  export {reconcileTerrainVertexTiles} from './vertex-tiles';
81
+ export {createTerrainVertexTileHalos, TerrainVertexHaloStatus} from './vertex-halos';
82
+ export type {TerrainVertexHaloTile} from './vertex-halos';
83
+ export {getTerrainVertexHaloAffectedTiles} from './vertex-halo-invalidation';
84
+ export type {TerrainVertexTileAddress} from './vertex-halo-invalidation';
85
+ export {updateTerrainVertexTileHalos} from './vertex-halo-update';
86
+ export {createTerrainFilteredPyramid} from './filtered-pyramid';
87
+ export type {TerrainFilteredLevel} from './filtered-pyramid';
76
88
  export type {
77
89
  TerrainVertexTile,
78
90
  TerrainVertexTileOptions,
@@ -0,0 +1,86 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import type {TerrainProfile} from './profile';
6
+ import {TerrainSampleStatus} from './types';
7
+ import {compareTerrainSlopes} from './profile-slope';
8
+
9
+ /** Horizon of known samples. Missing coverage means the true horizon may be higher. */
10
+ export type TerrainProfileHorizon = {
11
+ angle: number | undefined;
12
+ sampleIndex: number | undefined;
13
+ missingSampleCount: number;
14
+ complete: boolean;
15
+ };
16
+
17
+ export type TerrainProfileHorizonOptions = {observerHeight: number; maxSamples?: number};
18
+
19
+ /** Calculate the maximum elevation angle in radians of a straight, sampled profile.
20
+ * The observer is at station zero, and its absolute height must be above known terrain
21
+ * there. Values describe a local Cartesian piecewise-linear profile, not unsampled
22
+ * terrain, curvature, refraction or a geographic path. Missing samples leave the
23
+ * maximum of known samples as a lower bound rather than a complete horizon.
24
+ */
25
+ export function getTerrainProfileHorizon(
26
+ profile: TerrainProfile,
27
+ options: TerrainProfileHorizonOptions
28
+ ): TerrainProfileHorizon {
29
+ const {distances, heights, statuses, length} = profile;
30
+ const count = distances.length;
31
+ const limit = options.maxSamples ?? 1_000_000;
32
+ if (
33
+ !(distances instanceof Float64Array) ||
34
+ !(heights instanceof Float64Array) ||
35
+ !(statuses instanceof Uint8Array) ||
36
+ count < 2 ||
37
+ heights.length !== count ||
38
+ statuses.length !== count ||
39
+ !Number.isSafeInteger(limit) ||
40
+ limit < count ||
41
+ !Number.isFinite(options.observerHeight) ||
42
+ !Number.isFinite(length) ||
43
+ length <= 0 ||
44
+ distances[0] !== 0 ||
45
+ distances[count - 1] !== length
46
+ )
47
+ throw new Error('Invalid terrain horizon profile or options');
48
+ let winningRise = 0;
49
+ let winningDistance = 1;
50
+ let sampleIndex: number | undefined;
51
+ let missingSampleCount = 0;
52
+ for (let i = 0; i < count; i++) {
53
+ const distance = distances[i];
54
+ const status = statuses[i];
55
+ if (!Number.isFinite(distance) || (i > 0 && distance <= distances[i - 1]))
56
+ throw new Error('Invalid terrain horizon stationing');
57
+ if (status > TerrainSampleStatus.NOT_RESIDENT)
58
+ throw new Error('Invalid terrain horizon status');
59
+ if (status !== TerrainSampleStatus.VALID) {
60
+ missingSampleCount++;
61
+ continue;
62
+ }
63
+ if (!Number.isFinite(heights[i])) throw new Error('Invalid terrain horizon height');
64
+ if (i === 0) {
65
+ if (options.observerHeight <= heights[i])
66
+ throw new Error('Terrain horizon observer must be above ground');
67
+ continue;
68
+ }
69
+ const delta = heights[i] - options.observerHeight;
70
+ if (!Number.isFinite(delta)) throw new Error('Terrain horizon arithmetic overflow');
71
+ if (
72
+ sampleIndex === undefined ||
73
+ compareTerrainSlopes(delta, distance, winningRise, winningDistance) > 0
74
+ ) {
75
+ winningRise = delta;
76
+ winningDistance = distance;
77
+ sampleIndex = i;
78
+ }
79
+ }
80
+ return {
81
+ angle: sampleIndex === undefined ? undefined : Math.atan2(winningRise, winningDistance),
82
+ sampleIndex,
83
+ missingSampleCount,
84
+ complete: missingSampleCount === 0
85
+ };
86
+ }
@@ -0,0 +1,32 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ /** Compare finite rises divided by positive distances, including overflow and rounded ties. */
6
+ export function compareTerrainSlopes(a: number, ad: number, b: number, bd: number): number {
7
+ const as = a / ad;
8
+ const bs = b / bd;
9
+ if (as < bs) return -1;
10
+ if (as > bs) return 1;
11
+ if (a === 0 || b === 0 || Math.sign(a) !== Math.sign(b)) return Math.sign(a) - Math.sign(b);
12
+ // Division can round distinct ratios to the same value, zero or infinity.
13
+ // Compare the exact products of their binary64 significands only on that path.
14
+ const bytes = new DataView(new ArrayBuffer(8));
15
+ const parts = (value: number): [bigint, number] => {
16
+ bytes.setFloat64(0, Math.abs(value));
17
+ const bits = bytes.getBigUint64(0);
18
+ const exponent = Number((bits >> 52n) & 0x7ffn);
19
+ const fraction = bits & 0xfffffffffffffn;
20
+ return exponent ? [fraction | 0x10000000000000n, exponent - 1075] : [fraction, -1074];
21
+ };
22
+ const [am, ae] = parts(a),
23
+ [bdm, bde] = parts(bd);
24
+ const [bm, be] = parts(b),
25
+ [adm, ade] = parts(ad);
26
+ let left = am * bdm;
27
+ let right = bm * adm;
28
+ const shift = ae + bde - be - ade;
29
+ if (shift > 0) left <<= BigInt(shift);
30
+ else if (shift < 0) right <<= BigInt(-shift);
31
+ return (left < right ? -1 : left > right ? 1 : 0) * Math.sign(a);
32
+ }
@@ -0,0 +1,57 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import type {TerrainProfile} from './profile';
6
+ import {TerrainSampleStatus} from './types';
7
+ import {getTerrainProfileHorizon, type TerrainProfileHorizonOptions} from './profile-horizon';
8
+ import {compareTerrainSlopes} from './profile-slope';
9
+
10
+ /** Sample classification for a single radial profile; station zero is the observer. */
11
+ export const TerrainProfileViewStatus = {
12
+ OBSERVER: 0,
13
+ VISIBLE: 1,
14
+ BLOCKED: 2,
15
+ UNKNOWN: 3,
16
+ MISSING: 4
17
+ } as const;
18
+
19
+ /** Classify each terrain sample against earlier samples on a straight radial profile.
20
+ * A previous sample on the ray blocks it. Missing earlier samples make otherwise
21
+ * visible targets unknown, but cannot undo a known obstruction. This is a sampled
22
+ * local profile, not an area viewshed or a guarantee about unsampled terrain.
23
+ */
24
+ export function getTerrainProfileViewshed(
25
+ profile: TerrainProfile,
26
+ options: TerrainProfileHorizonOptions
27
+ ): Uint8Array {
28
+ // Validate the whole profile before writing any output.
29
+ getTerrainProfileHorizon(profile, options);
30
+ const result = new Uint8Array(profile.distances.length);
31
+ let maxRise = 0;
32
+ let maxDistance = 1;
33
+ let hasHorizon = false;
34
+ let missingBefore = profile.statuses[0] !== TerrainSampleStatus.VALID;
35
+ for (let i = 1; i < result.length; i++) {
36
+ if (profile.statuses[i] !== TerrainSampleStatus.VALID) {
37
+ result[i] = TerrainProfileViewStatus.MISSING;
38
+ missingBefore = true;
39
+ continue;
40
+ }
41
+ const rise = profile.heights[i] - options.observerHeight;
42
+ const distance = profile.distances[i];
43
+ const comparison = hasHorizon ? compareTerrainSlopes(rise, distance, maxRise, maxDistance) : 1;
44
+ result[i] =
45
+ comparison <= 0
46
+ ? TerrainProfileViewStatus.BLOCKED
47
+ : missingBefore
48
+ ? TerrainProfileViewStatus.UNKNOWN
49
+ : TerrainProfileViewStatus.VISIBLE;
50
+ if (comparison > 0) {
51
+ maxRise = rise;
52
+ maxDistance = distance;
53
+ hasHorizon = true;
54
+ }
55
+ }
56
+ return result;
57
+ }
@@ -0,0 +1,81 @@
1
+ // math.gl
2
+ // SPDX-License-Identifier: MIT
3
+ // SPDX-FileCopyrightText: Copyright (c) vis.gl contributors
4
+
5
+ import type {TerrainProfile} from './profile';
6
+ import {TerrainSampleStatus} from './types';
7
+
8
+ export type TerrainProfileVisibility = {
9
+ /** A sample blocks the line, all samples are clear, or coverage is incomplete. */
10
+ status: 'blocked' | 'clear' | 'unknown';
11
+ /** First observed blocking sample; missing samples can hide an earlier obstruction. */
12
+ firstBlockingSample: number | undefined;
13
+ missingSampleCount: number;
14
+ /** Smallest sampled vertical clearance, including endpoints. */
15
+ minimumClearance: number | undefined;
16
+ };
17
+
18
+ /** Compare absolute observer and target heights against a sampled, straight horizontal profile.
19
+ * A touching sample blocks the line. A clear result applies only to the sampled
20
+ * piecewise-linear profile; it does not certify unsampled terrain, Earth curvature,
21
+ * refraction, or a geographic/geodesic path. Heights and distances must use compatible units.
22
+ */
23
+ export function getTerrainProfileVisibility(
24
+ profile: TerrainProfile,
25
+ options: {
26
+ observerHeight: number;
27
+ targetHeight: number;
28
+ maxSamples?: number;
29
+ }
30
+ ): TerrainProfileVisibility {
31
+ const {observerHeight, targetHeight} = options;
32
+ const limit = options.maxSamples ?? 1_000_000;
33
+ const {distances, heights, statuses, length} = profile;
34
+ const count = distances.length;
35
+ if (
36
+ !(distances instanceof Float64Array) ||
37
+ !(heights instanceof Float64Array) ||
38
+ !(statuses instanceof Uint8Array) ||
39
+ count < 2 ||
40
+ heights.length !== count ||
41
+ statuses.length !== count ||
42
+ !Number.isSafeInteger(limit) ||
43
+ limit < count ||
44
+ !Number.isFinite(observerHeight) ||
45
+ !Number.isFinite(targetHeight) ||
46
+ !Number.isFinite(length) ||
47
+ length <= 0 ||
48
+ distances[0] !== 0 ||
49
+ distances[count - 1] !== length
50
+ )
51
+ throw new Error('Invalid terrain visibility profile or options');
52
+ let missingSampleCount = 0;
53
+ let firstBlockingSample: number | undefined;
54
+ let minimumClearance = Infinity;
55
+ for (let i = 0; i < count; i++) {
56
+ const distance = distances[i],
57
+ status = statuses[i];
58
+ if (!Number.isFinite(distance) || (i > 0 && distance <= distances[i - 1]))
59
+ throw new Error('Invalid terrain visibility stationing');
60
+ if (status > TerrainSampleStatus.NOT_RESIDENT)
61
+ throw new Error('Invalid terrain visibility status');
62
+ if (status !== TerrainSampleStatus.VALID) {
63
+ missingSampleCount++;
64
+ continue;
65
+ }
66
+ if (!Number.isFinite(heights[i])) throw new Error('Invalid terrain visibility height');
67
+ const fraction = distance / length;
68
+ const lineHeight = observerHeight * (1 - fraction) + targetHeight * fraction;
69
+ const clearance = lineHeight - heights[i];
70
+ if (!Number.isFinite(clearance)) throw new Error('Terrain visibility arithmetic overflow');
71
+ minimumClearance = Math.min(minimumClearance, clearance);
72
+ if (clearance <= 0 && firstBlockingSample === undefined) firstBlockingSample = i;
73
+ }
74
+ return {
75
+ status:
76
+ firstBlockingSample !== undefined ? 'blocked' : missingSampleCount ? 'unknown' : 'clear',
77
+ firstBlockingSample,
78
+ missingSampleCount,
79
+ minimumClearance: minimumClearance === Infinity ? undefined : minimumClearance
80
+ };
81
+ }