@math.gl/web-mercator 3.5.7 → 3.6.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 (92) hide show
  1. package/dist/assert.d.ts +2 -0
  2. package/dist/assert.d.ts.map +1 -0
  3. package/dist/assert.js +8 -0
  4. package/dist/es5/assert.js.map +1 -1
  5. package/dist/es5/fit-bounds.js +27 -24
  6. package/dist/es5/fit-bounds.js.map +1 -1
  7. package/dist/es5/fly-to-viewport.js +23 -16
  8. package/dist/es5/fly-to-viewport.js.map +1 -1
  9. package/dist/es5/get-bounds.js +1 -1
  10. package/dist/es5/get-bounds.js.map +1 -1
  11. package/dist/es5/index.js.map +1 -1
  12. package/dist/es5/math-utils.js +3 -9
  13. package/dist/es5/math-utils.js.map +1 -1
  14. package/dist/es5/normalize-viewport-props.js +10 -10
  15. package/dist/es5/normalize-viewport-props.js.map +1 -1
  16. package/dist/es5/web-mercator-utils.js +44 -60
  17. package/dist/es5/web-mercator-utils.js.map +1 -1
  18. package/dist/es5/web-mercator-viewport.js +69 -51
  19. package/dist/es5/web-mercator-viewport.js.map +1 -1
  20. package/dist/esm/assert.js.map +1 -1
  21. package/dist/esm/fit-bounds.js +24 -22
  22. package/dist/esm/fit-bounds.js.map +1 -1
  23. package/dist/esm/fly-to-viewport.js +13 -9
  24. package/dist/esm/fly-to-viewport.js.map +1 -1
  25. package/dist/esm/get-bounds.js +1 -1
  26. package/dist/esm/get-bounds.js.map +1 -1
  27. package/dist/esm/index.js.map +1 -1
  28. package/dist/esm/math-utils.js +3 -3
  29. package/dist/esm/math-utils.js.map +1 -1
  30. package/dist/esm/normalize-viewport-props.js +13 -9
  31. package/dist/esm/normalize-viewport-props.js.map +1 -1
  32. package/dist/esm/web-mercator-utils.js +46 -52
  33. package/dist/esm/web-mercator-utils.js.map +1 -1
  34. package/dist/esm/web-mercator-viewport.js +76 -34
  35. package/dist/esm/web-mercator-viewport.js.map +1 -1
  36. package/dist/fit-bounds.d.ts +50 -0
  37. package/dist/fit-bounds.d.ts.map +1 -0
  38. package/dist/fit-bounds.js +63 -0
  39. package/dist/fly-to-viewport.d.ts +19 -0
  40. package/dist/fly-to-viewport.d.ts.map +1 -0
  41. package/dist/fly-to-viewport.js +87 -0
  42. package/dist/get-bounds.d.ts +3 -0
  43. package/dist/get-bounds.d.ts.map +1 -0
  44. package/dist/get-bounds.js +51 -0
  45. package/dist/index.d.ts +11 -0
  46. package/dist/index.d.ts.map +1 -0
  47. package/dist/index.js +8 -0
  48. package/dist/math-utils.d.ts +7 -0
  49. package/dist/math-utils.d.ts.map +1 -0
  50. package/dist/math-utils.js +26 -0
  51. package/dist/normalize-viewport-props.d.ts +16 -0
  52. package/dist/normalize-viewport-props.d.ts.map +1 -0
  53. package/dist/normalize-viewport-props.js +41 -0
  54. package/dist/{es5/web-mercator-utils.d.ts → web-mercator-utils.d.ts} +78 -95
  55. package/dist/web-mercator-utils.d.ts.map +1 -0
  56. package/dist/web-mercator-utils.js +290 -0
  57. package/dist/web-mercator-viewport.d.ts +182 -0
  58. package/dist/web-mercator-viewport.d.ts.map +1 -0
  59. package/dist/web-mercator-viewport.js +281 -0
  60. package/package.json +4 -4
  61. package/src/{assert.js → assert.ts} +1 -1
  62. package/src/fit-bounds.ts +127 -0
  63. package/src/{fly-to-viewport.js → fly-to-viewport.ts} +52 -14
  64. package/src/{get-bounds.js → get-bounds.ts} +7 -5
  65. package/src/{index.js → index.ts} +4 -0
  66. package/src/math-utils.ts +32 -0
  67. package/src/{normalize-viewport-props.js → normalize-viewport-props.ts} +19 -10
  68. package/src/{web-mercator-utils.js → web-mercator-utils.ts} +184 -76
  69. package/src/web-mercator-viewport.ts +415 -0
  70. package/dist/es5/fit-bounds.d.ts +0 -64
  71. package/dist/es5/fly-to-viewport.d.ts +0 -31
  72. package/dist/es5/get-bounds.d.ts +0 -3
  73. package/dist/es5/index.d.ts +0 -24
  74. package/dist/es5/normalize-viewport-props.d.ts +0 -16
  75. package/dist/es5/web-mercator-viewport.d.ts +0 -187
  76. package/dist/esm/fit-bounds.d.ts +0 -64
  77. package/dist/esm/fly-to-viewport.d.ts +0 -31
  78. package/dist/esm/get-bounds.d.ts +0 -3
  79. package/dist/esm/index.d.ts +0 -24
  80. package/dist/esm/normalize-viewport-props.d.ts +0 -16
  81. package/dist/esm/web-mercator-utils.d.ts +0 -190
  82. package/dist/esm/web-mercator-viewport.d.ts +0 -187
  83. package/src/fit-bounds.d.ts +0 -64
  84. package/src/fit-bounds.js +0 -76
  85. package/src/fly-to-viewport.d.ts +0 -31
  86. package/src/get-bounds.d.ts +0 -3
  87. package/src/index.d.ts +0 -24
  88. package/src/math-utils.js +0 -32
  89. package/src/normalize-viewport-props.d.ts +0 -16
  90. package/src/web-mercator-utils.d.ts +0 -190
  91. package/src/web-mercator-viewport.d.ts +0 -187
  92. package/src/web-mercator-viewport.js +0 -262
