@math.gl/web-mercator 3.6.1 → 3.6.2

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.
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "description": "Utilities for perspective-enabled Web Mercator projections",
4
4
  "author": "Uber Technologies, Inc.",
5
5
  "license": "MIT",
6
- "version": "3.6.1",
6
+ "version": "3.6.2",
7
7
  "keywords": [
8
8
  "webgl",
9
9
  "javascript",
@@ -33,5 +33,5 @@
33
33
  "mapbox-gl": "^1.0.0",
34
34
  "mock-browser": "^0.92.14"
35
35
  },
36
- "gitHead": "1d356f92757adf26caab09abcb5fc424f11835c0"
36
+ "gitHead": "517015873bbd7143bfc4bb761e70071c7a86771b"
37
37
  }
package/dist/assert.js DELETED
@@ -1,8 +0,0 @@
1
- // Replacement for the external assert method to reduce bundle size
2
- // Note: We don't use the second "message" argument in calling code,
3
- // so no need to support it here
4
- export default function assert(condition, message) {
5
- if (!condition) {
6
- throw new Error(message || '@math.gl/web-mercator: assertion failed.');
7
- }
8
- }
@@ -1,63 +0,0 @@
1
- import assert from './assert';
2
- import { log2, clamp } from './math-utils';
3
- import { MAX_LATITUDE, lngLatToWorld, worldToLngLat } from './web-mercator-utils';
4
- /**
5
- * Returns map settings {latitude, longitude, zoom}
6
- * that will contain the provided corners within the provided width.
7
- *
8
- * > _Note: Only supports non-perspective mode._
9
- *
10
- * @param options fit bounds parameters
11
- * @returns - latitude, longitude and zoom
12
- */
13
- export default function fitBounds(options) {
14
- const { width, height, bounds, minExtent = 0, // 0.01 would be about 1000 meters (degree is ~110KM)
15
- maxZoom = 24, // ~x4,000,000 => About 10 meter extents
16
- offset = [0, 0] } = options;
17
- const [[west, south], [east, north]] = bounds;
18
- const padding = getPaddingObject(options.padding);
19
- const nw = lngLatToWorld([west, clamp(north, -MAX_LATITUDE, MAX_LATITUDE)]);
20
- const se = lngLatToWorld([east, clamp(south, -MAX_LATITUDE, MAX_LATITUDE)]);
21
- // width/height on the Web Mercator plane
22
- const size = [
23
- Math.max(Math.abs(se[0] - nw[0]), minExtent),
24
- Math.max(Math.abs(se[1] - nw[1]), minExtent)
25
- ];
26
- const targetSize = [
27
- width - padding.left - padding.right - Math.abs(offset[0]) * 2,
28
- height - padding.top - padding.bottom - Math.abs(offset[1]) * 2
29
- ];
30
- assert(targetSize[0] > 0 && targetSize[1] > 0);
31
- // scale = screen pixels per unit on the Web Mercator plane
32
- const scaleX = targetSize[0] / size[0];
33
- const scaleY = targetSize[1] / size[1];
34
- // Find how much we need to shift the center
35
- const offsetX = (padding.right - padding.left) / 2 / scaleX;
36
- const offsetY = (padding.bottom - padding.top) / 2 / scaleY;
37
- const center = [(se[0] + nw[0]) / 2 + offsetX, (se[1] + nw[1]) / 2 + offsetY];
38
- const centerLngLat = worldToLngLat(center);
39
- const zoom = Math.min(maxZoom, log2(Math.abs(Math.min(scaleX, scaleY))));
40
- assert(Number.isFinite(zoom));
41
- return {
42
- longitude: centerLngLat[0],
43
- latitude: centerLngLat[1],
44
- zoom
45
- };
46
- }
47
- // Helpers
48
- function getPaddingObject(padding = 0) {
49
- if (typeof padding === 'number') {
50
- return {
51
- top: padding,
52
- bottom: padding,
53
- left: padding,
54
- right: padding
55
- };
56
- }
57
- // Make sure all the required properties are set
58
- assert(Number.isFinite(padding.top) &&
59
- Number.isFinite(padding.bottom) &&
60
- Number.isFinite(padding.left) &&
61
- Number.isFinite(padding.right));
62
- return padding;
63
- }
@@ -1,87 +0,0 @@
1
- import { lerp } from './math-utils';
2
- import { scaleToZoom, zoomToScale, lngLatToWorld, worldToLngLat } from './web-mercator-utils';
3
- import * as vec2 from 'gl-matrix/vec2';
4
- const EPSILON = 0.01;
5
- const VIEWPORT_TRANSITION_PROPS = ['longitude', 'latitude', 'zoom'];
6
- const DEFAULT_OPTS = {
7
- curve: 1.414,
8
- speed: 1.2
9
- // screenSpeed and maxDuration are used only if specified
10
- };
11
- /**
12
- * mapbox-gl-js flyTo : https://www.mapbox.com/mapbox-gl-js/api/#map#flyto.
13
- * It implements “Smooth and efficient zooming and panning.” algorithm by
14
- * "Jarke J. van Wijk and Wim A.A. Nuij"
15
- */
16
- export default function flyToViewport(startProps, endProps, t, options) {
17
- // Equations from above paper are referred where needed.
18
- const { startZoom, startCenterXY, uDelta, w0, u1, S, rho, rho2, r0 } = getFlyToTransitionParams(startProps, endProps, options);
19
- // If change in center is too small, do linear interpolaiton.
20
- if (u1 < EPSILON) {
21
- const viewport = {};
22
- for (const key of VIEWPORT_TRANSITION_PROPS) {
23
- const startValue = startProps[key];
24
- const endValue = endProps[key];
25
- viewport[key] = lerp(startValue, endValue, t);
26
- }
27
- // @ts-expect-error properties are populated dynamically
28
- return viewport;
29
- }
30
- const s = t * S;
31
- const w = Math.cosh(r0) / Math.cosh(r0 + rho * s);
32
- const u = (w0 * ((Math.cosh(r0) * Math.tanh(r0 + rho * s) - Math.sinh(r0)) / rho2)) / u1;
33
- const scaleIncrement = 1 / w; // Using w method for scaling.
34
- const newZoom = startZoom + scaleToZoom(scaleIncrement);
35
- const newCenterWorld = vec2.scale([], uDelta, u);
36
- vec2.add(newCenterWorld, newCenterWorld, startCenterXY);
37
- const newCenter = worldToLngLat(newCenterWorld);
38
- return {
39
- longitude: newCenter[0],
40
- latitude: newCenter[1],
41
- zoom: newZoom
42
- };
43
- }
44
- // returns transition duration in milliseconds
45
- export function getFlyToDuration(startProps, endProps, options) {
46
- const opts = { ...DEFAULT_OPTS, ...options };
47
- const { screenSpeed, speed, maxDuration } = opts;
48
- const { S, rho } = getFlyToTransitionParams(startProps, endProps, opts);
49
- const length = 1000 * S;
50
- let duration;
51
- if (Number.isFinite(screenSpeed)) {
52
- duration = length / (screenSpeed / rho);
53
- }
54
- else {
55
- duration = length / speed;
56
- }
57
- return Number.isFinite(maxDuration) && duration > maxDuration ? 0 : duration;
58
- }
59
- // Private Methods
60
- // Calculate all parameters that are static for given startProps and endProps
61
- function getFlyToTransitionParams(startProps, endProps, opts) {
62
- opts = Object.assign({}, DEFAULT_OPTS, opts);
63
- const rho = opts.curve;
64
- const startZoom = startProps.zoom;
65
- const startCenter = [startProps.longitude, startProps.latitude];
66
- const startScale = zoomToScale(startZoom);
67
- const endZoom = endProps.zoom;
68
- const endCenter = [endProps.longitude, endProps.latitude];
69
- const scale = zoomToScale(endZoom - startZoom);
70
- const startCenterXY = lngLatToWorld(startCenter);
71
- const endCenterXY = lngLatToWorld(endCenter);
72
- const uDelta = vec2.sub([], endCenterXY, startCenterXY);
73
- const w0 = Math.max(startProps.width, startProps.height);
74
- const w1 = w0 / scale;
75
- const u1 = vec2.length(uDelta) * startScale;
76
- // u0 is treated as '0' in Eq (9).
77
- // If u1 is too small, will generate invalid number
78
- const _u1 = Math.max(u1, EPSILON);
79
- // Implement Equation (9) from above algorithm.
80
- const rho2 = rho * rho;
81
- const b0 = (w1 * w1 - w0 * w0 + rho2 * rho2 * _u1 * _u1) / (2 * w0 * rho2 * _u1);
82
- const b1 = (w1 * w1 - w0 * w0 - rho2 * rho2 * _u1 * _u1) / (2 * w1 * rho2 * _u1);
83
- const r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0);
84
- const r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
85
- const S = (r1 - r0) / rho;
86
- return { startZoom, startCenterXY, uDelta, w0, u1, S, rho, rho2, r0, r1 };
87
- }
@@ -1,51 +0,0 @@
1
- import { worldToLngLat } from './web-mercator-utils';
2
- import * as vec2 from 'gl-matrix/vec2';
3
- import { transformVector } from './math-utils';
4
- const DEGREES_TO_RADIANS = Math.PI / 180;
5
- /*
6
- * Returns the quad at the intersection of the frustum and the given z plane
7
- * @param {WebMercatorViewport} viewport
8
- * @param {Number} z - elevation in meters
9
- */
10
- export default function getBounds(viewport, z = 0) {
11
- // eslint-disable-next-line @typescript-eslint/unbound-method
12
- const { width, height, unproject } = viewport;
13
- const unprojectOps = { targetZ: z };
14
- const bottomLeft = unproject([0, height], unprojectOps);
15
- const bottomRight = unproject([width, height], unprojectOps);
16
- let topLeft;
17
- let topRight;
18
- const halfFov = viewport.fovy
19
- ? 0.5 * viewport.fovy * DEGREES_TO_RADIANS
20
- : Math.atan(0.5 / viewport.altitude);
21
- const angleToGround = (90 - viewport.pitch) * DEGREES_TO_RADIANS;
22
- // The top plane is parallel to the ground if halfFov == angleToGround
23
- if (halfFov > angleToGround - 0.01) {
24
- // intersect with the far plane
25
- topLeft = unprojectOnFarPlane(viewport, 0, z);
26
- topRight = unprojectOnFarPlane(viewport, width, z);
27
- }
28
- else {
29
- // intersect with the top plane
30
- topLeft = unproject([0, 0], unprojectOps);
31
- topRight = unproject([width, 0], unprojectOps);
32
- }
33
- return [bottomLeft, bottomRight, topRight, topLeft];
34
- }
35
- /*
36
- * Find a point on the far clipping plane of the viewport
37
- * @param {WebMercatorViewport} viewport
38
- * @param {Number} x - projected x in screen space
39
- * @param {Number} targetZ - the elevation of the point in meters
40
- */
41
- function unprojectOnFarPlane(viewport, x, targetZ) {
42
- const { pixelUnprojectionMatrix } = viewport;
43
- const coord0 = transformVector(pixelUnprojectionMatrix, [x, 0, 1, 1]);
44
- const coord1 = transformVector(pixelUnprojectionMatrix, [x, viewport.height, 1, 1]);
45
- const z = targetZ * viewport.distanceScales.unitsPerMeter[2];
46
- const t = (z - coord0[2]) / (coord1[2] - coord0[2]);
47
- const coord = vec2.lerp([], coord0, coord1, t);
48
- const result = worldToLngLat(coord);
49
- result.push(targetZ);
50
- return result;
51
- }
package/dist/index.js DELETED
@@ -1,8 +0,0 @@
1
- // Classic web-mercator-project
2
- export { default } from './web-mercator-viewport';
3
- export { default as WebMercatorViewport } from './web-mercator-viewport';
4
- export { default as getBounds } from './get-bounds';
5
- export { default as fitBounds } from './fit-bounds';
6
- export { default as normalizeViewportProps } from './normalize-viewport-props';
7
- export { default as flyToViewport, getFlyToDuration } from './fly-to-viewport';
8
- export { MAX_LATITUDE, lngLatToWorld, worldToLngLat, worldToPixels, pixelsToWorld, zoomToScale, scaleToZoom, altitudeToFovy, fovyToAltitude, getMeterZoom, unitsPerMeter, getDistanceScales, addMetersToLngLat, getViewMatrix, getProjectionMatrix, getProjectionParameters } from './web-mercator-utils';
@@ -1,26 +0,0 @@
1
- import { transformMat4, scale } from 'gl-matrix/vec4';
2
- // Helper, avoids low-precision 32 bit matrices from gl-matrix mat4.create()
3
- export function createMat4() {
4
- return [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
5
- }
6
- // Transforms a vec4 with a projection matrix
7
- export function transformVector(matrix, vector) {
8
- const result = transformMat4([], vector, matrix);
9
- scale(result, result, 1 / result[3]);
10
- return result;
11
- }
12
- export function mod(value, divisor) {
13
- const modulus = value % divisor;
14
- return modulus < 0 ? divisor + modulus : modulus;
15
- }
16
- export function lerp(start, end, step) {
17
- return step * end + (1 - step) * start;
18
- }
19
- export function clamp(x, min, max) {
20
- return x < min ? min : x > max ? max : x;
21
- }
22
- function ieLog2(x) {
23
- return Math.log(x) * Math.LOG2E;
24
- }
25
- // Handle missing log2 in IE 11
26
- export const log2 = Math.log2 || ieLog2;
@@ -1,41 +0,0 @@
1
- import { worldToLngLat } from './web-mercator-utils';
2
- import { mod, log2 } from './math-utils';
3
- // defined by mapbox-gl
4
- const TILE_SIZE = 512;
5
- /**
6
- * Apply mathematical constraints to viewport props
7
- * @param props
8
- */
9
- // eslint-disable-next-line complexity
10
- export default function normalizeViewportProps(props) {
11
- const { width, height, pitch = 0 } = props;
12
- let { longitude, latitude, zoom, bearing = 0 } = props;
13
- // Normalize degrees
14
- if (longitude < -180 || longitude > 180) {
15
- longitude = mod(longitude + 180, 360) - 180;
16
- }
17
- if (bearing < -180 || bearing > 180) {
18
- bearing = mod(bearing + 180, 360) - 180;
19
- }
20
- // Constrain zoom and shift center at low zoom levels
21
- const minZoom = log2(height / TILE_SIZE);
22
- if (zoom <= minZoom) {
23
- zoom = minZoom;
24
- latitude = 0;
25
- }
26
- else {
27
- // Eliminate white space above and below the map
28
- const halfHeightPixels = height / 2 / Math.pow(2, zoom);
29
- const minLatitude = worldToLngLat([0, halfHeightPixels])[1];
30
- if (latitude < minLatitude) {
31
- latitude = minLatitude;
32
- }
33
- else {
34
- const maxLatitude = worldToLngLat([0, TILE_SIZE - halfHeightPixels])[1];
35
- if (latitude > maxLatitude) {
36
- latitude = maxLatitude;
37
- }
38
- }
39
- }
40
- return { width, height, longitude, latitude, zoom, pitch, bearing };
41
- }
@@ -1,316 +0,0 @@
1
- // TODO - THE UTILITIES IN THIS FILE SHOULD BE IMPORTED FROM WEB-MERCATOR-VIEWPORT MODULE
2
- import { createMat4, transformVector, clamp, log2 } from './math-utils';
3
- import * as mat4 from 'gl-matrix/mat4';
4
- import * as vec2 from 'gl-matrix/vec2';
5
- import * as vec3 from 'gl-matrix/vec3';
6
- import assert from './assert';
7
- // CONSTANTS
8
- const PI = Math.PI;
9
- const PI_4 = PI / 4;
10
- const DEGREES_TO_RADIANS = PI / 180;
11
- const RADIANS_TO_DEGREES = 180 / PI;
12
- const TILE_SIZE = 512;
13
- // Average circumference (40075 km equatorial, 40007 km meridional)
14
- const EARTH_CIRCUMFERENCE = 40.03e6;
15
- // Latitude that makes a square world, 2 * atan(E ** PI) - PI / 2
16
- export const MAX_LATITUDE = 85.051129;
17
- // Mapbox default altitude
18
- export const DEFAULT_ALTITUDE = 1.5;
19
- /** Logarithimic zoom to linear scale **/
20
- export function zoomToScale(zoom) {
21
- return Math.pow(2, zoom);
22
- }
23
- /** Linear scale to logarithimic zoom **/
24
- export function scaleToZoom(scale) {
25
- return log2(scale);
26
- }
27
- /**
28
- * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.
29
- * Performs the nonlinear part of the web mercator projection.
30
- * Remaining projection is done with 4x4 matrices which also handles
31
- * perspective.
32
- *
33
- * @param lngLat - [lng, lat] coordinates
34
- * Specifies a point on the sphere to project onto the map.
35
- * @return [x,y] coordinates.
36
- */
37
- export function lngLatToWorld(lngLat) {
38
- const [lng, lat] = lngLat;
39
- assert(Number.isFinite(lng));
40
- assert(Number.isFinite(lat) && lat >= -90 && lat <= 90, 'invalid latitude');
41
- const lambda2 = lng * DEGREES_TO_RADIANS;
42
- const phi2 = lat * DEGREES_TO_RADIANS;
43
- const x = (TILE_SIZE * (lambda2 + PI)) / (2 * PI);
44
- const y = (TILE_SIZE * (PI + Math.log(Math.tan(PI_4 + phi2 * 0.5)))) / (2 * PI);
45
- return [x, y];
46
- }
47
- /**
48
- * Unproject world point [x,y] on map onto {lat, lon} on sphere
49
- *
50
- * @param xy - array with [x,y] members
51
- * representing point on projected map plane
52
- * @return - array with [x,y] of point on sphere.
53
- * Has toArray method if you need a GeoJSON Array.
54
- * Per cartographic tradition, lat and lon are specified as degrees.
55
- */
56
- export function worldToLngLat(xy) {
57
- const [x, y] = xy;
58
- const lambda2 = (x / TILE_SIZE) * (2 * PI) - PI;
59
- const phi2 = 2 * (Math.atan(Math.exp((y / TILE_SIZE) * (2 * PI) - PI)) - PI_4);
60
- return [lambda2 * RADIANS_TO_DEGREES, phi2 * RADIANS_TO_DEGREES];
61
- }
62
- /**
63
- * Returns the zoom level that gives a 1 meter pixel at a certain latitude
64
- * 1 = C*cos(y)/2^z/TILE_SIZE = C*cos(y)/2^(z+9)
65
- */
66
- export function getMeterZoom(options) {
67
- const { latitude } = options;
68
- assert(Number.isFinite(latitude));
69
- const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);
70
- return scaleToZoom(EARTH_CIRCUMFERENCE * latCosine) - 9;
71
- }
72
- /**
73
- * Calculate the conversion from meter to common units at a given latitude
74
- * This is a cheaper version of `getDistanceScales`
75
- * @param latitude center latitude in degrees
76
- * @returns common units per meter
77
- */
78
- export function unitsPerMeter(latitude) {
79
- const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);
80
- return TILE_SIZE / EARTH_CIRCUMFERENCE / latCosine;
81
- }
82
- /**
83
- * Calculate distance scales in meters around current lat/lon, both for
84
- * degrees and pixels.
85
- * In mercator projection mode, the distance scales vary significantly
86
- * with latitude.
87
- */
88
- export function getDistanceScales(options) {
89
- const { latitude, longitude, highPrecision = false } = options;
90
- assert(Number.isFinite(latitude) && Number.isFinite(longitude));
91
- const worldSize = TILE_SIZE;
92
- const latCosine = Math.cos(latitude * DEGREES_TO_RADIANS);
93
- /**
94
- * Number of pixels occupied by one degree longitude around current lat/lon:
95
- unitsPerDegreeX = d(lngLatToWorld([lng, lat])[0])/d(lng)
96
- = scale * TILE_SIZE * DEGREES_TO_RADIANS / (2 * PI)
97
- unitsPerDegreeY = d(lngLatToWorld([lng, lat])[1])/d(lat)
98
- = -scale * TILE_SIZE * DEGREES_TO_RADIANS / cos(lat * DEGREES_TO_RADIANS) / (2 * PI)
99
- */
100
- const unitsPerDegreeX = worldSize / 360;
101
- const unitsPerDegreeY = unitsPerDegreeX / latCosine;
102
- /**
103
- * Number of pixels occupied by one meter around current lat/lon:
104
- */
105
- const altUnitsPerMeter = worldSize / EARTH_CIRCUMFERENCE / latCosine;
106
- /**
107
- * LngLat: longitude -> east and latitude -> north (bottom left)
108
- * UTM meter offset: x -> east and y -> north (bottom left)
109
- * World space: x -> east and y -> south (top left)
110
- *
111
- * Y needs to be flipped when converting delta degree/meter to delta pixels
112
- */
113
- const result = {
114
- unitsPerMeter: [altUnitsPerMeter, altUnitsPerMeter, altUnitsPerMeter],
115
- metersPerUnit: [1 / altUnitsPerMeter, 1 / altUnitsPerMeter, 1 / altUnitsPerMeter],
116
- unitsPerDegree: [unitsPerDegreeX, unitsPerDegreeY, altUnitsPerMeter],
117
- degreesPerUnit: [1 / unitsPerDegreeX, 1 / unitsPerDegreeY, 1 / altUnitsPerMeter]
118
- };
119
- /**
120
- * Taylor series 2nd order for 1/latCosine
121
- f'(a) * (x - a)
122
- = d(1/cos(lat * DEGREES_TO_RADIANS))/d(lat) * dLat
123
- = DEGREES_TO_RADIANS * tan(lat * DEGREES_TO_RADIANS) / cos(lat * DEGREES_TO_RADIANS) * dLat
124
- */
125
- if (highPrecision) {
126
- const latCosine2 = (DEGREES_TO_RADIANS * Math.tan(latitude * DEGREES_TO_RADIANS)) / latCosine;
127
- const unitsPerDegreeY2 = (unitsPerDegreeX * latCosine2) / 2;
128
- const altUnitsPerDegree2 = (worldSize / EARTH_CIRCUMFERENCE) * latCosine2;
129
- const altUnitsPerMeter2 = (altUnitsPerDegree2 / unitsPerDegreeY) * altUnitsPerMeter;
130
- result.unitsPerDegree2 = [0, unitsPerDegreeY2, altUnitsPerDegree2];
131
- result.unitsPerMeter2 = [altUnitsPerMeter2, 0, altUnitsPerMeter2];
132
- }
133
- // Main results, used for converting meters to latlng deltas and scaling offsets
134
- return result;
135
- }
136
- /**
137
- * Offset a lng/lat position by meterOffset (northing, easting)
138
- */
139
- export function addMetersToLngLat(lngLatZ, xyz) {
140
- const [longitude, latitude, z0] = lngLatZ;
141
- const [x, y, z] = xyz;
142
- const { unitsPerMeter, unitsPerMeter2 } = getDistanceScales({
143
- longitude,
144
- latitude,
145
- highPrecision: true
146
- });
147
- const worldspace = lngLatToWorld(lngLatZ);
148
- worldspace[0] += x * (unitsPerMeter[0] + unitsPerMeter2[0] * y);
149
- worldspace[1] += y * (unitsPerMeter[1] + unitsPerMeter2[1] * y);
150
- const newLngLat = worldToLngLat(worldspace);
151
- const newZ = (z0 || 0) + (z || 0);
152
- return Number.isFinite(z0) || Number.isFinite(z) ? [newLngLat[0], newLngLat[1], newZ] : newLngLat;
153
- }
154
- /**
155
- *
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(options) {
161
- const {
162
- // Viewport props
163
- height, pitch, bearing, altitude,
164
- // Pre-calculated parameters
165
- scale, center } = options;
166
- // VIEW MATRIX: PROJECTS MERCATOR WORLD COORDINATES
167
- // Note that mercator world coordinates typically need to be flipped
168
- //
169
- // Note: As usual, matrix operation orders should be read in reverse
170
- // since vectors will be multiplied from the right during transformation
171
- const vm = createMat4();
172
- // Move camera to altitude (along the pitch & bearing direction)
173
- mat4.translate(vm, vm, [0, 0, -altitude]);
174
- // Rotate by bearing, and then by pitch (which tilts the view)
175
- mat4.rotateX(vm, vm, -pitch * DEGREES_TO_RADIANS);
176
- mat4.rotateZ(vm, vm, bearing * DEGREES_TO_RADIANS);
177
- const relativeScale = scale / height;
178
- mat4.scale(vm, vm, [relativeScale, relativeScale, relativeScale]);
179
- if (center) {
180
- mat4.translate(vm, vm, vec3.negate([], center));
181
- }
182
- return vm;
183
- }
184
- /**
185
- * Calculates mapbox compatible projection matrix from parameters
186
- *
187
- * @param options.width Width of "viewport" or window
188
- * @param options.height Height of "viewport" or window
189
- * @param options.scale Scale at the current zoom
190
- * @param options.center Offset of the target, vec3 in world space
191
- * @param options.offset Offset of the focal point, vec2 in screen space
192
- * @param options.pitch Camera angle in degrees (0 is straight down)
193
- * @param options.fovy field of view in degrees
194
- * @param options.altitude if provided, field of view is calculated using `altitudeToFovy()`
195
- * @param options.nearZMultiplier control z buffer
196
- * @param options.farZMultiplier control z buffer
197
- * @returns project parameters object
198
- */
199
- export function getProjectionParameters(options) {
200
- const { width, height, altitude, pitch = 0, offset, center, scale, nearZMultiplier = 1, farZMultiplier = 1 } = options;
201
- let { fovy = altitudeToFovy(DEFAULT_ALTITUDE) } = options;
202
- // For back-compatibility allow field of view to be
203
- // derived from altitude
204
- if (altitude !== undefined) {
205
- fovy = altitudeToFovy(altitude);
206
- }
207
- const fovRadians = fovy * DEGREES_TO_RADIANS;
208
- const pitchRadians = pitch * DEGREES_TO_RADIANS;
209
- // Distance from camera to the target
210
- const focalDistance = fovyToAltitude(fovy);
211
- let cameraToSeaLevelDistance = focalDistance;
212
- if (center) {
213
- cameraToSeaLevelDistance += (center[2] * scale) / Math.cos(pitchRadians) / height;
214
- }
215
- const fovAboveCenter = fovRadians * (0.5 + (offset ? offset[1] : 0) / height);
216
- // Find the distance from the center point to the center top
217
- // in focal distance units using law of sines.
218
- const topHalfSurfaceDistance = (Math.sin(fovAboveCenter) * cameraToSeaLevelDistance) /
219
- Math.sin(clamp(Math.PI / 2 - pitchRadians - fovAboveCenter, 0.01, Math.PI - 0.01));
220
- // Calculate z distance of the farthest fragment that should be rendered.
221
- const furthestDistance = Math.sin(pitchRadians) * topHalfSurfaceDistance + cameraToSeaLevelDistance;
222
- // Matches mapbox limit
223
- const horizonDistance = cameraToSeaLevelDistance * 10;
224
- // Calculate z value of the farthest fragment that should be rendered.
225
- const farZ = Math.min(furthestDistance * farZMultiplier, horizonDistance);
226
- return {
227
- fov: fovRadians,
228
- aspect: width / height,
229
- focalDistance,
230
- near: nearZMultiplier,
231
- far: farZ
232
- };
233
- }
234
- /**
235
- * CALCULATE PROJECTION MATRIX: PROJECTS FROM CAMERA (VIEW) SPACE TO CLIPSPACE
236
- *
237
- * To match mapbox's z buffer:
238
- * - \<= 0.28: nearZMultiplier: 0.1, farZmultiplier: 1
239
- * - \>= 0.29: nearZMultiplier: 1 / height, farZMultiplier: 1.01
240
- *
241
- * @param options Viewport options
242
- * @param options.width Width of "viewport" or window
243
- * @param options.height Height of "viewport" or window
244
- * @param options.scale Scale at the current zoom
245
- * @param options.center Offset of the target, vec3 in world space
246
- * @param options.offset Offset of the focal point, vec2 in screen space
247
- * @param options.pitch Camera angle in degrees (0 is straight down)
248
- * @param options.fovy field of view in degrees
249
- * @param options.altitude if provided, field of view is calculated using `altitudeToFovy()`
250
- * @param options.nearZMultiplier control z buffer
251
- * @param options.farZMultiplier control z buffer
252
- * @returns 4x4 projection matrix
253
- */
254
- export function getProjectionMatrix(options) {
255
- const { fov, aspect, near, far } = getProjectionParameters(options);
256
- const projectionMatrix = mat4.perspective([], fov, // fov in radians
257
- aspect, // aspect ratio
258
- near, // near plane
259
- far // far plane
260
- );
261
- return projectionMatrix;
262
- }
263
- /**
264
- *
265
- * Convert an altitude to field of view such that the
266
- * focal distance is equal to the altitude
267
- *
268
- * @param altitude - altitude of camera in screen units
269
- * @return fovy field of view in degrees
270
- */
271
- export function altitudeToFovy(altitude) {
272
- return 2 * Math.atan(0.5 / altitude) * RADIANS_TO_DEGREES;
273
- }
274
- /**
275
- *
276
- * Convert an field of view such that the
277
- * focal distance is equal to the altitude
278
- *
279
- * @param fovy - field of view in degrees
280
- * @return altitude altitude of camera in screen units
281
- */
282
- export function fovyToAltitude(fovy) {
283
- return 0.5 / Math.tan(0.5 * fovy * DEGREES_TO_RADIANS);
284
- }
285
- // Project flat coordinates to pixels on screen.
286
- export function worldToPixels(xyz, pixelProjectionMatrix) {
287
- const [x, y, z = 0] = xyz;
288
- assert(Number.isFinite(x) && Number.isFinite(y) && Number.isFinite(z));
289
- return transformVector(pixelProjectionMatrix, [x, y, z, 1]);
290
- }
291
- /**
292
- * Unproject pixels on screen to flat coordinates.
293
- *
294
- * @param xyz - pixel coordinate on screen.
295
- * @param pixelUnprojectionMatrix - unprojection matrix 4x4
296
- * @param targetZ - if pixel coordinate does not have a 3rd component (depth),
297
- * targetZ is used as the elevation plane to unproject onto
298
- * @return [x, y, Z] flat coordinates on 512*512 Mercator Zoom 0 tile.
299
- */
300
- export function pixelsToWorld(xyz, pixelUnprojectionMatrix, targetZ = 0) {
301
- const [x, y, z] = xyz;
302
- assert(Number.isFinite(x) && Number.isFinite(y), 'invalid pixel coordinate');
303
- if (Number.isFinite(z)) {
304
- // Has depth component
305
- const coord = transformVector(pixelUnprojectionMatrix, [x, y, z, 1]);
306
- return coord;
307
- }
308
- // since we don't know the correct projected z value for the point,
309
- // unproject two points to get a line and then find the point on that line with z=0
310
- const coord0 = transformVector(pixelUnprojectionMatrix, [x, y, 0, 1]);
311
- const coord1 = transformVector(pixelUnprojectionMatrix, [x, y, 1, 1]);
312
- const z0 = coord0[2];
313
- const z1 = coord1[2];
314
- const t = z0 === z1 ? 0 : ((targetZ || 0) - z0) / (z1 - z0);
315
- return vec2.lerp([], coord0, coord1, t);
316
- }
@@ -1,277 +0,0 @@
1
- // View and Projection Matrix calculations for mapbox-js style map view properties
2
- import { createMat4 } from './math-utils';
3
- import { zoomToScale, pixelsToWorld, lngLatToWorld, worldToLngLat, worldToPixels, altitudeToFovy, fovyToAltitude, DEFAULT_ALTITUDE, getProjectionMatrix, getDistanceScales, getViewMatrix } from './web-mercator-utils';
4
- import fitBounds from './fit-bounds';
5
- import getBounds from './get-bounds';
6
- import * as mat4 from 'gl-matrix/mat4';
7
- import * as vec2 from 'gl-matrix/vec2';
8
- import * as vec3 from 'gl-matrix/vec3';
9
- /**
10
- * The WebMercatorViewport class creates
11
- * - view/projection matrices
12
- * - "uniform values" (for shaders) from mercator params
13
- *
14
- * Note: Instances are immutable in the sense that they only have accessors.
15
- * A new viewport instance should be created if any parameters have changed.
16
- */
17
- export default class WebMercatorViewport {
18
- /**
19
- * @classdesc
20
- * Creates view/projection matrices from mercator params
21
- * Note: The Viewport is immutable in the sense that it only has accessors.
22
- * A new viewport instance should be created if any parameters have changed.
23
- */
24
- // eslint-disable-next-line max-statements
25
- constructor(props = { width: 1, height: 1 }) {
26
- /** Two viewports are equal if width and height are identical, and if
27
- * their view and projection matrices are (approximately) equal.
28
- */
29
- this.equals = (viewport) => {
30
- if (!(viewport instanceof WebMercatorViewport)) {
31
- return false;
32
- }
33
- return (viewport.width === this.width &&
34
- viewport.height === this.height &&
35
- mat4.equals(viewport.projectionMatrix, this.projectionMatrix) &&
36
- mat4.equals(viewport.viewMatrix, this.viewMatrix));
37
- };
38
- /**
39
- * Projects xyz (possibly latitude and longitude) to pixel coordinates in window
40
- * using viewport projection parameters
41
- * - [longitude, latitude] to [x, y]
42
- * - [longitude, latitude, Z] => [x, y, z]
43
- * Note: By default, returns top-left coordinates for canvas/SVG type render
44
- *
45
- * @param lngLatZ - [lng, lat] or [lng, lat, Z]
46
- * @param options - options
47
- * @param options.topLeft=true - Whether projected coords are top left
48
- * @return - screen coordinates [x, y] or [x, y, z], z as pixel depth
49
- */
50
- this.project = (lngLatZ, options = {}) => {
51
- const { topLeft = true } = options;
52
- const worldPosition = this.projectPosition(lngLatZ);
53
- const coord = worldToPixels(worldPosition, this.pixelProjectionMatrix);
54
- const [x, y] = coord;
55
- const y2 = topLeft ? y : this.height - y;
56
- return lngLatZ.length === 2 ? [x, y2] : [x, y2, coord[2]];
57
- };
58
- /**
59
- * Unproject pixel coordinates on screen onto world coordinates, possibly `[lon, lat]` on map.
60
- *
61
- * - [x, y] => [lng, lat]
62
- * - [x, y, z] => [lng, lat, Z]
63
- *
64
- * @param xyz - screen coordinates, z as pixel depth
65
- * @param options - options
66
- * @param options.topLeft=true - Whether projected coords are top left
67
- * @param options.targetZ=0 - If pixel depth is unknown, targetZ is used as
68
- * the elevation plane to unproject onto
69
- * @return - [lng, lat, Z] or [X, Y, Z]
70
- */
71
- this.unproject = (xyz, options = {}) => {
72
- const { topLeft = true, targetZ = undefined } = options;
73
- const [x, y, z] = xyz;
74
- const y2 = topLeft ? y : this.height - y;
75
- const targetZWorld = targetZ && targetZ * this.distanceScales.unitsPerMeter[2];
76
- const coord = pixelsToWorld([x, y2, z], this.pixelUnprojectionMatrix, targetZWorld);
77
- const [X, Y, Z] = this.unprojectPosition(coord);
78
- if (Number.isFinite(z)) {
79
- return [X, Y, Z];
80
- }
81
- return Number.isFinite(targetZ) ? [X, Y, targetZ] : [X, Y];
82
- };
83
- // NON_LINEAR PROJECTION HOOKS
84
- // Used for web meractor projection
85
- this.projectPosition = (xyz) => {
86
- const [X, Y] = lngLatToWorld(xyz);
87
- const Z = (xyz[2] || 0) * this.distanceScales.unitsPerMeter[2];
88
- return [X, Y, Z];
89
- };
90
- this.unprojectPosition = (xyz) => {
91
- const [X, Y] = worldToLngLat(xyz);
92
- const Z = (xyz[2] || 0) * this.distanceScales.metersPerUnit[2];
93
- return [X, Y, Z];
94
- };
95
- let {
96
- // Map state
97
- width, height, altitude = null, fovy = null } = props;
98
- const { latitude = 0, longitude = 0, zoom = 0, pitch = 0, bearing = 0, position = null, nearZMultiplier = 0.02, farZMultiplier = 1.01 } = props;
99
- // Silently allow apps to send in 0,0 to facilitate isomorphic render etc
100
- width = width || 1;
101
- height = height || 1;
102
- // `fovy` & `altitude` are independent parameters, one for the
103
- // projection and the latter for the view matrix. In the past,
104
- // the `fovy` was always derived from the `altitude`
105
- if (fovy === null && altitude === null) {
106
- altitude = DEFAULT_ALTITUDE;
107
- fovy = altitudeToFovy(altitude);
108
- }
109
- else if (fovy === null) {
110
- fovy = altitudeToFovy(altitude);
111
- }
112
- else if (altitude === null) {
113
- altitude = fovyToAltitude(fovy);
114
- }
115
- const scale = zoomToScale(zoom);
116
- // Altitude - prevent division by 0
117
- // TODO - just throw an Error instead?
118
- altitude = Math.max(0.75, altitude);
119
- const distanceScales = getDistanceScales({ longitude, latitude });
120
- const center = lngLatToWorld([longitude, latitude]);
121
- center.push(0);
122
- if (position) {
123
- vec3.add(center, center, vec3.mul([], position, distanceScales.unitsPerMeter));
124
- }
125
- this.projectionMatrix = getProjectionMatrix({
126
- width,
127
- height,
128
- scale,
129
- center,
130
- pitch,
131
- fovy,
132
- nearZMultiplier,
133
- farZMultiplier
134
- });
135
- this.viewMatrix = getViewMatrix({
136
- height,
137
- scale,
138
- center,
139
- pitch,
140
- bearing,
141
- altitude
142
- });
143
- // Save parameters
144
- this.width = width;
145
- this.height = height;
146
- this.scale = scale;
147
- this.latitude = latitude;
148
- this.longitude = longitude;
149
- this.zoom = zoom;
150
- this.pitch = pitch;
151
- this.bearing = bearing;
152
- this.altitude = altitude;
153
- this.fovy = fovy;
154
- this.center = center;
155
- this.meterOffset = position || [0, 0, 0];
156
- this.distanceScales = distanceScales;
157
- this._initMatrices();
158
- Object.freeze(this);
159
- }
160
- _initMatrices() {
161
- const { width, height, projectionMatrix, viewMatrix } = this;
162
- // Note: As usual, matrix operations should be applied in "reverse" order
163
- // since vectors will be multiplied in from the right during transformation
164
- const vpm = createMat4();
165
- mat4.multiply(vpm, vpm, projectionMatrix);
166
- mat4.multiply(vpm, vpm, viewMatrix);
167
- this.viewProjectionMatrix = vpm;
168
- // Calculate matrices and scales needed for projection
169
- /**
170
- * Builds matrices that converts preprojected lngLats to screen pixels
171
- * and vice versa.
172
- * Note: Currently returns bottom-left coordinates!
173
- * Note: Starts with the GL projection matrix and adds steps to the
174
- * scale and translate that matrix onto the window.
175
- * Note: WebGL controls clip space to screen projection with gl.viewport
176
- * and does not need this step.
177
- */
178
- const m = createMat4();
179
- // matrix for conversion from location to screen coordinates
180
- mat4.scale(m, m, [width / 2, -height / 2, 1]);
181
- mat4.translate(m, m, [1, -1, 0]);
182
- mat4.multiply(m, m, vpm);
183
- const mInverse = mat4.invert(createMat4(), m);
184
- if (!mInverse) {
185
- throw new Error('Pixel project matrix not invertible');
186
- }
187
- this.pixelProjectionMatrix = m;
188
- this.pixelUnprojectionMatrix = mInverse;
189
- }
190
- /**
191
- * Project [lng,lat] on sphere onto [x,y] on 512*512 Mercator Zoom 0 tile.
192
- * Performs the nonlinear part of the web mercator projection.
193
- * Remaining projection is done with 4x4 matrices which also handles
194
- * perspective.
195
- *
196
- * @param lngLat - [lng, lat] coordinates
197
- * Specifies a point on the sphere to project onto the map.
198
- * @return [x,y] coordinates.
199
- */
200
- projectFlat(lngLat) {
201
- return lngLatToWorld(lngLat);
202
- }
203
- /**
204
- * Unproject world point [x,y] on map onto {lat, lon} on sphere
205
- *
206
- * @param xy - array with [x,y] members
207
- * representing point on projected map plane
208
- * @return - array with [lat,lon] of point on sphere.
209
- * Has toArray method if you need a GeoJSON Array.
210
- * Per cartographic tradition, lat and lon are specified as degrees.
211
- */
212
- unprojectFlat(xy) {
213
- return worldToLngLat(xy);
214
- }
215
- /**
216
- * Get the map center that place a given [lng, lat] coordinate at screen point [x, y]
217
- * @param opt
218
- * @param opt.lngLat - [lng,lat] coordinates
219
- * Specifies a point on the sphere.
220
- * @param opt.pos - [x,y] coordinates
221
- * Specifies a point on the screen.
222
- * @return [lng,lat] new map center.
223
- */
224
- getMapCenterByLngLatPosition({ lngLat, pos }) {
225
- const fromLocation = pixelsToWorld(pos, this.pixelUnprojectionMatrix);
226
- const toLocation = lngLatToWorld(lngLat);
227
- const translate = vec2.add([], toLocation, vec2.negate([], fromLocation));
228
- const newCenter = vec2.add([], this.center, translate);
229
- return worldToLngLat(newCenter);
230
- }
231
- /**
232
- * Returns a new viewport that fit around the given rectangle.
233
- * Only supports non-perspective mode.
234
- * @param bounds - [[lon, lat], [lon, lat]]
235
- * @param [options]
236
- * @param [options.padding] - The amount of padding in pixels to add to the given bounds.
237
- * @param [options.offset] - The center of the given bounds relative to the map's center,
238
- * [x, y] measured in pixels.
239
- * @returns {WebMercatorViewport}
240
- */
241
- fitBounds(bounds, options = {}) {
242
- const { width, height } = this;
243
- const { longitude, latitude, zoom } = fitBounds(Object.assign({ width, height, bounds }, options));
244
- return new WebMercatorViewport({ width, height, longitude, latitude, zoom });
245
- }
246
- /**
247
- * Returns the bounding box of the viewport.
248
- * @param [options]
249
- * @param [options.z] - The altitude at which the bounds should be calculated.
250
- * @returns {Array} bounds - [[lon, lat], [lon, lat]]
251
- */
252
- getBounds(options) {
253
- const corners = this.getBoundingRegion(options);
254
- const west = Math.min(...corners.map((p) => p[0]));
255
- const east = Math.max(...corners.map((p) => p[0]));
256
- const south = Math.min(...corners.map((p) => p[1]));
257
- const north = Math.max(...corners.map((p) => p[1]));
258
- return [
259
- [west, south],
260
- [east, north]
261
- ];
262
- }
263
- /**
264
- * Returns the bounding box of the viewport.
265
- * @param [options]
266
- * @param [options.z] - The altitude at which the bounds should be calculated.
267
- * @returns {Array} an array of 4 points that define the visible region
268
- */
269
- getBoundingRegion(options = {}) {
270
- return getBounds(this, options.z || 0);
271
- }
272
- // DEPRECATED
273
- /** @deprecated Legacy method name */
274
- getLocationAtPoint({ lngLat, pos }) {
275
- return this.getMapCenterByLngLatPosition({ lngLat, pos });
276
- }
277
- }