@@ -2,37 +2,55 @@ import {lerp} from './math-utils';
2
2
  import {scaleToZoom, zoomToScale, lngLatToWorld, worldToLngLat} from './web-mercator-utils';
3
3
  import * as vec2 from 'gl-matrix/vec2';
4
4
 
5
+ import type {ViewportProps} from './normalize-viewport-props';
6
+
5
7
  const EPSILON = 0.01;
6
- const VIEWPORT_TRANSITION_PROPS = ['longitude', 'latitude', 'zoom'];
8
+ const VIEWPORT_TRANSITION_PROPS = ['longitude', 'latitude', 'zoom'] as const;
7
9
  const DEFAULT_OPTS = {
8
10
  curve: 1.414,
9
11
  speed: 1.2
10
12
  // screenSpeed and maxDuration are used only if specified
11
13
  };
12
14
 
15
+ export type FlytoTransitionOptions = {
16
+ curve?: number;
17
+ speed?: number;
18
+ screenSpeed?: number;
19
+ maxDuration?: number;
20
+ };
21
+
13
22
  /**
14
23
  * mapbox-gl-js flyTo : https://www.mapbox.com/mapbox-gl-js/api/#map#flyto.
15
24
  * It implements “Smooth and efficient zooming and panning.” algorithm by
16
25
  * "Jarke J. van Wijk and Wim A.A. Nuij"
17
26
  */
18
- export default function flyToViewport(startProps, endProps, t, opts = {}) {
27
+ export default function flyToViewport(
28
+ startProps: ViewportProps,
29
+ endProps: ViewportProps,
30
+ t: number,
31
+ options?: FlytoTransitionOptions
32
+ ): {
33
+ longitude: number;
34
+ latitude: number;
35
+ zoom: number;
36
+ } {
19
37
  // Equations from above paper are referred where needed.
20
38
 
21
- const viewport = {};
22
-
23
39
  const {startZoom, startCenterXY, uDelta, w0, u1, S, rho, rho2, r0} = getFlyToTransitionParams(
24
40
  startProps,
25
41
  endProps,
26
- opts
42
+ options
27
43
  );
28
44
 
29
45
  // If change in center is too small, do linear interpolaiton.
30
46
  if (u1 < EPSILON) {
47
+ const viewport = {};
31
48
  for (const key of VIEWPORT_TRANSITION_PROPS) {
32
49
  const startValue = startProps[key];
33
50
  const endValue = endProps[key];
34
51
  viewport[key] = lerp(startValue, endValue, t);
35
52
  }
53
+ // @ts-expect-error
36
54
  return viewport;
37
55
  }
38
56
 
@@ -48,19 +66,24 @@ export default function flyToViewport(startProps, endProps, t, opts = {}) {
48
66
  vec2.add(newCenterWorld, newCenterWorld, startCenterXY);
49
67
 
50
68
  const newCenter = worldToLngLat(newCenterWorld);
51
- viewport.longitude = newCenter[0];
52
- viewport.latitude = newCenter[1];
53
- viewport.zoom = newZoom;
54
- return viewport;
69
+ return {
70
+ longitude: newCenter[0],
71
+ latitude: newCenter[1],
72
+ zoom: newZoom
73
+ };
55
74
  }
56
75
 
57
76
  // returns transition duration in milliseconds
58
- export function getFlyToDuration(startProps, endProps, opts = {}) {
59
- opts = Object.assign({}, DEFAULT_OPTS, opts);
77
+ export function getFlyToDuration(
78
+ startProps: ViewportProps,
79
+ endProps: ViewportProps,
80
+ options?: FlytoTransitionOptions
81
+ ): number {
82
+ const opts = {...DEFAULT_OPTS, ...options};
60
83
  const {screenSpeed, speed, maxDuration} = opts;
61
84
  const {S, rho} = getFlyToTransitionParams(startProps, endProps, opts);
62
85
  const length = 1000 * S;
63
- let duration;
86
+ let duration: number;
64
87
  if (Number.isFinite(screenSpeed)) {
65
88
  duration = length / (screenSpeed / rho);
66
89
  } else {
@@ -73,7 +96,22 @@ export function getFlyToDuration(startProps, endProps, opts = {}) {
73
96
  // Private Methods
74
97
 
75
98
  // Calculate all parameters that are static for given startProps and endProps
76
- function getFlyToTransitionParams(startProps, endProps, opts) {
99
+ function getFlyToTransitionParams(
100
+ startProps: ViewportProps,
101
+ endProps: ViewportProps,
102
+ opts: FlytoTransitionOptions
103
+ ): {
104
+ startZoom: number;
105
+ startCenterXY: number[];
106
+ uDelta: number[];
107
+ w0: number;
108
+ u1: number;
109
+ S: number;
110
+ rho: number;
111
+ rho2: number;
112
+ r0: number;
113
+ r1: number;
114
+ } {
77
115
  opts = Object.assign({}, DEFAULT_OPTS, opts);
78
116
  const rho = opts.curve;
79
117
  const startZoom = startProps.zoom;
@@ -85,7 +123,7 @@ function getFlyToTransitionParams(startProps, endProps, opts) {
85
123
 
86
124
  const startCenterXY = lngLatToWorld(startCenter);
87
125
  const endCenterXY = lngLatToWorld(endCenter);
88
- const uDelta = vec2.sub([], endCenterXY, startCenterXY);
126
+ const uDelta = vec2.sub([] as number[], endCenterXY, startCenterXY);
89
127
 
90
128
  const w0 = Math.max(startProps.width, startProps.height);
91
129
  const w1 = w0 / scale;
@@ -1,6 +1,7 @@
1
1
  import {worldToLngLat} from './web-mercator-utils';
2
2
  import * as vec2 from 'gl-matrix/vec2';
3
3
  import {transformVector} from './math-utils';
4
+ import type WebMercatorViewport from './web-mercator-viewport';
4
5
 
5
6
  const DEGREES_TO_RADIANS = Math.PI / 180;
6
7
 
@@ -9,13 +10,14 @@ const DEGREES_TO_RADIANS = Math.PI / 180;
9
10
  * @param {WebMercatorViewport} viewport
10
11
  * @param {Number} z - elevation in meters
11
12
  */
12
- export default function getBounds(viewport, z = 0) {
13
+ export default function getBounds(viewport: WebMercatorViewport, z: number = 0): number[][] {
14
+ // eslint-disable-next-line @typescript-eslint/unbound-method
13
15
  const {width, height, unproject} = viewport;
14
16
  const unprojectOps = {targetZ: z};
15
17
  const bottomLeft = unproject([0, height], unprojectOps);
16
18
  const bottomRight = unproject([width, height], unprojectOps);
17
- let topLeft;
18
- let topRight;
19
+ let topLeft: number[];
20
+ let topRight: number[];
19
21
 
20
22
  const halfFov = viewport.fovy
21
23
  ? 0.5 * viewport.fovy * DEGREES_TO_RADIANS
@@ -41,7 +43,7 @@ export default function getBounds(viewport, z = 0) {
41
43
  * @param {Number} x - projected x in screen space
42
44
  * @param {Number} targetZ - the elevation of the point in meters
43
45
  */
44
- function unprojectOnFarPlane(viewport, x, targetZ) {
46
+ function unprojectOnFarPlane(viewport: WebMercatorViewport, x: number, targetZ: number): number[] {
45
47
  const {pixelUnprojectionMatrix} = viewport;
46
48
  const coord0 = transformVector(pixelUnprojectionMatrix, [x, 0, 1, 1]);
47
49
  const coord1 = transformVector(pixelUnprojectionMatrix, [x, viewport.height, 1, 1]);
@@ -51,6 +53,6 @@ function unprojectOnFarPlane(viewport, x, targetZ) {
51
53
  const coord = vec2.lerp([], coord0, coord1, t);
52
54
 
53
55
  const result = worldToLngLat(coord);
54
- result[2] = targetZ;
56
+ result.push(targetZ);
55
57
  return result;
56
58
  }
@@ -24,3 +24,7 @@ export {
24
24
  getProjectionMatrix,
25
25
  getProjectionParameters
26
26
  } from './web-mercator-utils';
27
+
28
+ /** Types */
29
+ export type {FitBoundsOptions} from './fit-bounds';
30
+ export type {DistanceScales} from './web-mercator-utils';
@@ -0,0 +1,32 @@
1
+ import {transformMat4, scale} from 'gl-matrix/vec4';
2
+
3
+ // Helper, avoids low-precision 32 bit matrices from gl-matrix mat4.create()
4
+ export function createMat4(): number[] {
5
+ return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
6
+ }
7
+
8
+ // Transforms a vec4 with a projection matrix
9
+ export function transformVector(matrix: number[], vector: number[]): number[] {
10
+ const result = transformMat4([] as number[], vector, matrix);
11
+ scale(result, result, 1 / result[3]);
12
+ return result;
13
+ }
14
+
15
+ export function mod(value: number, divisor: number): number {
16
+ const modulus = value % divisor;
17
+ return modulus < 0 ? divisor + modulus : modulus;
18
+ }
19
+
20
+ export function lerp(start: number, end: number, step: number): number {
21
+ return step * end + (1 - step) * start;
22
+ }
23
+
24
+ export function clamp(x: number, min: number, max: number): number {
25
+ return x < min ? min : x > max ? max : x;
26
+ }
27
+
28
+ function ieLog2(x: number): number {
29
+ return Math.log(x) * Math.LOG2E;
30
+ }
31
+ // Handle missing log2 in IE 11
32
+ export const log2 = Math.log2 || ieLog2;
@@ -4,17 +4,26 @@ import {mod, log2} from './math-utils';
4
4
  // defined by mapbox-gl
5
5
  const TILE_SIZE = 512;
6
6
 
7
- // Apply mathematical constraints to viewport props
7
+ /** Description of viewport */
8
+ export type ViewportProps = {
9
+ width: number;
10
+ height: number;
11
+ longitude: number;
12
+ latitude: number;
13
+ zoom: number;
14
+ pitch?: number;
15
+ bearing?: number;
16
+ };
17
+
18
+ /**
19
+ * Apply mathematical constraints to viewport props
20
+ * @param props
21
+ */
8
22
  // eslint-disable-next-line complexity
9
- export default function normalizeViewportProps({
10
- width,
11
- height,
12
- longitude,
13
- latitude,
14
- zoom,
15
- pitch = 0,
16
- bearing = 0
17
- }) {
23
+ export default function normalizeViewportProps(props: ViewportProps): ViewportProps {
24
+ const {width, height, pitch = 0} = props;
25
+ let {longitude, latitude, zoom, bearing = 0} = props;
26
+
18
27
  // Normalize degrees
19
28
  if (longitude < -180 || longitude > 180) {
20
29
  longitude = mod(longitude + 180, 360) - 180;
@@ -21,12 +21,40 @@ export const MAX_LATITUDE = 85.051129;
21
21
  // Mapbox default altitude
22
22
  export const DEFAULT_ALTITUDE = 1.5;
23
23
 
24
- /** Util functions **/
25
- export function zoomToScale(zoom) {
24
+ export type DistanceScales = {
25
+ unitsPerMeter: number[];
26
+ metersPerUnit: number[];
27
+ unitsPerMeter2?: number[];
28
+ unitsPerDegree: number[];
29
+ degreesPerUnit: number[];
30
+ unitsPerDegree2?: number[];
31
+ };
32
+
33
+ /**
34
+ * PROJECTION MATRIX PARAMETERS
35
+ *
36
+ * TODO how to document mebers
37
+ * @param fov in radians. fov is variable, depends on pitch and altitude
38
+ * @param aspect width/height
39
+ * @param focalDistance distance at which visual scale factor is 1
40
+ * @param near near clipping plane
41
+ * @param far far clipping plane
42
+ */
43
+ type ProjectionParameters = {
44
+ fov: number;
45
+ aspect: number;
46
+ focalDistance: number;
47
+ near: number;
48
+ far: number;
49
+ };
50
+
51
+ /** Logarithimic zoom to linear scale **/
52
+ export function zoomToScale(zoom: number): number {
26
53
  return Math.pow(2, zoom);
27
54
  }
28
55
 
29
- export function scaleToZoom(scale) {
56
+ /** Linear scale to logarithimic zoom **/
57
+ export function scaleToZoom(scale: number): number {
30
58
  return log2(scale);
31
59
  }
32
60
 
@@ -40,7 +68,8 @@ export function scaleToZoom(scale) {
40
68
  * Specifies a point on the sphere to project onto the map.
41
69
  * @return [x,y] coordinates.
42
70
  */
43
- export function lngLatToWorld([lng, lat]) {
71
+ export function lngLatToWorld(lngLat: number[]): [number, number] {
72
+ const [lng, lat] = lngLat;
44
73
  assert(Number.isFinite(lng));
45
74
  assert(Number.isFinite(lat) && lat >= -90 && lat <= 90, 'invalid latitude');
46
75
 
@@ -51,16 +80,28 @@ export function lngLatToWorld([lng, lat]) {
51
80
  return [x, y];
52
81
  }
53
82
 
54
- // Unproject world point [x,y] on map onto {lat, lon} on sphere
55
- export function worldToLngLat([x, y]) {
83
+ /**
84
+ * Unproject world point [x,y] on map onto {lat, lon} on sphere
85
+ *
86
+ * @param xy - array with [x,y] members
87
+ * representing point on projected map plane
88
+ * @return - array with [x,y] of point on sphere.
89
+ * Has toArray method if you need a GeoJSON Array.
90
+ * Per cartographic tradition, lat and lon are specified as degrees.
91
+ */
92
+ export function worldToLngLat(xy: number[]): [number, number] {
93
+ const [x, y] = xy;
56
94
  const lambda2 = (x / TILE_SIZE) * (2 * PI) - PI;
57
95
  const phi2 = 2 * (Math.atan(Math.exp((y / TILE_SIZE) * (2 * PI) - PI)) - PI_4);
58
96
  return [lambda2 * RADIANS_TO_DEGREES, phi2 * RADIANS_TO_DEGREES];
59
97
  }
60
98
 
61
- // Returns the zoom level that gives a 1 meter pixel at a certain latitude
62
- // 1 = C*cos(y)/2^z/TILE_SIZE = C*cos(y)/2^(z+9)
63
- export function getMeterZoom({latitude}) {
99
+ /**
100
+ * Returns the zoom level that gives a 1 meter pixel at a certain latitude
101
+ * 1 = C*cos(y)/2^z/TILE_SIZE = C*cos(y)/2^(z+9)
102
+ */
103
+ export function getMeterZoom(options: {latitude: number}): number {
104
+ const {latitude} = options;
64
105
  assert(Number.isFinite(latitude));
65
106
  const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);
66
107
  return scaleToZoom(EARTH_CIRCUMFERENCE * latCosine) - 9;
@@ -72,11 +113,14 @@ export function getMeterZoom({latitude}) {
72
113
  * In mercator projection mode, the distance scales vary significantly
73
114
  * with latitude.
74
115
  */
75
-
76
- export function getDistanceScales({latitude, longitude, highPrecision = false}) {
116
+ export function getDistanceScales(options: {
117
+ latitude: number;
118
+ longitude: number;
119
+ highPrecision?: boolean;
120
+ }): DistanceScales {
121
+ const {latitude, longitude, highPrecision = false} = options;
77
122
  assert(Number.isFinite(latitude) && Number.isFinite(longitude));
78
123
 
79
- const result = {};
80
124
  const worldSize = TILE_SIZE;
81
125
  const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);
82
126
 
@@ -102,11 +146,13 @@ export function getDistanceScales({latitude, longitude, highPrecision = false})
102
146
  *
103
147
  * Y needs to be flipped when converting delta degree/meter to delta pixels
104
148
  */
105
- result.unitsPerMeter = [altUnitsPerMeter, altUnitsPerMeter, altUnitsPerMeter];
106
- result.metersPerUnit = [1 / altUnitsPerMeter, 1 / altUnitsPerMeter, 1 / altUnitsPerMeter];
149
+ const result: DistanceScales = {
150
+ unitsPerMeter: [altUnitsPerMeter, altUnitsPerMeter, altUnitsPerMeter],
151
+ metersPerUnit: [1 / altUnitsPerMeter, 1 / altUnitsPerMeter, 1 / altUnitsPerMeter],
107
152
 
108
- result.unitsPerDegree = [unitsPerDegreeX, unitsPerDegreeY, altUnitsPerMeter];
109
- result.degreesPerUnit = [1 / unitsPerDegreeX, 1 / unitsPerDegreeY, 1 / altUnitsPerMeter];
153
+ unitsPerDegree: [unitsPerDegreeX, unitsPerDegreeY, altUnitsPerMeter],
154
+ degreesPerUnit: [1 / unitsPerDegreeX, 1 / unitsPerDegreeY, 1 / altUnitsPerMeter]
155
+ };
110
156
 
111
157
  /**
112
158
  * Taylor series 2nd order for 1/latCosine
@@ -131,7 +177,7 @@ export function getDistanceScales({latitude, longitude, highPrecision = false})
131
177
  /**
132
178
  * Offset a lng/lat position by meterOffset (northing, easting)
133
179
  */
134
- export function addMetersToLngLat(lngLatZ, xyz) {
180
+ export function addMetersToLngLat(lngLatZ: number[], xyz: number[]): number[] {
135
181
  const [longitude, latitude, z0] = lngLatZ;
136
182
  const [x, y, z] = xyz;
137
183
 
@@ -145,28 +191,38 @@ export function addMetersToLngLat(lngLatZ, xyz) {
145
191
  worldspace[0] += x * (unitsPerMeter[0] + unitsPerMeter2[0] * y);
146
192
  worldspace[1] += y * (unitsPerMeter[1] + unitsPerMeter2[1] * y);
147
193
 
148
- // @ts-ignore
149
194
  const newLngLat = worldToLngLat(worldspace);
150
195
  const newZ = (z0 || 0) + (z || 0);
151
196
 
152
197
  return Number.isFinite(z0) || Number.isFinite(z) ? [newLngLat[0], newLngLat[1], newZ] : newLngLat;
153
198
  }
154
199
 
155
- // ATTRIBUTION:
156
- // view and projection matrix creation is intentionally kept compatible with
157
- // mapbox-gl's implementation to ensure that seamless interoperation
158
- // with mapbox and react-map-gl. See: https://github.com/mapbox/mapbox-gl-js
159
-
160
- export function getViewMatrix({
200
+ /**
201
+ *
202
+ * view and projection matrix creation is intentionally kept compatible with
203
+ * mapbox-gl's implementation to ensure that seamless interoperation
204
+ * with mapbox and react-map-gl. See: https://github.com/mapbox/mapbox-gl-js
205
+ */
206
+ export function getViewMatrix(options: {
161
207
  // Viewport props
162
- height,
163
- pitch,
164
- bearing,
165
- altitude,
208
+ height: number;
209
+ pitch: number;
210
+ bearing: number;
211
+ altitude: number;
166
212
  // Pre-calculated parameters
167
- scale,
168
- center = null
169
- }) {
213
+ scale: number;
214
+ center?: number[];
215
+ }): number[] {
216
+ const {
217
+ // Viewport props
218
+ height,
219
+ pitch,
220
+ bearing,
221
+ altitude,
222
+ // Pre-calculated parameters
223
+ scale,
224
+ center
225
+ } = options;
170
226
  // VIEW MATRIX: PROJECTS MERCATOR WORLD COORDINATES
171
227
  // Note that mercator world coordinates typically need to be flipped
172
228
  //
@@ -181,8 +237,8 @@ export function getViewMatrix({
181
237
  mat4.rotateX(vm, vm, -pitch * DEGREES_TO_RADIANS);
182
238
  mat4.rotateZ(vm, vm, bearing * DEGREES_TO_RADIANS);
183
239
 
184
- scale /= height;
185
- mat4.scale(vm, vm, [scale, scale, scale]);
240
+ const relativeScale = scale / height;
241
+ mat4.scale(vm, vm, [relativeScale, relativeScale, relativeScale]);
186
242
 
187
243
  if (center) {
188
244
  mat4.translate(vm, vm, vec3.negate([], center));
@@ -191,17 +247,30 @@ export function getViewMatrix({
191
247
  return vm;
192
248
  }
193
249
 
194
- // PROJECTION MATRIX PARAMETERS
195
- // Variable fov (in radians)
196
- export function getProjectionParameters({
197
- width,
198
- height,
199
- fovy = altitudeToFovy(DEFAULT_ALTITUDE),
200
- altitude,
201
- pitch = 0,
202
- nearZMultiplier = 1,
203
- farZMultiplier = 1
204
- }) {
250
+ /**
251
+ * Calculates mapbox compatible projection matrix from parameters
252
+ *
253
+ * @param options.width Width of "viewport" or window
254
+ * @param options.height Height of "viewport" or window
255
+ * @param options.pitch Camera angle in degrees (0 is straight down)
256
+ * @param options.fovy field of view in degrees
257
+ * @param options.altitude if provided, field of view is calculated using `altitudeToFovy()`
258
+ * @param options.nearZMultiplier control z buffer
259
+ * @param options.farZMultiplier control z buffer
260
+ * @returns project parameters object
261
+ */
262
+ export function getProjectionParameters(options: {
263
+ width: number;
264
+ height: number;
265
+ fovy?: number;
266
+ altitude?: number;
267
+ pitch?: number;
268
+ nearZMultiplier?: number;
269
+ farZMultiplier?: number;
270
+ }): ProjectionParameters {
271
+ const {width, height, altitude, pitch = 0, nearZMultiplier = 1, farZMultiplier = 1} = options;
272
+ let {fovy = altitudeToFovy(DEFAULT_ALTITUDE)} = options;
273
+
205
274
  // For back-compatibility allow field of view to be
206
275
  // derived from altitude
207
276
  if (altitude !== undefined) {
@@ -229,31 +298,36 @@ export function getProjectionParameters({
229
298
  };
230
299
  }
231
300
 
232
- // PROJECTION MATRIX: PROJECTS FROM CAMERA (VIEW) SPACE TO CLIPSPACE
233
- // To match mapbox's z buffer:
234
- // <= 0.28 - nearZMultiplier: 0.1, farZmultiplier: 1
235
- // >= 0.29 - nearZMultiplier: 1 / height, farZMultiplier: 1.01
236
- export function getProjectionMatrix({
237
- width,
238
- height,
239
- pitch,
240
- altitude,
241
- fovy,
242
- nearZMultiplier,
243
- farZMultiplier
244
- }) {
245
- const {fov, aspect, near, far} = getProjectionParameters({
246
- width,
247
- height,
248
- altitude,
249
- fovy,
250
- pitch,
251
- nearZMultiplier,
252
- farZMultiplier
253
- });
301
+ /**
302
+ * CALCULATE PROJECTION MATRIX: PROJECTS FROM CAMERA (VIEW) SPACE TO CLIPSPACE
303
+ *
304
+ * To match mapbox's z buffer:
305
+ * - \<= 0.28: nearZMultiplier: 0.1, farZmultiplier: 1
306
+ * - \>= 0.29: nearZMultiplier: 1 / height, farZMultiplier: 1.01
307
+ *
308
+ * @param options Viewport options
309
+ * @param options.width Width of "viewport" or window
310
+ * @param options.height Height of "viewport" or window
311
+ * @param options.pitch Camera angle in degrees (0 is straight down)
312
+ * @param options.fovy field of view in degrees
313
+ * @param options.altitude if provided, field of view is calculated using `altitudeToFovy()`
314
+ * @param options.nearZMultiplier control z buffer
315
+ * @param options.farZMultiplier control z buffer
316
+ * @returns 4x4 projection matrix
317
+ */
318
+ export function getProjectionMatrix(options: {
319
+ width: number;
320
+ height: number;
321
+ pitch: number;
322
+ fovy?: number;
323
+ altitude?: number;
324
+ nearZMultiplier: number;
325
+ farZMultiplier: number;
326
+ }): number[] {
327
+ const {fov, aspect, near, far} = getProjectionParameters(options);
254
328
 
255
329
  const projectionMatrix = mat4.perspective(
256
- [],
330
+ [] as number[],
257
331
  fov, // fov in radians
258
332
  aspect, // aspect ratio
259
333
  near, // near plane
@@ -263,27 +337,61 @@ export function getProjectionMatrix({
263
337
  return projectionMatrix;
264
338
  }
265
339
 
266
- // Utility function to calculate the field of view such that
267
- // the focal distance is equal to the ground distance. This
268
- // is how mapbox's z fov is calculated
269
- export function altitudeToFovy(altitude) {
340
+ /**
341
+ *
342
+ * Convert an altitude to field of view such that the
343
+ * focal distance is equal to the altitude
344
+ *
345
+ * @param altitude - altitude of camera in screen units
346
+ * @return fovy field of view in degrees
347
+ */
348
+ export function altitudeToFovy(altitude: number): number {
270
349
  return 2 * Math.atan(0.5 / altitude) * RADIANS_TO_DEGREES;
271
350
  }
272
351
 
273
- export function fovyToAltitude(fovy) {
352
+ /**
353
+ *
354
+ * Convert an field of view such that the
355
+ * focal distance is equal to the altitude
356
+ *
357
+ * @param fovy - field of view in degrees
358
+ * @return altitude altitude of camera in screen units
359
+ */
360
+ export function fovyToAltitude(fovy: number): number {
274
361
  return 0.5 / Math.tan(0.5 * fovy * DEGREES_TO_RADIANS);
275
362
  }
276
363
 
364
+ /**
365
+ * Project flat coordinates to pixels on screen.
366
+ *
367
+ * @param xyz - flat coordinate on 512*512 Mercator Zoom 0 tile
368
+ * @param pixelProjectionMatrix - projection matrix 4x4
369
+ * @return [x, y, depth] pixel coordinate on screen.
370
+ */
371
+ export function worldToPixels(xyz: number[], pixelProjectionMatrix: number[]): number[];
372
+
277
373
  // Project flat coordinates to pixels on screen.
278
- export function worldToPixels(xyz, pixelProjectionMatrix) {
374
+ export function worldToPixels(xyz: number[], pixelProjectionMatrix: number[]): number[] {
279
375
  const [x, y, z = 0] = xyz;
280
376
  assert(Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z));
281
377
 
282
378
  return transformVector(pixelProjectionMatrix, [x, y, z, 1]);
283
379
  }
284
380
 
285
- // Unproject pixels on screen to flat coordinates.
286
- export function pixelsToWorld(xyz, pixelUnprojectionMatrix, targetZ = 0) {
381
+ /**
382
+ * Unproject pixels on screen to flat coordinates.
383
+ *
384
+ * @param xyz - pixel coordinate on screen.
385
+ * @param pixelUnprojectionMatrix - unprojection matrix 4x4
386
+ * @param targetZ - if pixel coordinate does not have a 3rd component (depth),
387
+ * targetZ is used as the elevation plane to unproject onto
388
+ * @return [x, y, Z] flat coordinates on 512*512 Mercator Zoom 0 tile.
389
+ */
390
+ export function pixelsToWorld(
391
+ xyz: number[],
392
+ pixelUnprojectionMatrix: number[],
393
+ targetZ: number = 0
394
+ ): number[] {
287
395
  const [x, y, z] = xyz;
288
396
  assert(Number.isFinite(x) && Number.isFinite(y), 'invalid pixel coordinate');
289
397
 
@@ -302,5 +410,5 @@ export function pixelsToWorld(xyz, pixelUnprojectionMatrix, targetZ = 0) {
302
410
  const z1 = coord1[2];
303
411
 
304
412
  const t = z0 === z1 ? 0 : ((targetZ || 0) - z0) / (z1 - z0);
305
- return vec2.lerp([], coord0, coord1, t);
413
+ return vec2.lerp([] as number[], coord0, coord1, t);
306
414
  }