File: //home/cafsindia/snap.cafsinfotech.in/node_modules/mapbox-gl/dist/mapbox-gl-csp-worker.js.map
{"version":3,"file":"mapbox-gl-csp-worker.js","sources":["../node_modules/@mapbox/unitbezier/index.js","../node_modules/@mapbox/point-geometry/index.js","../src/util/browser/window.js","../src/util/util.js","../node_modules/grid-index/grid-index.js","../node_modules/csscolorparser/csscolorparser.js","../src/style-spec/util/color.js","../src/style-spec/util/extend.js","../src/style-spec/expression/parsing_error.js","../src/style-spec/expression/scope.js","../src/style-spec/expression/types.js","../src/style-spec/expression/types/collator.js","../src/style-spec/expression/types/formatted.js","../src/style-spec/expression/types/resolved_image.js","../src/style-spec/expression/values.js","../src/style-spec/expression/definitions/literal.js","../src/style-spec/expression/runtime_error.js","../src/style-spec/expression/definitions/assertion.js","../src/style-spec/expression/definitions/format.js","../src/style-spec/expression/definitions/image.js","../src/style-spec/expression/definitions/coercion.js","../src/style-spec/expression/evaluation_context.js","../src/style-spec/expression/compound_expression.js","../src/style-spec/expression/definitions/collator.js","../src/style-spec/expression/definitions/within.js","../src/style-spec/expression/is_constant.js","../src/style-spec/expression/definitions/var.js","../src/style-spec/expression/parsing_context.js","../src/style-spec/expression/stops.js","../src/style-spec/expression/definitions/step.js","../src/style-spec/util/interpolate.js","../src/style-spec/util/color_spaces.js","../src/style-spec/expression/definitions/interpolate.js","../src/style-spec/expression/definitions/coalesce.js","../src/style-spec/expression/definitions/let.js","../src/style-spec/expression/definitions/at.js","../src/style-spec/expression/definitions/in.js","../src/style-spec/expression/definitions/index_of.js","../src/style-spec/expression/definitions/match.js","../src/style-spec/expression/definitions/case.js","../src/style-spec/expression/definitions/slice.js","../src/style-spec/expression/definitions/comparison.js","../src/style-spec/expression/definitions/number_format.js","../src/style-spec/expression/definitions/length.js","../src/style-spec/expression/definitions/index.js","../src/style-spec/util/result.js","../src/style-spec/util/properties.js","../src/style-spec/util/get_type.js","../src/style-spec/function/index.js","../src/style-spec/expression/index.js","../src/util/config.js","../src/util/webp_supported.js","../src/util/live_performance.js","../src/util/mapbox.js","../src/util/sku_token.js","../src/util/tile_request_cache.js","../src/util/ajax.js","../src/util/web_worker_transfer.js","../src/util/throttled_invoker.js","../src/util/performance.js","../src/util/scheduler.js","../src/util/actor.js","../src/util/evented.js","../src/style-spec/util/unbundle_jsonlint.js","../src/style-spec/error/validation_error.js","../src/style-spec/validate/validate_object.js","../src/style-spec/validate/validate_array.js","../src/style-spec/validate/validate_number.js","../src/style-spec/validate/validate_function.js","../src/style-spec/validate/validate_expression.js","../src/style-spec/validate/validate_enum.js","../src/style-spec/feature_filter/index.js","../src/style-spec/validate/validate_filter.js","../src/style-spec/validate/validate_property.js","../src/style-spec/validate/validate_paint_property.js","../src/style-spec/validate/validate_layout_property.js","../src/style-spec/validate/validate_string.js","../src/style-spec/validate/validate_source.js","../src/style-spec/validate/validate.js","../src/style-spec/validate/validate_boolean.js","../src/style-spec/validate/validate_color.js","../src/style-spec/validate/validate_layer.js","../src/style-spec/validate/validate_light.js","../src/style-spec/validate/validate_terrain.js","../src/style-spec/validate/validate_fog.js","../src/style-spec/validate/validate_formatted.js","../src/style-spec/validate/validate_image.js","../src/style-spec/validate/validate_projection.js","../src/style-spec/validate/validate_glyphs_url.js","../src/style-spec/validate_style.min.js","../src/util/is_char_in_unicode_block.js","../src/util/script_detection.js","../src/util/browser.js","../src/source/rtl_text_plugin.js","../src/style/evaluation_parameters.js","../src/style/properties.js","../src/shaders/encode_attribute.js","../src/util/struct_array.js","../src/data/array_types.js","../src/data/bucket/pattern_attributes.js","../src/data/bucket/dash_attributes.js","../node_modules/murmurhash-js/murmurhash3_gc.js","../node_modules/murmurhash-js/murmurhash2_gc.js","../node_modules/murmurhash-js/index.js","../src/data/feature_position_map.js","../src/render/uniform_binding.js","../src/data/program_configuration.js","../src/style/style_layer.js","../src/style/validate_style.js","../src/data/bucket/circle_attributes.js","../src/data/segment.js","../src/data/extent.js","../src/geo/lng_lat_bounds.js","../node_modules/gl-matrix/esm/common.js","../node_modules/gl-matrix/esm/mat4.js","../node_modules/gl-matrix/esm/vec3.js","../node_modules/gl-matrix/esm/mat3.js","../node_modules/gl-matrix/esm/vec4.js","../node_modules/gl-matrix/esm/quat.js","../src/terrain/globe_attributes.js","../src/data/pos_attributes.js","../src/util/primitives.js","../src/geo/projection/globe_util.js","../src/geo/lng_lat.js","../src/geo/mercator_coordinate.js","../src/geo/projection/resample.js","../src/data/load_geometry.js","../src/data/evaluation_feature.js","../src/data/bucket/circle_bucket.js","../src/util/intersection_tests.js","../src/style/query_utils.js","../src/style/style_layer/circle_style_layer_properties.js","../src/style/style_layer/circle_style_layer.js","../src/data/bucket/heatmap_bucket.js","../src/util/image.js","../src/style/style_layer/heatmap_style_layer_properties.js","../src/util/color_ramp.js","../src/style/style_layer/hillshade_style_layer_properties.js","../src/data/bucket/fill_attributes.js","../node_modules/earcut/src/earcut.js","../node_modules/quickselect/index.js","../src/util/classify_rings.js","../src/data/bucket/pattern_bucket_features.js","../src/data/bucket/fill_bucket.js","../src/style/style_layer/fill_style_layer_properties.js","../src/data/bucket/fill_extrusion_attributes.js","../node_modules/@mapbox/vector-tile/lib/vectortilefeature.js","../node_modules/@mapbox/vector-tile/lib/vectortilelayer.js","../node_modules/@mapbox/vector-tile/lib/vectortile.js","../node_modules/@mapbox/vector-tile/index.js","../src/util/polygon_clipping.js","../src/data/bucket/fill_extrusion_bucket.js","../src/style/style_layer/fill_extrusion_style_layer_properties.js","../node_modules/@mapbox/whoots-js/index.mjs","../src/source/tile_id.js","../src/style/style_layer/fill_extrusion_style_layer.js","../src/data/bucket/line_attributes.js","../src/data/bucket/line_attributes_ext.js","../src/data/bucket/line_bucket.js","../src/style/style_layer/line_style_layer_properties.js","../src/style/style_layer/line_style_layer.js","../src/data/bucket/symbol_attributes.js","../src/symbol/one_em.js","../src/symbol/symbol_size.js","../src/symbol/transform_text.js","../src/util/verticalize_punctuation.js","../node_modules/pbf/index.js","../node_modules/ieee754/index.js","../src/style/parse_glyph_pbf.js","../node_modules/potpack/index.js","../src/render/image_atlas.js","../src/symbol/shaping.js","../src/symbol/anchor.js","../src/symbol/check_max_angle.js","../src/symbol/get_anchors.js","../src/render/glyph_manager.js","../src/symbol/quads.js","../node_modules/tinyqueue/index.js","../src/util/find_pole_of_inaccessibility.js","../src/symbol/symbol_layout.js","../src/symbol/clip_line.js","../src/geo/projection/far_z.js","../src/geo/projection/tile_transform.js","../src/geo/projection/projection.js","../src/geo/projection/albers.js","../src/geo/projection/equal_earth.js","../src/geo/projection/equirectangular.js","../src/geo/projection/lambert.js","../src/geo/projection/mercator.js","../src/geo/projection/natural_earth.js","../src/geo/projection/winkel_tripel.js","../src/geo/projection/cylindrical_equal_area.js","../src/geo/projection/globe.js","../src/geo/projection/index.js","../src/data/bucket/symbol_bucket.js","../src/symbol/mergelines.js","../src/style/style_layer/symbol_style_layer_properties.js","../src/style/format_section_override.js","../src/style/style_layer/symbol_style_layer.js","../src/util/resolve_tokens.js","../src/style/style_layer/background_style_layer_properties.js","../src/style/style_layer/raster_style_layer_properties.js","../src/style/style_layer/custom_style_layer.js","../src/style/style_layer/sky_style_layer_properties.js","../src/style/style_layer/sky_style_layer.js","../src/style/create_style_layer.js","../src/style/style_layer/heatmap_style_layer.js","../src/style/style_layer/hillshade_style_layer.js","../src/style/style_layer/fill_style_layer.js","../src/style/style_layer/background_style_layer.js","../src/style/style_layer/raster_style_layer.js","../src/style-spec/util/ref_properties.js","../src/style-spec/group_by_layout.js","../src/style/style_layer_index.js","../src/util/dictionary_coder.js","../src/util/vectortile_to_geojson.js","../src/render/texture.js","../src/source/tile_mesh.js","../src/data/bounds_attributes.js","../src/source/tile.js","../src/data/bucket.js","../src/source/source_state.js","../src/data/dem_tree.js","../src/data/dem_data.js","../src/source/tile_cache.js","../src/gl/color_mode.js","../src/source/source_cache.js","../src/terrain/elevation.js","../src/data/feature_index.js","../src/render/line_atlas.js","../src/render/glyph_atlas.js","../src/source/worker_tile.js","../src/source/vector_tile_worker_source.js","../src/source/raster_dem_tile_worker_source.js","../node_modules/@mapbox/geojson-rewind/index.js","../src/source/geojson_wrapper.js","../node_modules/vt-pbf/lib/geojson_wrapper.js","../node_modules/vt-pbf/index.js","../node_modules/kdbush/index.js","../node_modules/supercluster/index.js","../node_modules/geojson-vt/src/simplify.js","../node_modules/geojson-vt/src/feature.js","../node_modules/geojson-vt/src/convert.js","../node_modules/geojson-vt/src/clip.js","../node_modules/geojson-vt/src/wrap.js","../node_modules/geojson-vt/src/transform.js","../node_modules/geojson-vt/src/tile.js","../node_modules/geojson-vt/src/index.js","../src/source/geojson_worker_source.js","../src/source/worker.js"],"sourcesContent":["'use strict';\n\nmodule.exports = UnitBezier;\n\nfunction UnitBezier(p1x, p1y, p2x, p2y) {\n // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).\n this.cx = 3.0 * p1x;\n this.bx = 3.0 * (p2x - p1x) - this.cx;\n this.ax = 1.0 - this.cx - this.bx;\n\n this.cy = 3.0 * p1y;\n this.by = 3.0 * (p2y - p1y) - this.cy;\n this.ay = 1.0 - this.cy - this.by;\n\n this.p1x = p1x;\n this.p1y = p1y;\n this.p2x = p2x;\n this.p2y = p2y;\n}\n\nUnitBezier.prototype = {\n sampleCurveX: function (t) {\n // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.\n return ((this.ax * t + this.bx) * t + this.cx) * t;\n },\n\n sampleCurveY: function (t) {\n return ((this.ay * t + this.by) * t + this.cy) * t;\n },\n\n sampleCurveDerivativeX: function (t) {\n return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;\n },\n\n solveCurveX: function (x, epsilon) {\n if (epsilon === undefined) epsilon = 1e-6;\n\n if (x < 0.0) return 0.0;\n if (x > 1.0) return 1.0;\n\n var t = x;\n\n // First try a few iterations of Newton's method - normally very fast.\n for (var i = 0; i < 8; i++) {\n var x2 = this.sampleCurveX(t) - x;\n if (Math.abs(x2) < epsilon) return t;\n\n var d2 = this.sampleCurveDerivativeX(t);\n if (Math.abs(d2) < 1e-6) break;\n\n t = t - x2 / d2;\n }\n\n // Fall back to the bisection method for reliability.\n var t0 = 0.0;\n var t1 = 1.0;\n t = x;\n\n for (i = 0; i < 20; i++) {\n x2 = this.sampleCurveX(t);\n if (Math.abs(x2 - x) < epsilon) break;\n\n if (x > x2) {\n t0 = t;\n } else {\n t1 = t;\n }\n\n t = (t1 - t0) * 0.5 + t0;\n }\n\n return t;\n },\n\n solve: function (x, epsilon) {\n return this.sampleCurveY(this.solveCurveX(x, epsilon));\n }\n};\n","'use strict';\n\nmodule.exports = Point;\n\n/**\n * A standalone point geometry with useful accessor, comparison, and\n * modification methods.\n *\n * @class Point\n * @param {Number} x the x-coordinate. this could be longitude or screen\n * pixels, or any other sort of unit.\n * @param {Number} y the y-coordinate. this could be latitude or screen\n * pixels, or any other sort of unit.\n * @example\n * var point = new Point(-77, 38);\n */\nfunction Point(x, y) {\n this.x = x;\n this.y = y;\n}\n\nPoint.prototype = {\n\n /**\n * Clone this point, returning a new point that can be modified\n * without affecting the old one.\n * @return {Point} the clone\n */\n clone: function() { return new Point(this.x, this.y); },\n\n /**\n * Add this point's x & y coordinates to another point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n add: function(p) { return this.clone()._add(p); },\n\n /**\n * Subtract this point's x & y coordinates to from point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n sub: function(p) { return this.clone()._sub(p); },\n\n /**\n * Multiply this point's x & y coordinates by point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n multByPoint: function(p) { return this.clone()._multByPoint(p); },\n\n /**\n * Divide this point's x & y coordinates by point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n divByPoint: function(p) { return this.clone()._divByPoint(p); },\n\n /**\n * Multiply this point's x & y coordinates by a factor,\n * yielding a new point.\n * @param {Point} k factor\n * @return {Point} output point\n */\n mult: function(k) { return this.clone()._mult(k); },\n\n /**\n * Divide this point's x & y coordinates by a factor,\n * yielding a new point.\n * @param {Point} k factor\n * @return {Point} output point\n */\n div: function(k) { return this.clone()._div(k); },\n\n /**\n * Rotate this point around the 0, 0 origin by an angle a,\n * given in radians\n * @param {Number} a angle to rotate around, in radians\n * @return {Point} output point\n */\n rotate: function(a) { return this.clone()._rotate(a); },\n\n /**\n * Rotate this point around p point by an angle a,\n * given in radians\n * @param {Number} a angle to rotate around, in radians\n * @param {Point} p Point to rotate around\n * @return {Point} output point\n */\n rotateAround: function(a,p) { return this.clone()._rotateAround(a,p); },\n\n /**\n * Multiply this point by a 4x1 transformation matrix\n * @param {Array<Number>} m transformation matrix\n * @return {Point} output point\n */\n matMult: function(m) { return this.clone()._matMult(m); },\n\n /**\n * Calculate this point but as a unit vector from 0, 0, meaning\n * that the distance from the resulting point to the 0, 0\n * coordinate will be equal to 1 and the angle from the resulting\n * point to the 0, 0 coordinate will be the same as before.\n * @return {Point} unit vector point\n */\n unit: function() { return this.clone()._unit(); },\n\n /**\n * Compute a perpendicular point, where the new y coordinate\n * is the old x coordinate and the new x coordinate is the old y\n * coordinate multiplied by -1\n * @return {Point} perpendicular point\n */\n perp: function() { return this.clone()._perp(); },\n\n /**\n * Return a version of this point with the x & y coordinates\n * rounded to integers.\n * @return {Point} rounded point\n */\n round: function() { return this.clone()._round(); },\n\n /**\n * Return the magitude of this point: this is the Euclidean\n * distance from the 0, 0 coordinate to this point's x and y\n * coordinates.\n * @return {Number} magnitude\n */\n mag: function() {\n return Math.sqrt(this.x * this.x + this.y * this.y);\n },\n\n /**\n * Judge whether this point is equal to another point, returning\n * true or false.\n * @param {Point} other the other point\n * @return {boolean} whether the points are equal\n */\n equals: function(other) {\n return this.x === other.x &&\n this.y === other.y;\n },\n\n /**\n * Calculate the distance from this point to another point\n * @param {Point} p the other point\n * @return {Number} distance\n */\n dist: function(p) {\n return Math.sqrt(this.distSqr(p));\n },\n\n /**\n * Calculate the distance from this point to another point,\n * without the square root step. Useful if you're comparing\n * relative distances.\n * @param {Point} p the other point\n * @return {Number} distance\n */\n distSqr: function(p) {\n var dx = p.x - this.x,\n dy = p.y - this.y;\n return dx * dx + dy * dy;\n },\n\n /**\n * Get the angle from the 0, 0 coordinate to this point, in radians\n * coordinates.\n * @return {Number} angle\n */\n angle: function() {\n return Math.atan2(this.y, this.x);\n },\n\n /**\n * Get the angle from this point to another point, in radians\n * @param {Point} b the other point\n * @return {Number} angle\n */\n angleTo: function(b) {\n return Math.atan2(this.y - b.y, this.x - b.x);\n },\n\n /**\n * Get the angle between this point and another point, in radians\n * @param {Point} b the other point\n * @return {Number} angle\n */\n angleWith: function(b) {\n return this.angleWithSep(b.x, b.y);\n },\n\n /*\n * Find the angle of the two vectors, solving the formula for\n * the cross product a x b = |a||b|sin(θ) for θ.\n * @param {Number} x the x-coordinate\n * @param {Number} y the y-coordinate\n * @return {Number} the angle in radians\n */\n angleWithSep: function(x, y) {\n return Math.atan2(\n this.x * y - this.y * x,\n this.x * x + this.y * y);\n },\n\n _matMult: function(m) {\n var x = m[0] * this.x + m[1] * this.y,\n y = m[2] * this.x + m[3] * this.y;\n this.x = x;\n this.y = y;\n return this;\n },\n\n _add: function(p) {\n this.x += p.x;\n this.y += p.y;\n return this;\n },\n\n _sub: function(p) {\n this.x -= p.x;\n this.y -= p.y;\n return this;\n },\n\n _mult: function(k) {\n this.x *= k;\n this.y *= k;\n return this;\n },\n\n _div: function(k) {\n this.x /= k;\n this.y /= k;\n return this;\n },\n\n _multByPoint: function(p) {\n this.x *= p.x;\n this.y *= p.y;\n return this;\n },\n\n _divByPoint: function(p) {\n this.x /= p.x;\n this.y /= p.y;\n return this;\n },\n\n _unit: function() {\n this._div(this.mag());\n return this;\n },\n\n _perp: function() {\n var y = this.y;\n this.y = this.x;\n this.x = -y;\n return this;\n },\n\n _rotate: function(angle) {\n var cos = Math.cos(angle),\n sin = Math.sin(angle),\n x = cos * this.x - sin * this.y,\n y = sin * this.x + cos * this.y;\n this.x = x;\n this.y = y;\n return this;\n },\n\n _rotateAround: function(angle, p) {\n var cos = Math.cos(angle),\n sin = Math.sin(angle),\n x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y),\n y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y);\n this.x = x;\n this.y = y;\n return this;\n },\n\n _round: function() {\n this.x = Math.round(this.x);\n this.y = Math.round(this.y);\n return this;\n }\n};\n\n/**\n * Construct a point from an array if necessary, otherwise if the input\n * is already a Point, or an unknown type, return it unchanged\n * @param {Array<Number>|Point|*} a any kind of input value\n * @return {Point} constructed point, or passed-through value.\n * @example\n * // this\n * var point = Point.convert([0, 1]);\n * // is equivalent to\n * var point = new Point(0, 1);\n */\nPoint.convert = function (a) {\n if (a instanceof Point) {\n return a;\n }\n if (Array.isArray(a)) {\n return new Point(a[0], a[1]);\n }\n return a;\n};\n","// @flow\n/* eslint-env browser */\nimport type {Window} from '../../types/window.js';\n\n// shim window for the case of requiring the browser bundle in Node\nexport default ((typeof self !== 'undefined' ? self : ({}: any)): Window);\n","// @flow\n\nimport UnitBezier from '@mapbox/unitbezier';\n\nimport Point from '@mapbox/point-geometry';\nimport window from './window.js';\nimport assert from 'assert';\n\nimport type {Callback} from '../types/callback.js';\nimport type {Mat4, Vec4} from 'gl-matrix';\n\nconst DEG_TO_RAD = Math.PI / 180;\nconst RAD_TO_DEG = 180 / Math.PI;\n\n/**\n * Converts an angle in degrees to radians\n * copy all properties from the source objects into the destination.\n * The last source object given overrides properties from previous\n * source objects.\n *\n * @param a angle to convert\n * @returns the angle in radians\n * @private\n */\nexport function degToRad(a: number): number {\n return a * DEG_TO_RAD;\n}\n\n/**\n * Converts an angle in radians to degrees\n * copy all properties from the source objects into the destination.\n * The last source object given overrides properties from previous\n * source objects.\n *\n * @param a angle to convert\n * @returns the angle in degrees\n * @private\n */\nexport function radToDeg(a: number): number {\n return a * RAD_TO_DEG;\n}\n\nconst TILE_CORNERS = [[0, 0], [1, 0], [1, 1], [0, 1]];\n\n/**\n * Given a particular bearing, returns the corner of the tile thats farthest\n * along the bearing.\n *\n * @param {number} bearing angle in degrees (-180, 180]\n * @returns {QuadCorner}\n * @private\n */\nexport function furthestTileCorner(bearing: number): [number, number] {\n const alignedBearing = ((bearing + 45) + 360) % 360;\n const cornerIdx = Math.round(alignedBearing / 90) % 4;\n return TILE_CORNERS[cornerIdx];\n}\n\n/**\n * @module util\n * @private\n */\n\n/**\n * Given a value `t` that varies between 0 and 1, return\n * an interpolation function that eases between 0 and 1 in a pleasing\n * cubic in-out fashion.\n *\n * @private\n */\nexport function easeCubicInOut(t: number): number {\n if (t <= 0) return 0;\n if (t >= 1) return 1;\n const t2 = t * t,\n t3 = t2 * t;\n return 4 * (t < 0.5 ? t3 : 3 * (t - t2) + t3 - 0.75);\n}\n\n/**\n * Computes an AABB for a set of points.\n *\n * @param {Point[]} points\n * @returns {{ min: Point, max: Point}}\n * @private\n */\nexport function getBounds(points: Point[]): { min: Point, max: Point} {\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const p of points) {\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x);\n maxY = Math.max(maxY, p.y);\n }\n\n return {\n min: new Point(minX, minY),\n max: new Point(maxX, maxY),\n };\n}\n\n/**\n * Returns the square of the 2D distance between an AABB defined by min and max and a point.\n * If point is null or undefined, the AABB distance from the origin (0,0) is returned.\n *\n * @param {Array<number>} min The minimum extent of the AABB.\n * @param {Array<number>} max The maximum extent of the AABB.\n * @param {Array<number>} [point] The point to compute the distance from, may be undefined.\n * @returns {number} The square distance from the AABB, 0.0 if the AABB contains the point.\n */\nexport function getAABBPointSquareDist(min: Array<number>, max: Array<number>, point: ?Array<number>): number {\n let sqDist = 0.0;\n\n for (let i = 0; i < 2; ++i) {\n const v = point ? point[i] : 0.0;\n assert(min[i] < max[i], 'Invalid aabb min and max inputs, min[i] must be < max[i].');\n if (min[i] > v) sqDist += (min[i] - v) * (min[i] - v);\n if (max[i] < v) sqDist += (v - max[i]) * (v - max[i]);\n }\n\n return sqDist;\n}\n\n/**\n * Converts a AABB into a polygon with clockwise winding order.\n *\n * @param {Point} min The top left point.\n * @param {Point} max The bottom right point.\n * @param {number} [buffer=0] The buffer width.\n * @param {boolean} [close=true] Whether to close the polygon or not.\n * @returns {Point[]} The polygon.\n */\nexport function polygonizeBounds(min: Point, max: Point, buffer: number = 0, close: boolean = true): Point[] {\n const offset = new Point(buffer, buffer);\n const minBuf = min.sub(offset);\n const maxBuf = max.add(offset);\n const polygon = [minBuf, new Point(maxBuf.x, minBuf.y), maxBuf, new Point(minBuf.x, maxBuf.y)];\n\n if (close) {\n polygon.push(minBuf.clone());\n }\n return polygon;\n}\n\n/**\n * Takes a convex ring and expands it outward by applying a buffer around it.\n * This function assumes that the ring is in clockwise winding order.\n *\n * @param {Point[]} ring The input ring.\n * @param {number} buffer The buffer width.\n * @returns {Point[]} The expanded ring.\n */\nexport function bufferConvexPolygon(ring: Point[], buffer: number): Point[] {\n assert(ring.length > 2, 'bufferConvexPolygon requires the ring to have atleast 3 points');\n const output = [];\n for (let currIdx = 0; currIdx < ring.length; currIdx++) {\n const prevIdx = wrap(currIdx - 1, -1, ring.length - 1);\n const nextIdx = wrap(currIdx + 1, -1, ring.length - 1);\n const prev = ring[prevIdx];\n const curr = ring[currIdx];\n const next = ring[nextIdx];\n const p1 = prev.sub(curr).unit();\n const p2 = next.sub(curr).unit();\n const interiorAngle = p2.angleWithSep(p1.x, p1.y);\n // Calcuate a vector that points in the direction of the angle bisector between two sides.\n // Scale it based on a right angled triangle constructed at that corner.\n const offset = p1.add(p2).unit().mult(-1 * buffer / Math.sin(interiorAngle / 2));\n output.push(curr.add(offset));\n }\n return output;\n}\n\ntype EaseFunction = (t: number) => number;\n\n/**\n * Given given (x, y), (x1, y1) control points for a bezier curve,\n * return a function that interpolates along that curve.\n *\n * @param p1x control point 1 x coordinate\n * @param p1y control point 1 y coordinate\n * @param p2x control point 2 x coordinate\n * @param p2y control point 2 y coordinate\n * @private\n */\nexport function bezier(p1x: number, p1y: number, p2x: number, p2y: number): EaseFunction {\n const bezier = new UnitBezier(p1x, p1y, p2x, p2y);\n return function(t: number) {\n return bezier.solve(t);\n };\n}\n\n/**\n * A default bezier-curve powered easing function with\n * control points (0.25, 0.1) and (0.25, 1)\n *\n * @private\n */\nexport const ease: EaseFunction = bezier(0.25, 0.1, 0.25, 1);\n\n/**\n * constrain n to the given range via min + max\n *\n * @param n value\n * @param min the minimum value to be returned\n * @param max the maximum value to be returned\n * @returns the clamped value\n * @private\n */\nexport function clamp(n: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, n));\n}\n\n/**\n * Equivalent to GLSL smoothstep.\n *\n * @param {number} e0 The lower edge of the sigmoid\n * @param {number} e1 The upper edge of the sigmoid\n * @param {number} x the value to be interpolated\n * @returns {number} in the range [0, 1]\n * @private\n */\nexport function smoothstep(e0: number, e1: number, x: number): number {\n x = clamp((x - e0) / (e1 - e0), 0, 1);\n return x * x * (3 - 2 * x);\n}\n\n/**\n * constrain n to the given range, excluding the minimum, via modular arithmetic\n *\n * @param n value\n * @param min the minimum value to be returned, exclusive\n * @param max the maximum value to be returned, inclusive\n * @returns constrained number\n * @private\n */\nexport function wrap(n: number, min: number, max: number): number {\n const d = max - min;\n const w = ((n - min) % d + d) % d + min;\n return (w === min) ? max : w;\n}\n\n/**\n * Computes shortest angle in range [-180, 180) between two angles.\n *\n * @param {*} a First angle in degrees\n * @param {*} b Second angle in degrees\n * @returns Shortest angle\n * @private\n */\nexport function shortestAngle(a: number, b: number): number {\n const diff = (b - a + 180) % 360 - 180;\n return diff < -180 ? diff + 360 : diff;\n}\n\n/*\n * Call an asynchronous function on an array of arguments,\n * calling `callback` with the completed results of all calls.\n *\n * @param array input to each call of the async function.\n * @param fn an async function with signature (data, callback)\n * @param callback a callback run after all async work is done.\n * called with an array, containing the results of each async call.\n * @private\n */\nexport function asyncAll<Item, Result>(\n array: Array<Item>,\n fn: (item: Item, fnCallback: Callback<Result>) => void,\n callback: Callback<Array<Result>>\n): void {\n if (!array.length) { return callback(null, []); }\n let remaining = array.length;\n const results = new Array(array.length);\n let error = null;\n array.forEach((item, i) => {\n fn(item, (err, result) => {\n if (err) error = err;\n results[i] = ((result: any): Result); // https://github.com/facebook/flow/issues/2123\n if (--remaining === 0) callback(error, results);\n });\n });\n}\n\n/*\n * Polyfill for Object.values. Not fully spec compliant, but we don't\n * need it to be.\n *\n * @private\n */\nexport function values<T>(obj: {[key: string]: T}): Array<T> {\n const result = [];\n for (const k in obj) {\n result.push(obj[k]);\n }\n return result;\n}\n\n/*\n * Compute the difference between the keys in one object and the keys\n * in another object.\n *\n * @returns keys difference\n * @private\n */\nexport function keysDifference<S, T>(obj: {[key: string]: S}, other: {[key: string]: T}): Array<string> {\n const difference = [];\n for (const i in obj) {\n if (!(i in other)) {\n difference.push(i);\n }\n }\n return difference;\n}\n\n/**\n * Given a destination object and optionally many source objects,\n * copy all properties from the source objects into the destination.\n * The last source object given overrides properties from previous\n * source objects.\n *\n * @param dest destination object\n * @param sources sources from which properties are pulled\n * @private\n */\nexport function extend(dest: Object, ...sources: Array<?Object>): Object {\n for (const src of sources) {\n for (const k in src) {\n dest[k] = src[k];\n }\n }\n return dest;\n}\n\n/**\n * Given an object and a number of properties as strings, return version\n * of that object with only those properties.\n *\n * @param src the object\n * @param properties an array of property names chosen\n * to appear on the resulting object.\n * @returns object with limited properties.\n * @example\n * var foo = { name: 'Charlie', age: 10 };\n * var justName = pick(foo, ['name']);\n * // justName = { name: 'Charlie' }\n * @private\n */\nexport function pick(src: Object, properties: Array<string>): Object {\n const result = {};\n for (let i = 0; i < properties.length; i++) {\n const k = properties[i];\n if (k in src) {\n result[k] = src[k];\n }\n }\n return result;\n}\n\nlet id = 1;\n\n/**\n * Return a unique numeric id, starting at 1 and incrementing with\n * each call.\n *\n * @returns unique numeric id.\n * @private\n */\nexport function uniqueId(): number {\n return id++;\n}\n\n/**\n * Return a random UUID (v4). Taken from: https://gist.github.com/jed/982883\n * @private\n */\nexport function uuid(): string {\n function b(a: void) {\n return a ? (a ^ Math.random() * (16 >> a / 4)).toString(16) :\n //$FlowFixMe: Flow doesn't like the implied array literal conversion here\n ([1e7] + -[1e3] + -4e3 + -8e3 + -1e11).replace(/[018]/g, b);\n }\n return b();\n}\n\n/**\n * Return whether a given value is a power of two\n * @private\n */\nexport function isPowerOfTwo(value: number): boolean {\n return (Math.log(value) / Math.LN2) % 1 === 0;\n}\n\n/**\n * Return the next power of two, or the input value if already a power of two\n * @private\n */\nexport function nextPowerOfTwo(value: number): number {\n if (value <= 1) return 1;\n return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));\n}\n\n/**\n * Return the previous power of two, or the input value if already a power of two\n * @private\n */\nexport function prevPowerOfTwo(value: number): number {\n if (value <= 1) return 1;\n return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));\n}\n\n/**\n * Validate a string to match UUID(v4) of the\n * form: xxxxxxxx-xxxx-4xxx-[89ab]xxx-xxxxxxxxxxxx\n * @param str string to validate.\n * @private\n */\nexport function validateUuid(str: ?string): boolean {\n return str ? /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(str) : false;\n}\n\n/**\n * Given an array of member function names as strings, replace all of them\n * with bound versions that will always refer to `context` as `this`. This\n * is useful for classes where otherwise event bindings would reassign\n * `this` to the evented object or some other value: this lets you ensure\n * the `this` value always.\n *\n * @param fns list of member function names\n * @param context the context value\n * @example\n * function MyClass() {\n * bindAll(['ontimer'], this);\n * this.name = 'Tom';\n * }\n * MyClass.prototype.ontimer = function() {\n * alert(this.name);\n * };\n * var myClass = new MyClass();\n * setTimeout(myClass.ontimer, 100);\n * @private\n */\nexport function bindAll(fns: Array<string>, context: Object): void {\n fns.forEach((fn) => {\n if (!context[fn]) { return; }\n context[fn] = context[fn].bind(context);\n });\n}\n\n/**\n * Determine if a string ends with a particular substring\n *\n * @private\n */\nexport function endsWith(string: string, suffix: string): boolean {\n return string.indexOf(suffix, string.length - suffix.length) !== -1;\n}\n\n/**\n * Create an object by mapping all the values of an existing object while\n * preserving their keys.\n *\n * @private\n */\n// $FlowFixMe[missing-this-annot]\nexport function mapObject(input: Object, iterator: Function, context?: Object): Object {\n const output = {};\n for (const key in input) {\n output[key] = iterator.call(context || this, input[key], key, input);\n }\n return output;\n}\n\n/**\n * Create an object by filtering out values of an existing object.\n *\n * @private\n */\n// $FlowFixMe[missing-this-annot]\nexport function filterObject(input: Object, iterator: Function, context?: Object): Object {\n const output = {};\n for (const key in input) {\n if (iterator.call(context || this, input[key], key, input)) {\n output[key] = input[key];\n }\n }\n return output;\n}\n\nimport deepEqual from '../style-spec/util/deep_equal.js';\nexport {deepEqual};\n\n/**\n * Deeply clones two objects.\n *\n * @private\n */\nexport function clone<T>(input: T): T {\n if (Array.isArray(input)) {\n return ((input.map(clone): any): T);\n } else if (typeof input === 'object' && input) {\n return ((mapObject(input, clone): any): T);\n } else {\n return input;\n }\n}\n\n/**\n * Maps a value from a range between [min, max] to the range [outMin, outMax]\n *\n * @private\n */\nexport function mapValue(value: number, min: number, max: number, outMin: number, outMax: number): number {\n return clamp((value - min) / (max - min) * (outMax - outMin) + outMin, outMin, outMax);\n}\n\n/**\n * Check if two arrays have at least one common element.\n *\n * @private\n */\nexport function arraysIntersect<T>(a: Array<T>, b: Array<T>): boolean {\n for (let l = 0; l < a.length; l++) {\n if (b.indexOf(a[l]) >= 0) return true;\n }\n return false;\n}\n\n/**\n * Print a warning message to the console and ensure duplicate warning messages\n * are not printed.\n *\n * @private\n */\nconst warnOnceHistory: {[key: string]: boolean} = {};\n\nexport function warnOnce(message: string): void {\n if (!warnOnceHistory[message]) {\n // console isn't defined in some WebWorkers, see #2558\n if (typeof console !== \"undefined\") console.warn(message);\n warnOnceHistory[message] = true;\n }\n}\n\n/**\n * Indicates if the provided Points are in a counter clockwise (true) or clockwise (false) order\n *\n * @private\n * @returns true for a counter clockwise set of points\n */\n// http://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/\nexport function isCounterClockwise(a: Point, b: Point, c: Point): boolean {\n return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x);\n}\n\n/**\n * Returns the signed area for the polygon ring. Postive areas are exterior rings and\n * have a clockwise winding. Negative areas are interior rings and have a counter clockwise\n * ordering.\n *\n * @private\n * @param ring Exterior or interior ring\n */\nexport function calculateSignedArea(ring: Array<Point>): number {\n let sum = 0;\n for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) {\n p1 = ring[i];\n p2 = ring[j];\n sum += (p2.x - p1.x) * (p1.y + p2.y);\n }\n return sum;\n}\n\n/* global self, WorkerGlobalScope */\n/**\n * Returns true if run in the web-worker context.\n *\n * @private\n * @returns {boolean}\n */\nexport function isWorker(): boolean {\n return typeof WorkerGlobalScope !== 'undefined' && typeof self !== 'undefined' &&\n self instanceof WorkerGlobalScope;\n}\n\n/**\n * Parses data from 'Cache-Control' headers.\n *\n * @private\n * @param cacheControl Value of 'Cache-Control' header\n * @return object containing parsed header info.\n */\n\nexport function parseCacheControl(cacheControl: string): Object {\n // Taken from [Wreck](https://github.com/hapijs/wreck)\n const re = /(?:^|(?:\\s*\\,\\s*))([^\\x00-\\x20\\(\\)<>@\\,;\\:\\\\\"\\/\\[\\]\\?\\=\\{\\}\\x7F]+)(?:\\=(?:([^\\x00-\\x20\\(\\)<>@\\,;\\:\\\\\"\\/\\[\\]\\?\\=\\{\\}\\x7F]+)|(?:\\\"((?:[^\"\\\\]|\\\\.)*)\\\")))?/g;\n\n const header = {};\n cacheControl.replace(re, ($0, $1, $2, $3) => {\n const value = $2 || $3;\n header[$1] = value ? value.toLowerCase() : true;\n return '';\n });\n\n if (header['max-age']) {\n const maxAge = parseInt(header['max-age'], 10);\n if (isNaN(maxAge)) delete header['max-age'];\n else header['max-age'] = maxAge;\n }\n\n return header;\n}\n\nlet _isSafari = null;\n\nexport function _resetSafariCheckForTest() {\n _isSafari = null;\n}\n\n/**\n * Returns true when run in WebKit derived browsers.\n * This is used as a workaround for a memory leak in Safari caused by using Transferable objects to\n * transfer data between WebWorkers and the main thread.\n * https://github.com/mapbox/mapbox-gl-js/issues/8771\n *\n * This should be removed once the underlying Safari issue is fixed.\n *\n * @private\n * @param scope {WindowOrWorkerGlobalScope} Since this function is used both on the main thread and WebWorker context,\n * let the calling scope pass in the global scope object.\n * @returns {boolean}\n */\nexport function isSafari(scope: any): boolean {\n if (_isSafari == null) {\n const userAgent = scope.navigator ? scope.navigator.userAgent : null;\n _isSafari = !!scope.safari ||\n !!(userAgent && (/\\b(iPad|iPhone|iPod)\\b/.test(userAgent) || (!!userAgent.match('Safari') && !userAgent.match('Chrome'))));\n }\n return _isSafari;\n}\n\nexport function isSafariWithAntialiasingBug(scope: any): ?boolean {\n const userAgent = scope.navigator ? scope.navigator.userAgent : null;\n if (!isSafari(scope)) return false;\n // 15.4 is known to be buggy.\n // 15.5 may or may not include the fix. Mark it as buggy to be on the safe side.\n return userAgent && (userAgent.match('Version/15.4') || userAgent.match('Version/15.5') || userAgent.match(/CPU (OS|iPhone OS) (15_4|15_5) like Mac OS X/));\n}\n\nexport function isFullscreen(): boolean {\n return !!window.document.fullscreenElement || !!window.document.webkitFullscreenElement;\n}\n\nexport function storageAvailable(type: string): boolean {\n try {\n const storage = window[type];\n storage.setItem('_mapbox_test_', 1);\n storage.removeItem('_mapbox_test_');\n return true;\n } catch (e) {\n return false;\n }\n}\n\n// The following methods are from https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding#The_Unicode_Problem\n//Unicode compliant base64 encoder for strings\nexport function b64EncodeUnicode(str: string): string {\n return window.btoa(\n encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,\n (match, p1) => {\n return String.fromCharCode(Number('0x' + p1)); //eslint-disable-line\n }\n )\n );\n}\n\n// Unicode compliant decoder for base64-encoded strings\nexport function b64DecodeUnicode(str: string): string {\n return decodeURIComponent(window.atob(str).split('').map((c) => {\n return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); //eslint-disable-line\n }).join(''));\n}\n\nexport function getColumn(matrix: Mat4, col: number): Vec4 {\n return [matrix[col * 4], matrix[col * 4 + 1], matrix[col * 4 + 2], matrix[col * 4 + 3]];\n}\n\nexport function setColumn(matrix: Mat4, col: number, values: Vec4) {\n matrix[col * 4 + 0] = values[0];\n matrix[col * 4 + 1] = values[1];\n matrix[col * 4 + 2] = values[2];\n matrix[col * 4 + 3] = values[3];\n}\n","'use strict';\n\nmodule.exports = GridIndex;\n\nvar NUM_PARAMS = 3;\n\nfunction GridIndex(extent, n, padding) {\n var cells = this.cells = [];\n\n if (extent instanceof ArrayBuffer) {\n this.arrayBuffer = extent;\n var array = new Int32Array(this.arrayBuffer);\n extent = array[0];\n n = array[1];\n padding = array[2];\n\n this.d = n + 2 * padding;\n for (var k = 0; k < this.d * this.d; k++) {\n var start = array[NUM_PARAMS + k];\n var end = array[NUM_PARAMS + k + 1];\n cells.push(start === end ?\n null :\n array.subarray(start, end));\n }\n var keysOffset = array[NUM_PARAMS + cells.length];\n var bboxesOffset = array[NUM_PARAMS + cells.length + 1];\n this.keys = array.subarray(keysOffset, bboxesOffset);\n this.bboxes = array.subarray(bboxesOffset);\n\n this.insert = this._insertReadonly;\n\n } else {\n this.d = n + 2 * padding;\n for (var i = 0; i < this.d * this.d; i++) {\n cells.push([]);\n }\n this.keys = [];\n this.bboxes = [];\n }\n\n this.n = n;\n this.extent = extent;\n this.padding = padding;\n this.scale = n / extent;\n this.uid = 0;\n\n var p = (padding / n) * extent;\n this.min = -p;\n this.max = extent + p;\n}\n\n\nGridIndex.prototype.insert = function(key, x1, y1, x2, y2) {\n this._forEachCell(x1, y1, x2, y2, this._insertCell, this.uid++);\n this.keys.push(key);\n this.bboxes.push(x1);\n this.bboxes.push(y1);\n this.bboxes.push(x2);\n this.bboxes.push(y2);\n};\n\nGridIndex.prototype._insertReadonly = function() {\n throw 'Cannot insert into a GridIndex created from an ArrayBuffer.';\n};\n\nGridIndex.prototype._insertCell = function(x1, y1, x2, y2, cellIndex, uid) {\n this.cells[cellIndex].push(uid);\n};\n\nGridIndex.prototype.query = function(x1, y1, x2, y2, intersectionTest) {\n var min = this.min;\n var max = this.max;\n if (x1 <= min && y1 <= min && max <= x2 && max <= y2 && !intersectionTest) {\n // We use `Array#slice` because `this.keys` may be a `Int32Array` and\n // some browsers (Safari and IE) do not support `TypedArray#slice`\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/slice#Browser_compatibility\n return Array.prototype.slice.call(this.keys);\n\n } else {\n var result = [];\n var seenUids = {};\n this._forEachCell(x1, y1, x2, y2, this._queryCell, result, seenUids, intersectionTest);\n return result;\n }\n};\n\nGridIndex.prototype._queryCell = function(x1, y1, x2, y2, cellIndex, result, seenUids, intersectionTest) {\n var cell = this.cells[cellIndex];\n if (cell !== null) {\n var keys = this.keys;\n var bboxes = this.bboxes;\n for (var u = 0; u < cell.length; u++) {\n var uid = cell[u];\n if (seenUids[uid] === undefined) {\n var offset = uid * 4;\n if (intersectionTest ?\n intersectionTest(bboxes[offset + 0], bboxes[offset + 1], bboxes[offset + 2], bboxes[offset + 3]) :\n ((x1 <= bboxes[offset + 2]) &&\n (y1 <= bboxes[offset + 3]) &&\n (x2 >= bboxes[offset + 0]) &&\n (y2 >= bboxes[offset + 1]))) {\n seenUids[uid] = true;\n result.push(keys[uid]);\n } else {\n seenUids[uid] = false;\n }\n }\n }\n }\n};\n\nGridIndex.prototype._forEachCell = function(x1, y1, x2, y2, fn, arg1, arg2, intersectionTest) {\n var cx1 = this._convertToCellCoord(x1);\n var cy1 = this._convertToCellCoord(y1);\n var cx2 = this._convertToCellCoord(x2);\n var cy2 = this._convertToCellCoord(y2);\n for (var x = cx1; x <= cx2; x++) {\n for (var y = cy1; y <= cy2; y++) {\n var cellIndex = this.d * y + x;\n if (intersectionTest && !intersectionTest(\n this._convertFromCellCoord(x),\n this._convertFromCellCoord(y),\n this._convertFromCellCoord(x + 1),\n this._convertFromCellCoord(y + 1))) continue;\n if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, intersectionTest)) return;\n }\n }\n};\n\nGridIndex.prototype._convertFromCellCoord = function(x) {\n return (x - this.padding) / this.scale;\n};\n\nGridIndex.prototype._convertToCellCoord = function(x) {\n return Math.max(0, Math.min(this.d - 1, Math.floor(x * this.scale) + this.padding));\n};\n\nGridIndex.prototype.toArrayBuffer = function() {\n if (this.arrayBuffer) return this.arrayBuffer;\n\n var cells = this.cells;\n\n var metadataLength = NUM_PARAMS + this.cells.length + 1 + 1;\n var totalCellLength = 0;\n for (var i = 0; i < this.cells.length; i++) {\n totalCellLength += this.cells[i].length;\n }\n\n var array = new Int32Array(metadataLength + totalCellLength + this.keys.length + this.bboxes.length);\n array[0] = this.extent;\n array[1] = this.n;\n array[2] = this.padding;\n\n var offset = metadataLength;\n for (var k = 0; k < cells.length; k++) {\n var cell = cells[k];\n array[NUM_PARAMS + k] = offset;\n array.set(cell, offset);\n offset += cell.length;\n }\n\n array[NUM_PARAMS + cells.length] = offset;\n array.set(this.keys, offset);\n offset += this.keys.length;\n\n array[NUM_PARAMS + cells.length + 1] = offset;\n array.set(this.bboxes, offset);\n offset += this.bboxes.length;\n\n return array.buffer;\n};\n","// (c) Dean McNamee <dean@gmail.com>, 2012.\n//\n// https://github.com/deanm/css-color-parser-js\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n\n// http://www.w3.org/TR/css3-color/\nvar kCSSColorTable = {\n \"transparent\": [0,0,0,0], \"aliceblue\": [240,248,255,1],\n \"antiquewhite\": [250,235,215,1], \"aqua\": [0,255,255,1],\n \"aquamarine\": [127,255,212,1], \"azure\": [240,255,255,1],\n \"beige\": [245,245,220,1], \"bisque\": [255,228,196,1],\n \"black\": [0,0,0,1], \"blanchedalmond\": [255,235,205,1],\n \"blue\": [0,0,255,1], \"blueviolet\": [138,43,226,1],\n \"brown\": [165,42,42,1], \"burlywood\": [222,184,135,1],\n \"cadetblue\": [95,158,160,1], \"chartreuse\": [127,255,0,1],\n \"chocolate\": [210,105,30,1], \"coral\": [255,127,80,1],\n \"cornflowerblue\": [100,149,237,1], \"cornsilk\": [255,248,220,1],\n \"crimson\": [220,20,60,1], \"cyan\": [0,255,255,1],\n \"darkblue\": [0,0,139,1], \"darkcyan\": [0,139,139,1],\n \"darkgoldenrod\": [184,134,11,1], \"darkgray\": [169,169,169,1],\n \"darkgreen\": [0,100,0,1], \"darkgrey\": [169,169,169,1],\n \"darkkhaki\": [189,183,107,1], \"darkmagenta\": [139,0,139,1],\n \"darkolivegreen\": [85,107,47,1], \"darkorange\": [255,140,0,1],\n \"darkorchid\": [153,50,204,1], \"darkred\": [139,0,0,1],\n \"darksalmon\": [233,150,122,1], \"darkseagreen\": [143,188,143,1],\n \"darkslateblue\": [72,61,139,1], \"darkslategray\": [47,79,79,1],\n \"darkslategrey\": [47,79,79,1], \"darkturquoise\": [0,206,209,1],\n \"darkviolet\": [148,0,211,1], \"deeppink\": [255,20,147,1],\n \"deepskyblue\": [0,191,255,1], \"dimgray\": [105,105,105,1],\n \"dimgrey\": [105,105,105,1], \"dodgerblue\": [30,144,255,1],\n \"firebrick\": [178,34,34,1], \"floralwhite\": [255,250,240,1],\n \"forestgreen\": [34,139,34,1], \"fuchsia\": [255,0,255,1],\n \"gainsboro\": [220,220,220,1], \"ghostwhite\": [248,248,255,1],\n \"gold\": [255,215,0,1], \"goldenrod\": [218,165,32,1],\n \"gray\": [128,128,128,1], \"green\": [0,128,0,1],\n \"greenyellow\": [173,255,47,1], \"grey\": [128,128,128,1],\n \"honeydew\": [240,255,240,1], \"hotpink\": [255,105,180,1],\n \"indianred\": [205,92,92,1], \"indigo\": [75,0,130,1],\n \"ivory\": [255,255,240,1], \"khaki\": [240,230,140,1],\n \"lavender\": [230,230,250,1], \"lavenderblush\": [255,240,245,1],\n \"lawngreen\": [124,252,0,1], \"lemonchiffon\": [255,250,205,1],\n \"lightblue\": [173,216,230,1], \"lightcoral\": [240,128,128,1],\n \"lightcyan\": [224,255,255,1], \"lightgoldenrodyellow\": [250,250,210,1],\n \"lightgray\": [211,211,211,1], \"lightgreen\": [144,238,144,1],\n \"lightgrey\": [211,211,211,1], \"lightpink\": [255,182,193,1],\n \"lightsalmon\": [255,160,122,1], \"lightseagreen\": [32,178,170,1],\n \"lightskyblue\": [135,206,250,1], \"lightslategray\": [119,136,153,1],\n \"lightslategrey\": [119,136,153,1], \"lightsteelblue\": [176,196,222,1],\n \"lightyellow\": [255,255,224,1], \"lime\": [0,255,0,1],\n \"limegreen\": [50,205,50,1], \"linen\": [250,240,230,1],\n \"magenta\": [255,0,255,1], \"maroon\": [128,0,0,1],\n \"mediumaquamarine\": [102,205,170,1], \"mediumblue\": [0,0,205,1],\n \"mediumorchid\": [186,85,211,1], \"mediumpurple\": [147,112,219,1],\n \"mediumseagreen\": [60,179,113,1], \"mediumslateblue\": [123,104,238,1],\n \"mediumspringgreen\": [0,250,154,1], \"mediumturquoise\": [72,209,204,1],\n \"mediumvioletred\": [199,21,133,1], \"midnightblue\": [25,25,112,1],\n \"mintcream\": [245,255,250,1], \"mistyrose\": [255,228,225,1],\n \"moccasin\": [255,228,181,1], \"navajowhite\": [255,222,173,1],\n \"navy\": [0,0,128,1], \"oldlace\": [253,245,230,1],\n \"olive\": [128,128,0,1], \"olivedrab\": [107,142,35,1],\n \"orange\": [255,165,0,1], \"orangered\": [255,69,0,1],\n \"orchid\": [218,112,214,1], \"palegoldenrod\": [238,232,170,1],\n \"palegreen\": [152,251,152,1], \"paleturquoise\": [175,238,238,1],\n \"palevioletred\": [219,112,147,1], \"papayawhip\": [255,239,213,1],\n \"peachpuff\": [255,218,185,1], \"peru\": [205,133,63,1],\n \"pink\": [255,192,203,1], \"plum\": [221,160,221,1],\n \"powderblue\": [176,224,230,1], \"purple\": [128,0,128,1],\n \"rebeccapurple\": [102,51,153,1],\n \"red\": [255,0,0,1], \"rosybrown\": [188,143,143,1],\n \"royalblue\": [65,105,225,1], \"saddlebrown\": [139,69,19,1],\n \"salmon\": [250,128,114,1], \"sandybrown\": [244,164,96,1],\n \"seagreen\": [46,139,87,1], \"seashell\": [255,245,238,1],\n \"sienna\": [160,82,45,1], \"silver\": [192,192,192,1],\n \"skyblue\": [135,206,235,1], \"slateblue\": [106,90,205,1],\n \"slategray\": [112,128,144,1], \"slategrey\": [112,128,144,1],\n \"snow\": [255,250,250,1], \"springgreen\": [0,255,127,1],\n \"steelblue\": [70,130,180,1], \"tan\": [210,180,140,1],\n \"teal\": [0,128,128,1], \"thistle\": [216,191,216,1],\n \"tomato\": [255,99,71,1], \"turquoise\": [64,224,208,1],\n \"violet\": [238,130,238,1], \"wheat\": [245,222,179,1],\n \"white\": [255,255,255,1], \"whitesmoke\": [245,245,245,1],\n \"yellow\": [255,255,0,1], \"yellowgreen\": [154,205,50,1]}\n\nfunction clamp_css_byte(i) { // Clamp to integer 0 .. 255.\n i = Math.round(i); // Seems to be what Chrome does (vs truncation).\n return i < 0 ? 0 : i > 255 ? 255 : i;\n}\n\nfunction clamp_css_float(f) { // Clamp to float 0.0 .. 1.0.\n return f < 0 ? 0 : f > 1 ? 1 : f;\n}\n\nfunction parse_css_int(str) { // int or percentage.\n if (str[str.length - 1] === '%')\n return clamp_css_byte(parseFloat(str) / 100 * 255);\n return clamp_css_byte(parseInt(str));\n}\n\nfunction parse_css_float(str) { // float or percentage.\n if (str[str.length - 1] === '%')\n return clamp_css_float(parseFloat(str) / 100);\n return clamp_css_float(parseFloat(str));\n}\n\nfunction css_hue_to_rgb(m1, m2, h) {\n if (h < 0) h += 1;\n else if (h > 1) h -= 1;\n\n if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;\n if (h * 2 < 1) return m2;\n if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6;\n return m1;\n}\n\nfunction parseCSSColor(css_str) {\n // Remove all whitespace, not compliant, but should just be more accepting.\n var str = css_str.replace(/ /g, '').toLowerCase();\n\n // Color keywords (and transparent) lookup.\n if (str in kCSSColorTable) return kCSSColorTable[str].slice(); // dup.\n\n // #abc and #abc123 syntax.\n if (str[0] === '#') {\n if (str.length === 4) {\n var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.\n if (!(iv >= 0 && iv <= 0xfff)) return null; // Covers NaN.\n return [((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),\n (iv & 0xf0) | ((iv & 0xf0) >> 4),\n (iv & 0xf) | ((iv & 0xf) << 4),\n 1];\n } else if (str.length === 7) {\n var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.\n if (!(iv >= 0 && iv <= 0xffffff)) return null; // Covers NaN.\n return [(iv & 0xff0000) >> 16,\n (iv & 0xff00) >> 8,\n iv & 0xff,\n 1];\n }\n\n return null;\n }\n\n var op = str.indexOf('('), ep = str.indexOf(')');\n if (op !== -1 && ep + 1 === str.length) {\n var fname = str.substr(0, op);\n var params = str.substr(op+1, ep-(op+1)).split(',');\n var alpha = 1; // To allow case fallthrough.\n switch (fname) {\n case 'rgba':\n if (params.length !== 4) return null;\n alpha = parse_css_float(params.pop());\n // Fall through.\n case 'rgb':\n if (params.length !== 3) return null;\n return [parse_css_int(params[0]),\n parse_css_int(params[1]),\n parse_css_int(params[2]),\n alpha];\n case 'hsla':\n if (params.length !== 4) return null;\n alpha = parse_css_float(params.pop());\n // Fall through.\n case 'hsl':\n if (params.length !== 3) return null;\n var h = (((parseFloat(params[0]) % 360) + 360) % 360) / 360; // 0 .. 1\n // NOTE(deanm): According to the CSS spec s/l should only be\n // percentages, but we don't bother and let float or percentage.\n var s = parse_css_float(params[1]);\n var l = parse_css_float(params[2]);\n var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;\n var m1 = l * 2 - m2;\n return [clamp_css_byte(css_hue_to_rgb(m1, m2, h+1/3) * 255),\n clamp_css_byte(css_hue_to_rgb(m1, m2, h) * 255),\n clamp_css_byte(css_hue_to_rgb(m1, m2, h-1/3) * 255),\n alpha];\n default:\n return null;\n }\n }\n\n return null;\n}\n\ntry { exports.parseCSSColor = parseCSSColor } catch(e) { }\n","// @flow\n\nimport {parseCSSColor} from 'csscolorparser';\n\n/**\n * An RGBA color value. Create instances from color strings using the static\n * method `Color.parse`. The constructor accepts RGB channel values in the range\n * `[0, 1]`, premultiplied by A.\n *\n * @param {number} r The red channel.\n * @param {number} g The green channel.\n * @param {number} b The blue channel.\n * @param {number} a The alpha channel.\n * @private\n */\nclass Color {\n r: number;\n g: number;\n b: number;\n a: number;\n\n constructor(r: number, g: number, b: number, a: number = 1) {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n }\n\n static black: Color;\n static white: Color;\n static transparent: Color;\n static red: Color;\n static blue: Color;\n\n /**\n * Parses valid CSS color strings and returns a `Color` instance.\n * @returns A `Color` instance, or `undefined` if the input is not a valid color string.\n */\n static parse(input?: string | Color | null): Color | void {\n if (!input) {\n return undefined;\n }\n\n if (input instanceof Color) {\n return input;\n }\n\n if (typeof input !== 'string') {\n return undefined;\n }\n\n const rgba = parseCSSColor(input);\n if (!rgba) {\n return undefined;\n }\n\n return new Color(\n rgba[0] / 255 * rgba[3],\n rgba[1] / 255 * rgba[3],\n rgba[2] / 255 * rgba[3],\n rgba[3]\n );\n }\n\n /**\n * Returns an RGBA string representing the color value.\n *\n * @returns An RGBA string.\n * @example\n * var purple = new Color.parse('purple');\n * purple.toString; // = \"rgba(128,0,128,1)\"\n * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)');\n * translucentGreen.toString(); // = \"rgba(26,207,26,0.73)\"\n */\n toString(): string {\n const [r, g, b, a] = this.toArray();\n return `rgba(${Math.round(r)},${Math.round(g)},${Math.round(b)},${a})`;\n }\n\n /**\n * Returns an RGBA array of values representing the color, unpremultiplied by A.\n *\n * @returns An array of RGBA color values in the range [0, 255].\n */\n toArray(): [number, number, number, number] {\n const {r, g, b, a} = this;\n return a === 0 ? [0, 0, 0, 0] : [\n r * 255 / a,\n g * 255 / a,\n b * 255 / a,\n a\n ];\n }\n\n /**\n * Returns a RGBA array of float values representing the color, unpremultiplied by A.\n *\n * @returns An array of RGBA color values in the range [0, 1].\n */\n toArray01(): [number, number, number, number] {\n const {r, g, b, a} = this;\n return a === 0 ? [0, 0, 0, 0] : [\n r / a,\n g / a,\n b / a,\n a\n ];\n }\n\n /**\n * Returns an RGBA array of values representing the color, premultiplied by A.\n *\n * @returns An array of RGBA color values in the range [0, 1].\n */\n toArray01PremultipliedAlpha(): [number, number, number, number] {\n const {r, g, b, a} = this;\n return [\n r,\n g,\n b,\n a\n ];\n }\n}\n\nColor.black = new Color(0, 0, 0, 1);\nColor.white = new Color(1, 1, 1, 1);\nColor.transparent = new Color(0, 0, 0, 0);\nColor.red = new Color(1, 0, 0, 1);\nColor.blue = new Color(0, 0, 1, 1);\n\nexport default Color;\n","// @flow\n\nexport default function (output: any, ...inputs: Array<any>): any {\n for (const input of inputs) {\n for (const k in input) {\n output[k] = input[k];\n }\n }\n return output;\n}\n","// @flow\n\nclass ParsingError extends Error {\n key: string;\n message: string;\n constructor(key: string, message: string) {\n super(message);\n this.message = message;\n this.key = key;\n }\n}\n\nexport default ParsingError;\n","// @flow\n\nimport type {Expression} from './expression.js';\n\n/**\n * Tracks `let` bindings during expression parsing.\n * @private\n */\nclass Scope {\n parent: ?Scope;\n bindings: {[_: string]: Expression};\n constructor(parent?: Scope, bindings: Array<[string, Expression]> = []) {\n this.parent = parent;\n this.bindings = {};\n for (const [name, expression] of bindings) {\n this.bindings[name] = expression;\n }\n }\n\n concat(bindings: Array<[string, Expression]>): Scope {\n return new Scope(this, bindings);\n }\n\n get(name: string): Expression {\n if (this.bindings[name]) { return this.bindings[name]; }\n if (this.parent) { return this.parent.get(name); }\n throw new Error(`${name} not found in scope.`);\n }\n\n has(name: string): boolean {\n if (this.bindings[name]) return true;\n return this.parent ? this.parent.has(name) : false;\n }\n}\n\nexport default Scope;\n","// @flow\n\nexport type NullTypeT = { kind: 'null' };\nexport type NumberTypeT = { kind: 'number' };\nexport type StringTypeT = { kind: 'string' };\nexport type BooleanTypeT = { kind: 'boolean' };\nexport type ColorTypeT = { kind: 'color' };\nexport type ObjectTypeT = { kind: 'object' };\nexport type ValueTypeT = { kind: 'value' };\nexport type ErrorTypeT = { kind: 'error' };\nexport type CollatorTypeT = { kind: 'collator' };\nexport type FormattedTypeT = { kind: 'formatted' };\nexport type ResolvedImageTypeT = { kind: 'resolvedImage' };\n\nexport type EvaluationKind = 'constant' | 'source' | 'camera' | 'composite';\n\nexport type Type =\n NullTypeT |\n NumberTypeT |\n StringTypeT |\n BooleanTypeT |\n ColorTypeT |\n ObjectTypeT |\n ValueTypeT |\n ArrayType | // eslint-disable-line no-use-before-define\n ErrorTypeT |\n CollatorTypeT |\n FormattedTypeT |\n ResolvedImageTypeT\n\nexport type ArrayType = {\n kind: 'array',\n itemType: Type,\n N: ?number\n}\n\nexport type NativeType = 'number' | 'string' | 'boolean' | 'null' | 'array' | 'object'\n\nexport const NullType = {kind: 'null'};\nexport const NumberType = {kind: 'number'};\nexport const StringType = {kind: 'string'};\nexport const BooleanType = {kind: 'boolean'};\nexport const ColorType = {kind: 'color'};\nexport const ObjectType = {kind: 'object'};\nexport const ValueType = {kind: 'value'};\nexport const ErrorType = {kind: 'error'};\nexport const CollatorType = {kind: 'collator'};\nexport const FormattedType = {kind: 'formatted'};\nexport const ResolvedImageType = {kind: 'resolvedImage'};\n\nexport function array(itemType: Type, N: ?number): ArrayType {\n return {\n kind: 'array',\n itemType,\n N\n };\n}\n\nexport function toString(type: Type): string {\n if (type.kind === 'array') {\n const itemType = toString(type.itemType);\n return typeof type.N === 'number' ?\n `array<${itemType}, ${type.N}>` :\n type.itemType.kind === 'value' ? 'array' : `array<${itemType}>`;\n } else {\n return type.kind;\n }\n}\n\nconst valueMemberTypes = [\n NullType,\n NumberType,\n StringType,\n BooleanType,\n ColorType,\n FormattedType,\n ObjectType,\n array(ValueType),\n ResolvedImageType\n];\n\n/**\n * Returns null if `t` is a subtype of `expected`; otherwise returns an\n * error message.\n * @private\n */\nexport function checkSubtype(expected: Type, t: Type): ?string {\n if (t.kind === 'error') {\n // Error is a subtype of every type\n return null;\n } else if (expected.kind === 'array') {\n if (t.kind === 'array' &&\n ((t.N === 0 && t.itemType.kind === 'value') || !checkSubtype(expected.itemType, t.itemType)) &&\n (typeof expected.N !== 'number' || expected.N === t.N)) {\n return null;\n }\n } else if (expected.kind === t.kind) {\n return null;\n } else if (expected.kind === 'value') {\n for (const memberType of valueMemberTypes) {\n if (!checkSubtype(memberType, t)) {\n return null;\n }\n }\n }\n\n return `Expected ${toString(expected)} but found ${toString(t)} instead.`;\n}\n\nexport function isValidType(provided: Type, allowedTypes: Array<Type>): boolean {\n return allowedTypes.some(t => t.kind === provided.kind);\n}\n\nexport function isValidNativeType(provided: any, allowedTypes: Array<NativeType>): boolean {\n return allowedTypes.some(t => {\n if (t === 'null') {\n return provided === null;\n } else if (t === 'array') {\n return Array.isArray(provided);\n } else if (t === 'object') {\n return provided && !Array.isArray(provided) && typeof provided === 'object';\n } else {\n return t === typeof provided;\n }\n });\n}\n","// @flow\n\n// Flow type declarations for Intl cribbed from\n// https://github.com/facebook/flow/issues/1270\n\ndeclare var Intl: {\n Collator: Class<Intl$Collator>\n};\n\ndeclare class Intl$Collator {\n constructor (\n locales?: string | string[],\n options?: CollatorOptions\n ): Intl$Collator;\n\n static (\n locales?: string | string[],\n options?: CollatorOptions\n ): Intl$Collator;\n\n compare (a: string, b: string): number;\n\n resolvedOptions(): any;\n}\n\ntype CollatorOptions = {\n localeMatcher?: 'lookup' | 'best fit',\n usage?: 'sort' | 'search',\n sensitivity?: 'base' | 'accent' | 'case' | 'variant',\n ignorePunctuation?: boolean,\n numeric?: boolean,\n caseFirst?: 'upper' | 'lower' | 'false'\n}\n\nexport default class Collator {\n locale: string | null;\n sensitivity: 'base' | 'accent' | 'case' | 'variant';\n collator: Intl$Collator;\n\n constructor(caseSensitive: boolean, diacriticSensitive: boolean, locale: string | null) {\n if (caseSensitive)\n this.sensitivity = diacriticSensitive ? 'variant' : 'case';\n else\n this.sensitivity = diacriticSensitive ? 'accent' : 'base';\n\n this.locale = locale;\n this.collator = new Intl.Collator(this.locale ? this.locale : [],\n {sensitivity: this.sensitivity, usage: 'search'});\n }\n\n compare(lhs: string, rhs: string): number {\n return this.collator.compare(lhs, rhs);\n }\n\n resolvedLocale(): string {\n // We create a Collator without \"usage: search\" because we don't want\n // the search options encoded in our result (e.g. \"en-u-co-search\")\n return new Intl.Collator(this.locale ? this.locale : [])\n .resolvedOptions().locale;\n }\n}\n","// @flow\nimport type Color from '../../util/color.js';\nimport type ResolvedImage from '../types/resolved_image.js';\n\nexport class FormattedSection {\n text: string;\n image: ResolvedImage | null;\n scale: number | null;\n fontStack: string | null;\n textColor: Color | null;\n\n constructor(text: string, image: ResolvedImage | null, scale: number | null, fontStack: string | null, textColor: Color | null) {\n // combine characters so that diacritic marks are not separate code points\n this.text = text.normalize ? text.normalize() : text;\n this.image = image;\n this.scale = scale;\n this.fontStack = fontStack;\n this.textColor = textColor;\n }\n}\n\nexport default class Formatted {\n sections: Array<FormattedSection>;\n\n constructor(sections: Array<FormattedSection>) {\n this.sections = sections;\n }\n\n static fromString(unformatted: string): Formatted {\n return new Formatted([new FormattedSection(unformatted, null, null, null, null)]);\n }\n\n isEmpty(): boolean {\n if (this.sections.length === 0) return true;\n return !this.sections.some(section => section.text.length !== 0 ||\n (section.image && section.image.name.length !== 0));\n }\n\n static factory(text: Formatted | string): Formatted {\n if (text instanceof Formatted) {\n return text;\n } else {\n return Formatted.fromString(text);\n }\n }\n\n toString(): string {\n if (this.sections.length === 0) return '';\n return this.sections.map(section => section.text).join('');\n }\n\n serialize(): Array<mixed> {\n const serialized: Array<mixed> = [\"format\"];\n for (const section of this.sections) {\n if (section.image) {\n serialized.push([\"image\", section.image.name]);\n continue;\n }\n serialized.push(section.text);\n const options: { [key: string]: mixed } = {};\n if (section.fontStack) {\n options[\"text-font\"] = [\"literal\", section.fontStack.split(',')];\n }\n if (section.scale) {\n options[\"font-scale\"] = section.scale;\n }\n if (section.textColor) {\n options[\"text-color\"] = ([\"rgba\"]: Array<mixed>).concat(section.textColor.toArray());\n }\n serialized.push(options);\n }\n return serialized;\n }\n}\n","// @flow\n\nexport type ResolvedImageOptions = {\n name: string,\n available: boolean\n};\n\nexport default class ResolvedImage {\n name: string;\n available: boolean;\n\n constructor(options: ResolvedImageOptions) {\n this.name = options.name;\n this.available = options.available;\n }\n\n toString(): string {\n return this.name;\n }\n\n static fromString(name: string): ResolvedImage | null {\n if (!name) return null; // treat empty values as no image\n return new ResolvedImage({name, available: false});\n }\n\n serialize(): Array<string> {\n return [\"image\", this.name];\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport Color from '../util/color.js';\nimport Collator from './types/collator.js';\nimport Formatted from './types/formatted.js';\nimport ResolvedImage from './types/resolved_image.js';\nimport {NullType, NumberType, StringType, BooleanType, ColorType, ObjectType, ValueType, CollatorType, FormattedType, ResolvedImageType, array} from './types.js';\n\nimport type {Type} from './types.js';\n\nexport function validateRGBA(r: mixed, g: mixed, b: mixed, a?: mixed): string | null {\n if (!(\n typeof r === 'number' && r >= 0 && r <= 255 &&\n typeof g === 'number' && g >= 0 && g <= 255 &&\n typeof b === 'number' && b >= 0 && b <= 255\n )) {\n const value = typeof a === 'number' ? [r, g, b, a] : [r, g, b];\n return `Invalid rgba value [${value.join(', ')}]: 'r', 'g', and 'b' must be between 0 and 255.`;\n }\n\n if (!(\n typeof a === 'undefined' || (typeof a === 'number' && a >= 0 && a <= 1)\n )) {\n return `Invalid rgba value [${[r, g, b, a].join(', ')}]: 'a' must be between 0 and 1.`;\n }\n\n return null;\n}\n\nexport type Value = null | string | boolean | number | Color | Collator | Formatted | ResolvedImage | $ReadOnlyArray<Value> | { +[string]: Value }\n\nexport function isValue(mixed: mixed): boolean {\n if (mixed === null) {\n return true;\n } else if (typeof mixed === 'string') {\n return true;\n } else if (typeof mixed === 'boolean') {\n return true;\n } else if (typeof mixed === 'number') {\n return true;\n } else if (mixed instanceof Color) {\n return true;\n } else if (mixed instanceof Collator) {\n return true;\n } else if (mixed instanceof Formatted) {\n return true;\n } else if (mixed instanceof ResolvedImage) {\n return true;\n } else if (Array.isArray(mixed)) {\n for (const item of mixed) {\n if (!isValue(item)) {\n return false;\n }\n }\n return true;\n } else if (typeof mixed === 'object') {\n for (const key in mixed) {\n if (!isValue(mixed[key])) {\n return false;\n }\n }\n return true;\n } else {\n return false;\n }\n}\n\nexport function typeOf(value: Value): Type {\n if (value === null) {\n return NullType;\n } else if (typeof value === 'string') {\n return StringType;\n } else if (typeof value === 'boolean') {\n return BooleanType;\n } else if (typeof value === 'number') {\n return NumberType;\n } else if (value instanceof Color) {\n return ColorType;\n } else if (value instanceof Collator) {\n return CollatorType;\n } else if (value instanceof Formatted) {\n return FormattedType;\n } else if (value instanceof ResolvedImage) {\n return ResolvedImageType;\n } else if (Array.isArray(value)) {\n const length = value.length;\n let itemType: Type | typeof undefined;\n\n for (const item of value) {\n const t = typeOf(item);\n if (!itemType) {\n itemType = t;\n } else if (itemType === t) {\n continue;\n } else {\n itemType = ValueType;\n break;\n }\n }\n\n return array(itemType || ValueType, length);\n } else {\n assert(typeof value === 'object');\n return ObjectType;\n }\n}\n\nexport function toString(value: Value): string {\n const type = typeof value;\n if (value === null) {\n return '';\n } else if (type === 'string' || type === 'number' || type === 'boolean') {\n return String(value);\n } else if (value instanceof Color || value instanceof Formatted || value instanceof ResolvedImage) {\n return value.toString();\n } else {\n return JSON.stringify(value);\n }\n}\n\nexport {Color, Collator};\n","// @flow\n\nimport assert from 'assert';\nimport {isValue, typeOf, Color} from '../values.js';\nimport Formatted from '../types/formatted.js';\n\nimport type {Type} from '../types.js';\nimport type {Value} from '../values.js';\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\n\nclass Literal implements Expression {\n type: Type;\n value: Value;\n\n constructor(type: Type, value: Value) {\n this.type = type;\n this.value = value;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): void | Literal {\n if (args.length !== 2)\n return context.error(`'literal' expression requires exactly one argument, but found ${args.length - 1} instead.`);\n\n if (!isValue(args[1]))\n return context.error(`invalid value`);\n\n const value = (args[1]: any);\n let type = typeOf(value);\n\n // special case: infer the item type if possible for zero-length arrays\n const expected = context.expectedType;\n if (\n type.kind === 'array' &&\n type.N === 0 &&\n expected &&\n expected.kind === 'array' &&\n (typeof expected.N !== 'number' || expected.N === 0)\n ) {\n type = expected;\n }\n\n return new Literal(type, value);\n }\n\n evaluate(): Value {\n return this.value;\n }\n\n eachChild() {}\n\n outputDefined(): boolean {\n return true;\n }\n\n serialize(): SerializedExpression {\n if (this.type.kind === 'array' || this.type.kind === 'object') {\n return [\"literal\", this.value];\n } else if (this.value instanceof Color) {\n // Constant-folding can generate Literal expressions that you\n // couldn't actually generate with a \"literal\" expression,\n // so we have to implement an equivalent serialization here\n return [\"rgba\"].concat(this.value.toArray());\n } else if (this.value instanceof Formatted) {\n // Same as Color\n return this.value.serialize();\n } else {\n assert(this.value === null ||\n typeof this.value === 'string' ||\n typeof this.value === 'number' ||\n typeof this.value === 'boolean');\n return (this.value: any);\n }\n }\n}\n\nexport default Literal;\n","// @flow\n\nclass RuntimeError {\n name: string;\n message: string;\n\n constructor(message: string) {\n this.name = 'ExpressionEvaluationError';\n this.message = message;\n }\n\n toJSON(): string {\n return this.message;\n }\n}\n\nexport default RuntimeError;\n","// @flow\n\nimport assert from 'assert';\n\nimport {\n ObjectType,\n ValueType,\n StringType,\n NumberType,\n BooleanType,\n checkSubtype,\n toString,\n array\n} from '../types.js';\nimport RuntimeError from '../runtime_error.js';\nimport {typeOf} from '../values.js';\n\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type {Type} from '../types.js';\n\nconst types = {\n string: StringType,\n number: NumberType,\n boolean: BooleanType,\n object: ObjectType\n};\n\nclass Assertion implements Expression {\n type: Type;\n args: Array<Expression>;\n\n constructor(type: Type, args: Array<Expression>) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Expression {\n if (args.length < 2)\n return context.error(`Expected at least one argument.`);\n\n let i = 1;\n let type;\n\n const name: string = (args[0]: any);\n if (name === 'array') {\n let itemType;\n if (args.length > 2) {\n const type = args[1];\n if (typeof type !== 'string' || !(type in types) || type === 'object')\n return context.error('The item type argument of \"array\" must be one of string, number, boolean', 1);\n itemType = types[type];\n i++;\n } else {\n itemType = ValueType;\n }\n\n let N: ?number;\n if (args.length > 3) {\n if (args[2] !== null &&\n (typeof args[2] !== 'number' ||\n args[2] < 0 ||\n args[2] !== Math.floor(args[2]))\n ) {\n return context.error('The length argument to \"array\" must be a positive integer literal', 2);\n }\n N = ((args[2]: any): number);\n i++;\n }\n\n type = array(itemType, N);\n } else {\n assert(types[name], name);\n type = types[name];\n }\n\n const parsed = [];\n for (; i < args.length; i++) {\n const input = context.parse(args[i], i, ValueType);\n if (!input) return null;\n parsed.push(input);\n }\n\n return new Assertion(type, parsed);\n }\n\n evaluate(ctx: EvaluationContext): any | null {\n for (let i = 0; i < this.args.length; i++) {\n const value = this.args[i].evaluate(ctx);\n const error = checkSubtype(this.type, typeOf(value));\n if (!error) {\n return value;\n } else if (i === this.args.length - 1) {\n throw new RuntimeError(`Expected value to be of type ${toString(this.type)}, but found ${toString(typeOf(value))} instead.`);\n }\n }\n\n assert(false);\n return null;\n }\n\n eachChild(fn: (_: Expression) => void) {\n this.args.forEach(fn);\n }\n\n outputDefined(): boolean {\n return this.args.every(arg => arg.outputDefined());\n }\n\n serialize(): SerializedExpression {\n const type = this.type;\n const serialized = [type.kind];\n if (type.kind === 'array') {\n const itemType = type.itemType;\n if (itemType.kind === 'string' ||\n itemType.kind === 'number' ||\n itemType.kind === 'boolean') {\n serialized.push(itemType.kind);\n const N = type.N;\n if (typeof N === 'number' || this.args.length > 1) {\n serialized.push(N);\n }\n }\n }\n return serialized.concat(this.args.map(arg => arg.serialize()));\n }\n}\n\nexport default Assertion;\n","// @flow\n\nimport {NumberType, ValueType, FormattedType, array, StringType, ColorType, ResolvedImageType} from '../types.js';\nimport Formatted, {FormattedSection} from '../types/formatted.js';\nimport {toString, typeOf} from '../values.js';\n\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type {Type} from '../types.js';\n\nexport type FormattedSectionExpression = {\n // Content of a section may be Image expression or other\n // type of expression that is coercable to 'string'.\n content: Expression,\n scale: Expression | null;\n font: Expression | null;\n textColor: Expression | null;\n}\n\nexport default class FormatExpression implements Expression {\n type: Type;\n sections: Array<FormattedSectionExpression>;\n\n constructor(sections: Array<FormattedSectionExpression>) {\n this.type = FormattedType;\n this.sections = sections;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Expression {\n if (args.length < 2) {\n return context.error(`Expected at least one argument.`);\n }\n\n const firstArg = args[1];\n if (!Array.isArray(firstArg) && typeof firstArg === 'object') {\n return context.error(`First argument must be an image or text section.`);\n }\n\n const sections: Array<FormattedSectionExpression> = [];\n let nextTokenMayBeObject = false;\n for (let i = 1; i <= args.length - 1; ++i) {\n const arg = (args[i]: any);\n\n if (nextTokenMayBeObject && typeof arg === \"object\" && !Array.isArray(arg)) {\n nextTokenMayBeObject = false;\n\n let scale = null;\n if (arg['font-scale']) {\n scale = context.parse(arg['font-scale'], 1, NumberType);\n if (!scale) return null;\n }\n\n let font = null;\n if (arg['text-font']) {\n font = context.parse(arg['text-font'], 1, array(StringType));\n if (!font) return null;\n }\n\n let textColor = null;\n if (arg['text-color']) {\n textColor = context.parse(arg['text-color'], 1, ColorType);\n if (!textColor) return null;\n }\n\n const lastExpression = sections[sections.length - 1];\n lastExpression.scale = scale;\n lastExpression.font = font;\n lastExpression.textColor = textColor;\n } else {\n const content = context.parse(args[i], 1, ValueType);\n if (!content) return null;\n\n const kind = content.type.kind;\n if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage')\n return context.error(`Formatted text type must be 'string', 'value', 'image' or 'null'.`);\n\n nextTokenMayBeObject = true;\n sections.push({content, scale: null, font: null, textColor: null});\n }\n }\n\n return new FormatExpression(sections);\n }\n\n evaluate(ctx: EvaluationContext): Formatted {\n const evaluateSection = (section: FormattedSectionExpression) => {\n const evaluatedContent = section.content.evaluate(ctx);\n if (typeOf(evaluatedContent) === ResolvedImageType) {\n return new FormattedSection('', evaluatedContent, null, null, null);\n }\n\n return new FormattedSection(\n toString(evaluatedContent),\n null,\n section.scale ? section.scale.evaluate(ctx) : null,\n section.font ? section.font.evaluate(ctx).join(',') : null,\n section.textColor ? section.textColor.evaluate(ctx) : null\n );\n };\n\n return new Formatted(this.sections.map(evaluateSection));\n }\n\n eachChild(fn: (_: Expression) => void) {\n for (const section of this.sections) {\n fn(section.content);\n if (section.scale) {\n fn(section.scale);\n }\n if (section.font) {\n fn(section.font);\n }\n if (section.textColor) {\n fn(section.textColor);\n }\n }\n }\n\n outputDefined(): boolean {\n // Technically the combinatoric set of all children\n // Usually, this.text will be undefined anyway\n return false;\n }\n\n serialize(): SerializedExpression {\n const serialized = [\"format\"];\n for (const section of this.sections) {\n serialized.push(section.content.serialize());\n const options = {};\n if (section.scale) {\n options['font-scale'] = section.scale.serialize();\n }\n if (section.font) {\n options['text-font'] = section.font.serialize();\n }\n if (section.textColor) {\n options['text-color'] = section.textColor.serialize();\n }\n serialized.push(options);\n }\n return serialized;\n }\n}\n","// @flow\n\nimport {ResolvedImageType, StringType} from '../types.js';\nimport ResolvedImage from '../types/resolved_image.js';\n\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type {Type} from '../types.js';\n\nexport default class ImageExpression implements Expression {\n type: Type;\n input: Expression;\n\n constructor(input: Expression) {\n this.type = ResolvedImageType;\n this.input = input;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Expression {\n if (args.length !== 2) {\n return context.error(`Expected two arguments.`);\n }\n\n const name = context.parse(args[1], 1, StringType);\n if (!name) return context.error(`No image name provided.`);\n\n return new ImageExpression(name);\n }\n\n evaluate(ctx: EvaluationContext): null | ResolvedImage {\n const evaluatedImageName = this.input.evaluate(ctx);\n\n const value = ResolvedImage.fromString(evaluatedImageName);\n if (value && ctx.availableImages) value.available = ctx.availableImages.indexOf(evaluatedImageName) > -1;\n\n return value;\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n }\n\n outputDefined(): boolean {\n // The output of image is determined by the list of available images in the evaluation context\n return false;\n }\n\n serialize(): SerializedExpression {\n return [\"image\", this.input.serialize()];\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport {BooleanType, ColorType, NumberType, StringType, ValueType} from '../types.js';\nimport {Color, toString as valueToString, validateRGBA} from '../values.js';\nimport RuntimeError from '../runtime_error.js';\nimport Formatted from '../types/formatted.js';\nimport FormatExpression from '../definitions/format.js';\nimport ImageExpression from '../definitions/image.js';\nimport ResolvedImage from '../types/resolved_image.js';\n\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type {Type} from '../types.js';\n\nconst types = {\n 'to-boolean': BooleanType,\n 'to-color': ColorType,\n 'to-number': NumberType,\n 'to-string': StringType\n};\n\n/**\n * Special form for error-coalescing coercion expressions \"to-number\",\n * \"to-color\". Since these coercions can fail at runtime, they accept multiple\n * arguments, only evaluating one at a time until one succeeds.\n *\n * @private\n */\nclass Coercion implements Expression {\n type: Type;\n args: Array<Expression>;\n\n constructor(type: Type, args: Array<Expression>) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Expression {\n if (args.length < 2)\n return context.error(`Expected at least one argument.`);\n\n const name: string = (args[0]: any);\n assert(types[name], name);\n\n if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2)\n return context.error(`Expected one argument.`);\n\n const type = types[name];\n\n const parsed = [];\n for (let i = 1; i < args.length; i++) {\n const input = context.parse(args[i], i, ValueType);\n if (!input) return null;\n parsed.push(input);\n }\n\n return new Coercion(type, parsed);\n }\n\n evaluate(ctx: EvaluationContext): null | boolean | number | string | Color | Formatted | ResolvedImage {\n if (this.type.kind === 'boolean') {\n return Boolean(this.args[0].evaluate(ctx));\n } else if (this.type.kind === 'color') {\n let input;\n let error;\n for (const arg of this.args) {\n input = arg.evaluate(ctx);\n error = null;\n if (input instanceof Color) {\n return input;\n } else if (typeof input === 'string') {\n const c = ctx.parseColor(input);\n if (c) return c;\n } else if (Array.isArray(input)) {\n if (input.length < 3 || input.length > 4) {\n error = `Invalid rbga value ${JSON.stringify(input)}: expected an array containing either three or four numeric values.`;\n } else {\n error = validateRGBA(input[0], input[1], input[2], input[3]);\n }\n if (!error) {\n return new Color((input[0]: any) / 255, (input[1]: any) / 255, (input[2]: any) / 255, (input[3]: any));\n }\n }\n }\n throw new RuntimeError(error || `Could not parse color from value '${typeof input === 'string' ? input : String(JSON.stringify(input))}'`);\n } else if (this.type.kind === 'number') {\n let value = null;\n for (const arg of this.args) {\n value = arg.evaluate(ctx);\n if (value === null) return 0;\n const num = Number(value);\n if (isNaN(num)) continue;\n return num;\n }\n throw new RuntimeError(`Could not convert ${JSON.stringify(value)} to number.`);\n } else if (this.type.kind === 'formatted') {\n // There is no explicit 'to-formatted' but this coercion can be implicitly\n // created by properties that expect the 'formatted' type.\n return Formatted.fromString(valueToString(this.args[0].evaluate(ctx)));\n } else if (this.type.kind === 'resolvedImage') {\n return ResolvedImage.fromString(valueToString(this.args[0].evaluate(ctx)));\n } else {\n return valueToString(this.args[0].evaluate(ctx));\n }\n }\n\n eachChild(fn: (_: Expression) => void) {\n this.args.forEach(fn);\n }\n\n outputDefined(): boolean {\n return this.args.every(arg => arg.outputDefined());\n }\n\n serialize(): SerializedExpression {\n if (this.type.kind === 'formatted') {\n return new FormatExpression([{content: this.args[0], scale: null, font: null, textColor: null}]).serialize();\n }\n\n if (this.type.kind === 'resolvedImage') {\n return new ImageExpression(this.args[0]).serialize();\n }\n\n const serialized = [`to-${this.type.kind}`];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Coercion;\n","// @flow\n\nimport {Color} from './values.js';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {FormattedSection} from './types/formatted.js';\nimport type {GlobalProperties, Feature, FeatureState} from './index.js';\nimport type {CanonicalTileID} from '../../source/tile_id.js';\nimport type {FeatureDistanceData} from '../feature_filter/index.js';\n\nconst geometryTypes = ['Unknown', 'Point', 'LineString', 'Polygon'];\n\nclass EvaluationContext {\n globals: GlobalProperties;\n feature: ?Feature;\n featureState: ?FeatureState;\n formattedSection: ?FormattedSection;\n availableImages: ?Array<string>;\n canonical: null | CanonicalTileID;\n featureTileCoord: ?Point;\n featureDistanceData: ?FeatureDistanceData;\n\n _parseColorCache: {[_: string]: ?Color};\n\n constructor() {\n this.globals = (null: any);\n this.feature = null;\n this.featureState = null;\n this.formattedSection = null;\n this._parseColorCache = {};\n this.availableImages = null;\n this.canonical = null;\n this.featureTileCoord = null;\n this.featureDistanceData = null;\n }\n\n id(): number | null {\n return this.feature && this.feature.id !== undefined ? this.feature.id : null;\n }\n\n geometryType(): null | string {\n return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null;\n }\n\n geometry(): ?Array<Array<Point>> {\n return this.feature && 'geometry' in this.feature ? this.feature.geometry : null;\n }\n\n canonicalID(): null | CanonicalTileID {\n return this.canonical;\n }\n\n properties(): {[string]: any} {\n return (this.feature && this.feature.properties) || {};\n }\n\n distanceFromCenter(): number {\n if (this.featureTileCoord && this.featureDistanceData) {\n\n const c = this.featureDistanceData.center;\n const scale = this.featureDistanceData.scale;\n const {x, y} = this.featureTileCoord;\n\n // Calculate the distance vector `d` (left handed)\n const dX = x * scale - c[0];\n const dY = y * scale - c[1];\n\n // The bearing vector `b` (left handed)\n const bX = this.featureDistanceData.bearing[0];\n const bY = this.featureDistanceData.bearing[1];\n\n // Distance is calculated as `dot(d, v)`\n const dist = (bX * dX + bY * dY);\n return dist;\n }\n\n return 0;\n }\n\n parseColor(input: string): ?Color {\n let cached = this._parseColorCache[input];\n if (!cached) {\n cached = this._parseColorCache[input] = Color.parse(input);\n }\n return cached;\n }\n}\n\nexport default EvaluationContext;\n","// @flow\n\nimport {toString} from './types.js';\n\nimport ParsingContext from './parsing_context.js';\nimport EvaluationContext from './evaluation_context.js';\nimport assert from 'assert';\n\nimport type {Expression, ExpressionRegistry} from './expression.js';\nimport type {Type} from './types.js';\nimport type {Value} from './values.js';\n\nexport type Varargs = {| type: Type |};\ntype Signature = Array<Type> | Varargs;\ntype Evaluate = (EvaluationContext, Array<Expression>) => Value;\ntype Definition = [Type, Signature, Evaluate] |\n {|type: Type, overloads: Array<[Signature, Evaluate]>|};\n\nclass CompoundExpression implements Expression {\n name: string;\n type: Type;\n _evaluate: Evaluate;\n args: Array<Expression>;\n\n static definitions: {[_: string]: Definition };\n\n constructor(name: string, type: Type, evaluate: Evaluate, args: Array<Expression>) {\n this.name = name;\n this.type = type;\n this._evaluate = evaluate;\n this.args = args;\n }\n\n evaluate(ctx: EvaluationContext): Value {\n return this._evaluate(ctx, this.args);\n }\n\n eachChild(fn: (_: Expression) => void) {\n this.args.forEach(fn);\n }\n\n outputDefined(): boolean {\n return false;\n }\n\n serialize(): Array<mixed> {\n return [this.name].concat(this.args.map(arg => arg.serialize()));\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Expression {\n const op: string = (args[0]: any);\n const definition = CompoundExpression.definitions[op];\n if (!definition) {\n return context.error(`Unknown expression \"${op}\". If you wanted a literal array, use [\"literal\", [...]].`, 0);\n }\n\n // Now check argument types against each signature\n const type = Array.isArray(definition) ?\n definition[0] : definition.type;\n\n const availableOverloads = Array.isArray(definition) ?\n [[definition[1], definition[2]]] :\n definition.overloads;\n\n const overloads = availableOverloads.filter(([signature]) => (\n !Array.isArray(signature) || // varags\n signature.length === args.length - 1 // correct param count\n ));\n\n let signatureContext: ParsingContext = (null: any);\n\n for (const [params, evaluate] of overloads) {\n // Use a fresh context for each attempted signature so that, if\n // we eventually succeed, we haven't polluted `context.errors`.\n signatureContext = new ParsingContext(context.registry, context.path, null, context.scope);\n\n // First parse all the args, potentially coercing to the\n // types expected by this overload.\n const parsedArgs: Array<Expression> = [];\n let argParseFailed = false;\n for (let i = 1; i < args.length; i++) {\n const arg = args[i];\n const expectedType = Array.isArray(params) ?\n params[i - 1] :\n params.type;\n\n const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType);\n if (!parsed) {\n argParseFailed = true;\n break;\n }\n parsedArgs.push(parsed);\n }\n if (argParseFailed) {\n // Couldn't coerce args of this overload to expected type, move\n // on to next one.\n continue;\n }\n\n if (Array.isArray(params)) {\n if (params.length !== parsedArgs.length) {\n signatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`);\n continue;\n }\n }\n\n for (let i = 0; i < parsedArgs.length; i++) {\n const expected = Array.isArray(params) ? params[i] : params.type;\n const arg = parsedArgs[i];\n signatureContext.concat(i + 1).checkSubtype(expected, arg.type);\n }\n\n if (signatureContext.errors.length === 0) {\n return new CompoundExpression(op, type, evaluate, parsedArgs);\n }\n }\n\n assert(!signatureContext || signatureContext.errors.length > 0);\n\n if (overloads.length === 1) {\n context.errors.push(...signatureContext.errors);\n } else {\n const expected = overloads.length ? overloads : availableOverloads;\n const signatures = expected\n .map(([params]) => stringifySignature(params))\n .join(' | ');\n\n const actualTypes = [];\n // For error message, re-parse arguments without trying to\n // apply any coercions\n for (let i = 1; i < args.length; i++) {\n const parsed = context.parse(args[i], 1 + actualTypes.length);\n if (!parsed) return null;\n actualTypes.push(toString(parsed.type));\n }\n context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(', ')}) instead.`);\n }\n\n return null;\n }\n\n static register(\n registry: ExpressionRegistry,\n definitions: {[_: string]: Definition }\n ) {\n assert(!CompoundExpression.definitions);\n CompoundExpression.definitions = definitions;\n for (const name in definitions) {\n // $FlowFixMe[method-unbinding]\n registry[name] = CompoundExpression;\n }\n }\n}\n\nfunction stringifySignature(signature: Signature): string {\n if (Array.isArray(signature)) {\n return `(${signature.map(toString).join(', ')})`;\n } else {\n return `(${toString(signature.type)}...)`;\n }\n}\n\nexport default CompoundExpression;\n","// @flow\n\nimport {StringType, BooleanType, CollatorType} from '../types.js';\nimport Collator from '../types/collator.js';\n\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type {Type} from '../types.js';\n\nexport default class CollatorExpression implements Expression {\n type: Type;\n caseSensitive: Expression;\n diacriticSensitive: Expression;\n locale: Expression | null;\n\n constructor(caseSensitive: Expression, diacriticSensitive: Expression, locale: Expression | null) {\n this.type = CollatorType;\n this.locale = locale;\n this.caseSensitive = caseSensitive;\n this.diacriticSensitive = diacriticSensitive;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Expression {\n if (args.length !== 2)\n return context.error(`Expected one argument.`);\n\n const options = (args[1]: any);\n if (typeof options !== \"object\" || Array.isArray(options))\n return context.error(`Collator options argument must be an object.`);\n\n const caseSensitive = context.parse(\n options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType);\n if (!caseSensitive) return null;\n\n const diacriticSensitive = context.parse(\n options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType);\n if (!diacriticSensitive) return null;\n\n let locale = null;\n if (options['locale']) {\n locale = context.parse(options['locale'], 1, StringType);\n if (!locale) return null;\n }\n\n return new CollatorExpression(caseSensitive, diacriticSensitive, locale);\n }\n\n evaluate(ctx: EvaluationContext): Collator {\n return new Collator(this.caseSensitive.evaluate(ctx), this.diacriticSensitive.evaluate(ctx), this.locale ? this.locale.evaluate(ctx) : null);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.caseSensitive);\n fn(this.diacriticSensitive);\n if (this.locale) {\n fn(this.locale);\n }\n }\n\n outputDefined(): boolean {\n // Technically the set of possible outputs is the combinatoric set of Collators produced\n // by all possible outputs of locale/caseSensitive/diacriticSensitive\n // But for the primary use of Collators in comparison operators, we ignore the Collator's\n // possible outputs anyway, so we can get away with leaving this false for now.\n return false;\n }\n\n serialize(): SerializedExpression {\n const options = {};\n options['case-sensitive'] = this.caseSensitive.serialize();\n options['diacritic-sensitive'] = this.diacriticSensitive.serialize();\n if (this.locale) {\n options['locale'] = this.locale.serialize();\n }\n return [\"collator\", options];\n }\n}\n","// @flow\n\nimport {isValue} from '../values.js';\nimport type {Type} from '../types.js';\nimport {BooleanType} from '../types.js';\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type Point from '@mapbox/point-geometry';\nimport type {GeoJSON, GeoJSONPosition, GeoJSONPolygon, GeoJSONMultiPolygon} from '@mapbox/geojson-types';\nimport type {CanonicalTileID} from '../../../source/tile_id.js';\n\ntype GeoJSONPolygons =| GeoJSONPolygon | GeoJSONMultiPolygon;\n\n// minX, minY, maxX, maxY\ntype BBox = [number, number, number, number];\nconst EXTENT = 8192;\n\nfunction updateBBox(bbox: BBox, coord: GeoJSONPosition) {\n bbox[0] = Math.min(bbox[0], coord[0]);\n bbox[1] = Math.min(bbox[1], coord[1]);\n bbox[2] = Math.max(bbox[2], coord[0]);\n bbox[3] = Math.max(bbox[3], coord[1]);\n}\n\nfunction mercatorXfromLng(lng: number) {\n return (180 + lng) / 360;\n}\n\nfunction mercatorYfromLat(lat: number) {\n return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360;\n}\n\nfunction boxWithinBox(bbox1: BBox, bbox2: BBox) {\n if (bbox1[0] <= bbox2[0]) return false;\n if (bbox1[2] >= bbox2[2]) return false;\n if (bbox1[1] <= bbox2[1]) return false;\n if (bbox1[3] >= bbox2[3]) return false;\n return true;\n}\n\nfunction getTileCoordinates(p: GeoJSONPosition, canonical: CanonicalTileID) {\n const x = mercatorXfromLng(p[0]);\n const y = mercatorYfromLat(p[1]);\n const tilesAtZoom = Math.pow(2, canonical.z);\n return [Math.round(x * tilesAtZoom * EXTENT), Math.round(y * tilesAtZoom * EXTENT)];\n}\n\nfunction onBoundary(p: GeoJSONPosition, p1: GeoJSONPosition, p2: GeoJSONPosition) {\n const x1 = p[0] - p1[0];\n const y1 = p[1] - p1[1];\n const x2 = p[0] - p2[0];\n const y2 = p[1] - p2[1];\n return (x1 * y2 - x2 * y1 === 0) && (x1 * x2 <= 0) && (y1 * y2 <= 0);\n}\n\nfunction rayIntersect(p: GeoJSONPosition, p1: GeoJSONPosition, p2: GeoJSONPosition) {\n return ((p1[1] > p[1]) !== (p2[1] > p[1])) && (p[0] < (p2[0] - p1[0]) * (p[1] - p1[1]) / (p2[1] - p1[1]) + p1[0]);\n}\n\n// ray casting algorithm for detecting if point is in polygon\nfunction pointWithinPolygon(point: GeoJSONPosition, rings: Array<Array<GeoJSONPosition>>) {\n let inside = false;\n for (let i = 0, len = rings.length; i < len; i++) {\n const ring = rings[i];\n for (let j = 0, len2 = ring.length; j < len2 - 1; j++) {\n if (onBoundary(point, ring[j], ring[j + 1])) return false;\n if (rayIntersect(point, ring[j], ring[j + 1])) inside = !inside;\n }\n }\n return inside;\n}\n\nfunction pointWithinPolygons(point: GeoJSONPosition, polygons: Array<Array<Array<GeoJSONPosition>>>) {\n for (let i = 0; i < polygons.length; i++) {\n if (pointWithinPolygon(point, polygons[i])) return true;\n }\n return false;\n}\n\nfunction perp(v1: GeoJSONPosition, v2: GeoJSONPosition) {\n return (v1[0] * v2[1] - v1[1] * v2[0]);\n}\n\n// check if p1 and p2 are in different sides of line segment q1->q2\nfunction twoSided(p1: GeoJSONPosition, p2: GeoJSONPosition, q1: GeoJSONPosition, q2: GeoJSONPosition) {\n // q1->p1 (x1, y1), q1->p2 (x2, y2), q1->q2 (x3, y3)\n const x1 = p1[0] - q1[0];\n const y1 = p1[1] - q1[1];\n const x2 = p2[0] - q1[0];\n const y2 = p2[1] - q1[1];\n const x3 = q2[0] - q1[0];\n const y3 = q2[1] - q1[1];\n const det1 = (x1 * y3 - x3 * y1);\n const det2 = (x2 * y3 - x3 * y2);\n if ((det1 > 0 && det2 < 0) || (det1 < 0 && det2 > 0)) return true;\n return false;\n}\n// a, b are end points for line segment1, c and d are end points for line segment2\nfunction lineIntersectLine(a: GeoJSONPosition, b: GeoJSONPosition, c: GeoJSONPosition, d: GeoJSONPosition) {\n // check if two segments are parallel or not\n // precondition is end point a, b is inside polygon, if line a->b is\n // parallel to polygon edge c->d, then a->b won't intersect with c->d\n const vectorP = [b[0] - a[0], b[1] - a[1]];\n const vectorQ = [d[0] - c[0], d[1] - c[1]];\n if (perp(vectorQ, vectorP) === 0) return false;\n\n // If lines are intersecting with each other, the relative location should be:\n // a and b lie in different sides of segment c->d\n // c and d lie in different sides of segment a->b\n if (twoSided(a, b, c, d) && twoSided(c, d, a, b)) return true;\n return false;\n}\n\nfunction lineIntersectPolygon(p1: GeoJSONPosition, p2: GeoJSONPosition, polygon: Array<Array<GeoJSONPosition>>) {\n for (const ring of polygon) {\n // loop through every edge of the ring\n for (let j = 0; j < ring.length - 1; ++j) {\n if (lineIntersectLine(p1, p2, ring[j], ring[j + 1])) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction lineStringWithinPolygon(line: Array<GeoJSONPosition>, polygon: Array<Array<GeoJSONPosition>>) {\n // First, check if geometry points of line segments are all inside polygon\n for (let i = 0; i < line.length; ++i) {\n if (!pointWithinPolygon(line[i], polygon)) {\n return false;\n }\n }\n\n // Second, check if there is line segment intersecting polygon edge\n for (let i = 0; i < line.length - 1; ++i) {\n if (lineIntersectPolygon(line[i], line[i + 1], polygon)) {\n return false;\n }\n }\n return true;\n}\n\nfunction lineStringWithinPolygons(line: Array<GeoJSONPosition>, polygons: Array<Array<Array<GeoJSONPosition>>>) {\n for (let i = 0; i < polygons.length; i++) {\n if (lineStringWithinPolygon(line, polygons[i])) return true;\n }\n return false;\n}\n\nfunction getTilePolygon(coordinates: Array<Array<GeoJSONPosition>>, bbox: BBox, canonical: CanonicalTileID) {\n const polygon = [];\n for (let i = 0; i < coordinates.length; i++) {\n const ring = [];\n for (let j = 0; j < coordinates[i].length; j++) {\n const coord = getTileCoordinates(coordinates[i][j], canonical);\n updateBBox(bbox, coord);\n ring.push(coord);\n }\n polygon.push(ring);\n }\n return polygon;\n}\n\nfunction getTilePolygons(coordinates: Array<Array<Array<GeoJSONPosition>>>, bbox: BBox, canonical: CanonicalTileID) {\n const polygons = [];\n for (let i = 0; i < coordinates.length; i++) {\n const polygon = getTilePolygon(coordinates[i], bbox, canonical);\n polygons.push(polygon);\n }\n return polygons;\n}\n\nfunction updatePoint(p: GeoJSONPosition, bbox: BBox, polyBBox: Array<number>, worldSize: number) {\n if (p[0] < polyBBox[0] || p[0] > polyBBox[2]) {\n const halfWorldSize = worldSize * 0.5;\n let shift = (p[0] - polyBBox[0] > halfWorldSize) ? -worldSize : (polyBBox[0] - p[0] > halfWorldSize) ? worldSize : 0;\n if (shift === 0) {\n shift = (p[0] - polyBBox[2] > halfWorldSize) ? -worldSize : (polyBBox[2] - p[0] > halfWorldSize) ? worldSize : 0;\n }\n p[0] += shift;\n }\n updateBBox(bbox, p);\n}\n\nfunction resetBBox(bbox: BBox) {\n bbox[0] = bbox[1] = Infinity;\n bbox[2] = bbox[3] = -Infinity;\n}\n\nfunction getTilePoints(geometry: ?Array<Array<Point>>, pointBBox: BBox, polyBBox: Array<number>, canonical: CanonicalTileID) {\n const worldSize = Math.pow(2, canonical.z) * EXTENT;\n const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];\n const tilePoints = [];\n if (!geometry) return tilePoints;\n for (const points of geometry) {\n for (const point of points) {\n const p = [point.x + shifts[0], point.y + shifts[1]];\n updatePoint(p, pointBBox, polyBBox, worldSize);\n tilePoints.push(p);\n }\n }\n return tilePoints;\n}\n\nfunction getTileLines(geometry: ?Array<Array<Point>>, lineBBox: BBox, polyBBox: Array<number>, canonical: CanonicalTileID) {\n const worldSize = Math.pow(2, canonical.z) * EXTENT;\n const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];\n const tileLines: Array<Array<GeoJSONPosition>> = [];\n if (!geometry) return tileLines;\n for (const line of geometry) {\n const tileLine = [];\n for (const point of line) {\n const p: GeoJSONPosition = [point.x + shifts[0], point.y + shifts[1]];\n updateBBox(lineBBox, p);\n tileLine.push(p);\n }\n tileLines.push(tileLine);\n }\n if (lineBBox[2] - lineBBox[0] <= worldSize / 2) {\n resetBBox(lineBBox);\n for (const line of tileLines) {\n for (const p of line) {\n updatePoint(p, lineBBox, polyBBox, worldSize);\n }\n }\n }\n return tileLines;\n}\n\nfunction pointsWithinPolygons(ctx: EvaluationContext, polygonGeometry: GeoJSONPolygons) {\n const pointBBox = [Infinity, Infinity, -Infinity, -Infinity];\n const polyBBox = [Infinity, Infinity, -Infinity, -Infinity];\n\n const canonical = ctx.canonicalID();\n if (!canonical) {\n return false;\n }\n\n if (polygonGeometry.type === 'Polygon') {\n const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);\n const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);\n if (!boxWithinBox(pointBBox, polyBBox)) return false;\n\n for (const point of tilePoints) {\n if (!pointWithinPolygon(point, tilePolygon)) return false;\n }\n }\n if (polygonGeometry.type === 'MultiPolygon') {\n const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);\n const tilePoints = getTilePoints(ctx.geometry(), pointBBox, polyBBox, canonical);\n if (!boxWithinBox(pointBBox, polyBBox)) return false;\n\n for (const point of tilePoints) {\n if (!pointWithinPolygons(point, tilePolygons)) return false;\n }\n }\n\n return true;\n}\n\nfunction linesWithinPolygons(ctx: EvaluationContext, polygonGeometry: GeoJSONPolygons) {\n const lineBBox = [Infinity, Infinity, -Infinity, -Infinity];\n const polyBBox = [Infinity, Infinity, -Infinity, -Infinity];\n\n const canonical = ctx.canonicalID();\n if (!canonical) {\n return false;\n }\n\n if (polygonGeometry.type === 'Polygon') {\n const tilePolygon = getTilePolygon(polygonGeometry.coordinates, polyBBox, canonical);\n const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);\n if (!boxWithinBox(lineBBox, polyBBox)) return false;\n\n for (const line of tileLines) {\n if (!lineStringWithinPolygon(line, tilePolygon)) return false;\n }\n }\n if (polygonGeometry.type === 'MultiPolygon') {\n const tilePolygons = getTilePolygons(polygonGeometry.coordinates, polyBBox, canonical);\n const tileLines = getTileLines(ctx.geometry(), lineBBox, polyBBox, canonical);\n if (!boxWithinBox(lineBBox, polyBBox)) return false;\n\n for (const line of tileLines) {\n if (!lineStringWithinPolygons(line, tilePolygons)) return false;\n }\n }\n return true;\n}\n\nclass Within implements Expression {\n type: Type;\n geojson: GeoJSON\n geometries: GeoJSONPolygons;\n\n constructor(geojson: GeoJSON, geometries: GeoJSONPolygons) {\n this.type = BooleanType;\n this.geojson = geojson;\n this.geometries = geometries;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Within {\n if (args.length !== 2)\n return context.error(`'within' expression requires exactly one argument, but found ${args.length - 1} instead.`);\n if (isValue(args[1])) {\n const geojson = (args[1]: Object);\n if (geojson.type === 'FeatureCollection') {\n for (let i = 0; i < geojson.features.length; ++i) {\n const type = geojson.features[i].geometry.type;\n if (type === 'Polygon' || type === 'MultiPolygon') {\n return new Within(geojson, geojson.features[i].geometry);\n }\n }\n } else if (geojson.type === 'Feature') {\n const type = geojson.geometry.type;\n if (type === 'Polygon' || type === 'MultiPolygon') {\n return new Within(geojson, geojson.geometry);\n }\n } else if (geojson.type === 'Polygon' || geojson.type === 'MultiPolygon') {\n return new Within(geojson, geojson);\n }\n }\n return context.error(`'within' expression requires valid geojson object that contains polygon geometry type.`);\n }\n\n evaluate(ctx: EvaluationContext): boolean {\n if (ctx.geometry() != null && ctx.canonicalID() != null) {\n if (ctx.geometryType() === 'Point') {\n return pointsWithinPolygons(ctx, this.geometries);\n } else if (ctx.geometryType() === 'LineString') {\n return linesWithinPolygons(ctx, this.geometries);\n }\n }\n return false;\n }\n\n eachChild() {}\n\n outputDefined(): boolean {\n return true;\n }\n\n serialize(): SerializedExpression {\n return [\"within\", this.geojson];\n }\n\n}\n\nexport default Within;\n","// @flow\n\nimport CompoundExpression from './compound_expression.js';\nimport Within from './definitions/within.js';\nimport type {Expression} from './expression.js';\n\nfunction isFeatureConstant(e: Expression): boolean {\n if (e instanceof CompoundExpression) {\n if (e.name === 'get' && e.args.length === 1) {\n return false;\n } else if (e.name === 'feature-state') {\n return false;\n } else if (e.name === 'has' && e.args.length === 1) {\n return false;\n } else if (\n e.name === 'properties' ||\n e.name === 'geometry-type' ||\n e.name === 'id'\n ) {\n return false;\n } else if (/^filter-/.test(e.name)) {\n return false;\n }\n }\n\n if (e instanceof Within) {\n return false;\n }\n\n let result = true;\n e.eachChild(arg => {\n if (result && !isFeatureConstant(arg)) { result = false; }\n });\n return result;\n}\n\nfunction isStateConstant(e: Expression): boolean {\n if (e instanceof CompoundExpression) {\n if (e.name === 'feature-state') {\n return false;\n }\n }\n let result = true;\n e.eachChild(arg => {\n if (result && !isStateConstant(arg)) { result = false; }\n });\n return result;\n}\n\nfunction isGlobalPropertyConstant(e: Expression, properties: Array<string>): boolean {\n if (e instanceof CompoundExpression && properties.indexOf(e.name) >= 0) { return false; }\n let result = true;\n e.eachChild((arg) => {\n if (result && !isGlobalPropertyConstant(arg, properties)) { result = false; }\n });\n return result;\n}\n\nexport {isFeatureConstant, isGlobalPropertyConstant, isStateConstant};\n","// @flow\n\nimport type {Type} from '../types.js';\nimport type {Expression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\n\nclass Var implements Expression {\n type: Type;\n name: string;\n boundExpression: Expression;\n\n constructor(name: string, boundExpression: Expression) {\n this.type = boundExpression.type;\n this.name = name;\n this.boundExpression = boundExpression;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): void | Var {\n if (args.length !== 2 || typeof args[1] !== 'string')\n return context.error(`'var' expression requires exactly one string literal argument.`);\n\n const name = args[1];\n if (!context.scope.has(name)) {\n return context.error(`Unknown variable \"${name}\". Make sure \"${name}\" has been bound in an enclosing \"let\" expression before using it.`, 1);\n }\n\n return new Var(name, context.scope.get(name));\n }\n\n evaluate(ctx: EvaluationContext): any {\n return this.boundExpression.evaluate(ctx);\n }\n\n eachChild() {}\n\n outputDefined(): boolean {\n return false;\n }\n\n serialize(): Array<string> {\n return [\"var\", this.name];\n }\n}\n\nexport default Var;\n","// @flow\n\nimport Scope from './scope.js';\nimport {checkSubtype} from './types.js';\nimport ParsingError from './parsing_error.js';\nimport Literal from './definitions/literal.js';\nimport Assertion from './definitions/assertion.js';\nimport Coercion from './definitions/coercion.js';\nimport EvaluationContext from './evaluation_context.js';\nimport CompoundExpression from './compound_expression.js';\nimport CollatorExpression from './definitions/collator.js';\nimport Within from './definitions/within.js';\nimport {isGlobalPropertyConstant, isFeatureConstant} from './is_constant.js';\nimport Var from './definitions/var.js';\n\nimport type {Expression, ExpressionRegistry} from './expression.js';\nimport type {Type} from './types.js';\n\n/**\n * State associated parsing at a given point in an expression tree.\n * @private\n */\nclass ParsingContext {\n registry: ExpressionRegistry;\n path: Array<number>;\n key: string;\n scope: Scope;\n errors: Array<ParsingError>;\n\n // The expected type of this expression. Provided only to allow Expression\n // implementations to infer argument types: Expression#parse() need not\n // check that the output type of the parsed expression matches\n // `expectedType`.\n expectedType: ?Type;\n\n constructor(\n registry: ExpressionRegistry,\n path: Array<number> = [],\n expectedType: ?Type,\n scope: Scope = new Scope(),\n errors: Array<ParsingError> = []\n ) {\n this.registry = registry;\n this.path = path;\n this.key = path.map(part => `[${part}]`).join('');\n this.scope = scope;\n this.errors = errors;\n this.expectedType = expectedType;\n }\n\n /**\n * @param expr the JSON expression to parse\n * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed\n * @param options\n * @param options.omitTypeAnnotations set true to omit inferred type annotations. Caller beware: with this option set, the parsed expression's type will NOT satisfy `expectedType` if it would normally be wrapped in an inferred annotation.\n * @private\n */\n parse(\n expr: mixed,\n index?: number,\n expectedType?: ?Type,\n bindings?: Array<[string, Expression]>,\n options: {typeAnnotation?: 'assert' | 'coerce' | 'omit'} = {}\n ): ?Expression {\n if (index) {\n return this.concat(index, expectedType, bindings)._parse(expr, options);\n }\n return this._parse(expr, options);\n }\n\n _parse(expr: mixed, options: {typeAnnotation?: 'assert' | 'coerce' | 'omit'}): ?Expression {\n if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') {\n expr = ['literal', expr];\n }\n\n function annotate(parsed: Expression, type: Type, typeAnnotation: 'assert' | 'coerce' | 'omit') {\n if (typeAnnotation === 'assert') {\n return new Assertion(type, [parsed]);\n } else if (typeAnnotation === 'coerce') {\n return new Coercion(type, [parsed]);\n } else {\n return parsed;\n }\n }\n\n if (Array.isArray(expr)) {\n if (expr.length === 0) {\n return this.error(`Expected an array with at least one element. If you wanted a literal array, use [\"literal\", []].`);\n }\n\n const op = expr[0];\n if (typeof op !== 'string') {\n this.error(`Expression name must be a string, but found ${typeof op} instead. If you wanted a literal array, use [\"literal\", [...]].`, 0);\n return null;\n }\n\n const Expr = this.registry[op];\n if (Expr) {\n let parsed = Expr.parse(expr, this);\n if (!parsed) return null;\n\n if (this.expectedType) {\n const expected = this.expectedType;\n const actual = parsed.type;\n\n // When we expect a number, string, boolean, or array but have a value, wrap it in an assertion.\n // When we expect a color or formatted string, but have a string or value, wrap it in a coercion.\n // Otherwise, we do static type-checking.\n //\n // These behaviors are overridable for:\n // * The \"coalesce\" operator, which needs to omit type annotations.\n // * String-valued properties (e.g. `text-field`), where coercion is more convenient than assertion.\n //\n if ((expected.kind === 'string' || expected.kind === 'number' || expected.kind === 'boolean' || expected.kind === 'object' || expected.kind === 'array') && actual.kind === 'value') {\n parsed = annotate(parsed, expected, options.typeAnnotation || 'assert');\n } else if ((expected.kind === 'color' || expected.kind === 'formatted' || expected.kind === 'resolvedImage') && (actual.kind === 'value' || actual.kind === 'string')) {\n parsed = annotate(parsed, expected, options.typeAnnotation || 'coerce');\n } else if (this.checkSubtype(expected, actual)) {\n return null;\n }\n }\n\n // If an expression's arguments are all literals, we can evaluate\n // it immediately and replace it with a literal value in the\n // parsed/compiled result. Expressions that expect an image should\n // not be resolved here so we can later get the available images.\n if (!(parsed instanceof Literal) && (parsed.type.kind !== 'resolvedImage') && isConstant(parsed)) {\n const ec = new EvaluationContext();\n try {\n parsed = new Literal(parsed.type, parsed.evaluate(ec));\n } catch (e) {\n this.error(e.message);\n return null;\n }\n }\n\n return parsed;\n }\n\n return this.error(`Unknown expression \"${op}\". If you wanted a literal array, use [\"literal\", [...]].`, 0);\n } else if (typeof expr === 'undefined') {\n return this.error(`'undefined' value invalid. Use null instead.`);\n } else if (typeof expr === 'object') {\n return this.error(`Bare objects invalid. Use [\"literal\", {...}] instead.`);\n } else {\n return this.error(`Expected an array, but found ${typeof expr} instead.`);\n }\n }\n\n /**\n * Returns a copy of this context suitable for parsing the subexpression at\n * index `index`, optionally appending to 'let' binding map.\n *\n * Note that `errors` property, intended for collecting errors while\n * parsing, is copied by reference rather than cloned.\n * @private\n */\n concat(index: number, expectedType?: ?Type, bindings?: Array<[string, Expression]>): ParsingContext {\n const path = typeof index === 'number' ? this.path.concat(index) : this.path;\n const scope = bindings ? this.scope.concat(bindings) : this.scope;\n return new ParsingContext(\n this.registry,\n path,\n expectedType || null,\n scope,\n this.errors\n );\n }\n\n /**\n * Push a parsing (or type checking) error into the `this.errors`\n * @param error The message\n * @param keys Optionally specify the source of the error at a child\n * of the current expression at `this.key`.\n * @private\n */\n error(error: string, ...keys: Array<number>) {\n const key = `${this.key}${keys.map(k => `[${k}]`).join('')}`;\n this.errors.push(new ParsingError(key, error));\n }\n\n /**\n * Returns null if `t` is a subtype of `expected`; otherwise returns an\n * error message and also pushes it to `this.errors`.\n */\n checkSubtype(expected: Type, t: Type): ?string {\n const error = checkSubtype(expected, t);\n if (error) this.error(error);\n return error;\n }\n}\n\nexport default ParsingContext;\n\nfunction isConstant(expression: Expression) {\n if (expression instanceof Var) {\n return isConstant(expression.boundExpression);\n } else if (expression instanceof CompoundExpression && expression.name === 'error') {\n return false;\n } else if (expression instanceof CollatorExpression) {\n // Although the results of a Collator expression with fixed arguments\n // generally shouldn't change between executions, we can't serialize them\n // as constant expressions because results change based on environment.\n return false;\n } else if (expression instanceof Within) {\n return false;\n }\n\n const isTypeAnnotation = expression instanceof Coercion ||\n expression instanceof Assertion;\n\n let childrenConstant = true;\n expression.eachChild(child => {\n // We can _almost_ assume that if `expressions` children are constant,\n // they would already have been evaluated to Literal values when they\n // were parsed. Type annotations are the exception, because they might\n // have been inferred and added after a child was parsed.\n\n // So we recurse into isConstant() for the children of type annotations,\n // but otherwise simply check whether they are Literals.\n if (isTypeAnnotation) {\n childrenConstant = childrenConstant && isConstant(child);\n } else {\n childrenConstant = childrenConstant && child instanceof Literal;\n }\n });\n if (!childrenConstant) {\n return false;\n }\n\n return isFeatureConstant(expression) &&\n isGlobalPropertyConstant(expression, ['zoom', 'heatmap-density', 'line-progress', 'sky-radial-progress', 'accumulated', 'is-supported-script', 'pitch', 'distance-from-center']);\n}\n","// @flow\n\nimport RuntimeError from './runtime_error.js';\n\nimport type {Expression} from './expression.js';\n\nexport type Stops = Array<[number, Expression]>;\n\n/**\n * Returns the index of the last stop <= input, or 0 if it doesn't exist.\n * @private\n */\nexport function findStopLessThanOrEqualTo(stops: Array<number>, input: number): number {\n const lastIndex = stops.length - 1;\n let lowerIndex = 0;\n let upperIndex = lastIndex;\n let currentIndex = 0;\n let currentValue, nextValue;\n\n while (lowerIndex <= upperIndex) {\n currentIndex = Math.floor((lowerIndex + upperIndex) / 2);\n currentValue = stops[currentIndex];\n nextValue = stops[currentIndex + 1];\n\n if (currentValue <= input) {\n if (currentIndex === lastIndex || input < nextValue) { // Search complete\n return currentIndex;\n }\n\n lowerIndex = currentIndex + 1;\n } else if (currentValue > input) {\n upperIndex = currentIndex - 1;\n } else {\n throw new RuntimeError('Input is not a number.');\n }\n }\n\n return 0;\n}\n","// @flow\n\nimport {NumberType} from '../types.js';\n\nimport {findStopLessThanOrEqualTo} from '../stops.js';\n\nimport type {Stops} from '../stops.js';\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type {Type} from '../types.js';\n\nclass Step implements Expression {\n type: Type;\n\n input: Expression;\n labels: Array<number>;\n outputs: Array<Expression>;\n\n constructor(type: Type, input: Expression, stops: Stops) {\n this.type = type;\n this.input = input;\n\n this.labels = [];\n this.outputs = [];\n for (const [label, expression] of stops) {\n this.labels.push(label);\n this.outputs.push(expression);\n }\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Step {\n if (args.length - 1 < 4) {\n return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n }\n\n if ((args.length - 1) % 2 !== 0) {\n return context.error(`Expected an even number of arguments.`);\n }\n\n const input = context.parse(args[1], 1, NumberType);\n if (!input) return null;\n\n const stops: Stops = [];\n\n let outputType: Type = (null: any);\n if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n\n for (let i = 1; i < args.length; i += 2) {\n const label = i === 1 ? -Infinity : args[i];\n const value = args[i + 1];\n\n const labelKey = i;\n const valueKey = i + 1;\n\n if (typeof label !== 'number') {\n return context.error('Input/output pairs for \"step\" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey);\n }\n\n if (stops.length && stops[stops.length - 1][0] >= label) {\n return context.error('Input/output pairs for \"step\" expressions must be arranged with input values in strictly ascending order.', labelKey);\n }\n\n const parsed = context.parse(value, valueKey, outputType);\n if (!parsed) return null;\n outputType = outputType || parsed.type;\n stops.push([label, parsed]);\n }\n\n return new Step(outputType, input, stops);\n }\n\n evaluate(ctx: EvaluationContext): any {\n const labels = this.labels;\n const outputs = this.outputs;\n\n if (labels.length === 1) {\n return outputs[0].evaluate(ctx);\n }\n\n const value = ((this.input.evaluate(ctx): any): number);\n if (value <= labels[0]) {\n return outputs[0].evaluate(ctx);\n }\n\n const stopCount = labels.length;\n if (value >= labels[stopCount - 1]) {\n return outputs[stopCount - 1].evaluate(ctx);\n }\n\n const index = findStopLessThanOrEqualTo(labels, value);\n return outputs[index].evaluate(ctx);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n for (const expression of this.outputs) {\n fn(expression);\n }\n }\n\n outputDefined(): boolean {\n return this.outputs.every(out => out.outputDefined());\n }\n\n serialize(): SerializedExpression {\n const serialized = [\"step\", this.input.serialize()];\n for (let i = 0; i < this.labels.length; i++) {\n if (i > 0) {\n serialized.push(this.labels[i]);\n }\n serialized.push(this.outputs[i].serialize());\n }\n return serialized;\n }\n}\n\nexport default Step;\n","// @flow\n\nimport Color from './color.js';\n\nexport function number(a: number, b: number, t: number): number {\n return (a * (1 - t)) + (b * t);\n}\n\nexport function color(from: Color, to: Color, t: number): Color {\n return new Color(\n number(from.r, to.r, t),\n number(from.g, to.g, t),\n number(from.b, to.b, t),\n number(from.a, to.a, t)\n );\n}\n\nexport function array(from: Array<number>, to: Array<number>, t: number): Array<number> {\n return from.map((d, i) => {\n return number(d, to[i], t);\n });\n}\n","// @flow\n\nimport Color from './color.js';\n\nimport {number as interpolateNumber} from './interpolate.js';\n\ntype LABColor = {\n l: number,\n a: number,\n b: number,\n alpha: number\n};\n\ntype HCLColor = {\n h: number,\n c: number,\n l: number,\n alpha: number\n};\n\n// Constants\nconst Xn = 0.950470, // D65 standard referent\n Yn = 1,\n Zn = 1.088830,\n t0 = 4 / 29,\n t1 = 6 / 29,\n t2 = 3 * t1 * t1,\n t3 = t1 * t1 * t1,\n deg2rad = Math.PI / 180,\n rad2deg = 180 / Math.PI;\n\n// Utilities\nfunction xyz2lab(t: number) {\n return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0;\n}\n\nfunction lab2xyz(t: number) {\n return t > t1 ? t * t * t : t2 * (t - t0);\n}\n\nfunction xyz2rgb(x: number) {\n return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055);\n}\n\nfunction rgb2xyz(x: number) {\n x /= 255;\n return x <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);\n}\n\n// LAB\nfunction rgbToLab(rgbColor: Color): LABColor {\n const b = rgb2xyz(rgbColor.r),\n a = rgb2xyz(rgbColor.g),\n l = rgb2xyz(rgbColor.b),\n x = xyz2lab((0.4124564 * b + 0.3575761 * a + 0.1804375 * l) / Xn),\n y = xyz2lab((0.2126729 * b + 0.7151522 * a + 0.0721750 * l) / Yn),\n z = xyz2lab((0.0193339 * b + 0.1191920 * a + 0.9503041 * l) / Zn);\n\n return {\n l: 116 * y - 16,\n a: 500 * (x - y),\n b: 200 * (y - z),\n alpha: rgbColor.a\n };\n}\n\nfunction labToRgb(labColor: LABColor): Color {\n let y = (labColor.l + 16) / 116,\n x = isNaN(labColor.a) ? y : y + labColor.a / 500,\n z = isNaN(labColor.b) ? y : y - labColor.b / 200;\n y = Yn * lab2xyz(y);\n x = Xn * lab2xyz(x);\n z = Zn * lab2xyz(z);\n return new Color(\n xyz2rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z), // D65 -> sRGB\n xyz2rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z),\n xyz2rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z),\n labColor.alpha\n );\n}\n\nfunction interpolateLab(from: LABColor, to: LABColor, t: number): LABColor {\n return {\n l: interpolateNumber(from.l, to.l, t),\n a: interpolateNumber(from.a, to.a, t),\n b: interpolateNumber(from.b, to.b, t),\n alpha: interpolateNumber(from.alpha, to.alpha, t)\n };\n}\n\n// HCL\nfunction rgbToHcl(rgbColor: Color): HCLColor {\n const {l, a, b} = rgbToLab(rgbColor);\n const h = Math.atan2(b, a) * rad2deg;\n return {\n h: h < 0 ? h + 360 : h,\n c: Math.sqrt(a * a + b * b),\n l,\n alpha: rgbColor.a\n };\n}\n\nfunction hclToRgb(hclColor: HCLColor): Color {\n const h = hclColor.h * deg2rad,\n c = hclColor.c,\n l = hclColor.l;\n return labToRgb({\n l,\n a: Math.cos(h) * c,\n b: Math.sin(h) * c,\n alpha: hclColor.alpha\n });\n}\n\nfunction interpolateHue(a: number, b: number, t: number) {\n const d = b - a;\n return a + t * (d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d);\n}\n\nfunction interpolateHcl(from: HCLColor, to: HCLColor, t: number): HCLColor {\n return {\n h: interpolateHue(from.h, to.h, t),\n c: interpolateNumber(from.c, to.c, t),\n l: interpolateNumber(from.l, to.l, t),\n alpha: interpolateNumber(from.alpha, to.alpha, t)\n };\n}\n\nexport const lab = {\n forward: rgbToLab,\n reverse: labToRgb,\n interpolate: interpolateLab\n};\n\nexport const hcl = {\n forward: rgbToHcl,\n reverse: hclToRgb,\n interpolate: interpolateHcl\n};\n","// @flow\n\nimport UnitBezier from '@mapbox/unitbezier';\n\nimport * as interpolate from '../../util/interpolate.js';\nimport {toString, NumberType, ColorType} from '../types.js';\nimport {findStopLessThanOrEqualTo} from '../stops.js';\nimport {hcl, lab} from '../../util/color_spaces.js';\nimport Color from '../../util/color.js';\n\nimport type {Stops} from '../stops.js';\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type {Type} from '../types.js';\n\nexport type InterpolationType =\n { name: 'linear' } |\n { name: 'exponential', base: number } |\n { name: 'cubic-bezier', controlPoints: [number, number, number, number] };\n\nclass Interpolate implements Expression {\n type: Type;\n\n operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab';\n interpolation: InterpolationType;\n input: Expression;\n labels: Array<number>;\n outputs: Array<Expression>;\n\n constructor(type: Type, operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab', interpolation: InterpolationType, input: Expression, stops: Stops) {\n this.type = type;\n this.operator = operator;\n this.interpolation = interpolation;\n this.input = input;\n\n this.labels = [];\n this.outputs = [];\n for (const [label, expression] of stops) {\n this.labels.push(label);\n this.outputs.push(expression);\n }\n }\n\n static interpolationFactor(interpolation: InterpolationType, input: number, lower: number, upper: number): number {\n let t = 0;\n if (interpolation.name === 'exponential') {\n t = exponentialInterpolation(input, interpolation.base, lower, upper);\n } else if (interpolation.name === 'linear') {\n t = exponentialInterpolation(input, 1, lower, upper);\n } else if (interpolation.name === 'cubic-bezier') {\n const c = interpolation.controlPoints;\n const ub = new UnitBezier(c[0], c[1], c[2], c[3]);\n t = ub.solve(exponentialInterpolation(input, 1, lower, upper));\n }\n return t;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Interpolate {\n let [operator, interpolation, input, ...rest] = args;\n\n if (!Array.isArray(interpolation) || interpolation.length === 0) {\n return context.error(`Expected an interpolation type expression.`, 1);\n }\n\n if (interpolation[0] === 'linear') {\n interpolation = {name: 'linear'};\n } else if (interpolation[0] === 'exponential') {\n const base = interpolation[1];\n if (typeof base !== 'number')\n return context.error(`Exponential interpolation requires a numeric base.`, 1, 1);\n interpolation = {\n name: 'exponential',\n base\n };\n } else if (interpolation[0] === 'cubic-bezier') {\n const controlPoints = interpolation.slice(1);\n if (\n controlPoints.length !== 4 ||\n controlPoints.some(t => typeof t !== 'number' || t < 0 || t > 1)\n ) {\n return context.error('Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.', 1);\n }\n\n interpolation = {\n name: 'cubic-bezier',\n controlPoints: (controlPoints: any)\n };\n } else {\n return context.error(`Unknown interpolation type ${String(interpolation[0])}`, 1, 0);\n }\n\n if (args.length - 1 < 4) {\n return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n }\n\n if ((args.length - 1) % 2 !== 0) {\n return context.error(`Expected an even number of arguments.`);\n }\n\n input = context.parse(input, 2, NumberType);\n if (!input) return null;\n\n const stops: Stops = [];\n\n let outputType: Type = (null: any);\n if (operator === 'interpolate-hcl' || operator === 'interpolate-lab') {\n outputType = ColorType;\n } else if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n\n for (let i = 0; i < rest.length; i += 2) {\n const label = rest[i];\n const value = rest[i + 1];\n\n const labelKey = i + 3;\n const valueKey = i + 4;\n\n if (typeof label !== 'number') {\n return context.error('Input/output pairs for \"interpolate\" expressions must be defined using literal numeric values (not computed expressions) for the input values.', labelKey);\n }\n\n if (stops.length && stops[stops.length - 1][0] >= label) {\n return context.error('Input/output pairs for \"interpolate\" expressions must be arranged with input values in strictly ascending order.', labelKey);\n }\n\n const parsed = context.parse(value, valueKey, outputType);\n if (!parsed) return null;\n outputType = outputType || parsed.type;\n stops.push([label, parsed]);\n }\n\n if (outputType.kind !== 'number' &&\n outputType.kind !== 'color' &&\n !(\n outputType.kind === 'array' &&\n outputType.itemType.kind === 'number' &&\n typeof outputType.N === 'number'\n )\n ) {\n return context.error(`Type ${toString(outputType)} is not interpolatable.`);\n }\n\n return new Interpolate(outputType, (operator: any), interpolation, input, stops);\n }\n\n evaluate(ctx: EvaluationContext): Color {\n const labels = this.labels;\n const outputs = this.outputs;\n\n if (labels.length === 1) {\n return outputs[0].evaluate(ctx);\n }\n\n const value = ((this.input.evaluate(ctx): any): number);\n if (value <= labels[0]) {\n return outputs[0].evaluate(ctx);\n }\n\n const stopCount = labels.length;\n if (value >= labels[stopCount - 1]) {\n return outputs[stopCount - 1].evaluate(ctx);\n }\n\n const index = findStopLessThanOrEqualTo(labels, value);\n const lower = labels[index];\n const upper = labels[index + 1];\n const t = Interpolate.interpolationFactor(this.interpolation, value, lower, upper);\n\n const outputLower = outputs[index].evaluate(ctx);\n const outputUpper = outputs[index + 1].evaluate(ctx);\n\n if (this.operator === 'interpolate') {\n return (interpolate[this.type.kind.toLowerCase()]: any)(outputLower, outputUpper, t); // eslint-disable-line import/namespace\n } else if (this.operator === 'interpolate-hcl') {\n return hcl.reverse(hcl.interpolate(hcl.forward(outputLower), hcl.forward(outputUpper), t));\n } else {\n return lab.reverse(lab.interpolate(lab.forward(outputLower), lab.forward(outputUpper), t));\n }\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n for (const expression of this.outputs) {\n fn(expression);\n }\n }\n\n outputDefined(): boolean {\n return this.outputs.every(out => out.outputDefined());\n }\n\n serialize(): SerializedExpression {\n let interpolation;\n if (this.interpolation.name === 'linear') {\n interpolation = [\"linear\"];\n } else if (this.interpolation.name === 'exponential') {\n if (this.interpolation.base === 1) {\n interpolation = [\"linear\"];\n } else {\n interpolation = [\"exponential\", this.interpolation.base];\n }\n } else {\n interpolation = [\"cubic-bezier\" ].concat(this.interpolation.controlPoints);\n }\n\n const serialized = [this.operator, interpolation, this.input.serialize()];\n\n for (let i = 0; i < this.labels.length; i++) {\n serialized.push(\n this.labels[i],\n this.outputs[i].serialize()\n );\n }\n return serialized;\n }\n}\n\n/**\n * Returns a ratio that can be used to interpolate between exponential function\n * stops.\n * How it works: Two consecutive stop values define a (scaled and shifted) exponential function `f(x) = a * base^x + b`, where `base` is the user-specified base,\n * and `a` and `b` are constants affording sufficient degrees of freedom to fit\n * the function to the given stops.\n *\n * Here's a bit of algebra that lets us compute `f(x)` directly from the stop\n * values without explicitly solving for `a` and `b`:\n *\n * First stop value: `f(x0) = y0 = a * base^x0 + b`\n * Second stop value: `f(x1) = y1 = a * base^x1 + b`\n * => `y1 - y0 = a(base^x1 - base^x0)`\n * => `a = (y1 - y0)/(base^x1 - base^x0)`\n *\n * Desired value: `f(x) = y = a * base^x + b`\n * => `f(x) = y0 + a * (base^x - base^x0)`\n *\n * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a\n * little algebra:\n * ```\n * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0)\n * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0)\n * ```\n *\n * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have\n * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as\n * an interpolation factor between the two stops' output values.\n *\n * (Note: a slightly different form for `ratio`,\n * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer\n * expensive `Math.pow()` operations.)\n *\n * @private\n*/\nfunction exponentialInterpolation(input: number, base: number, lowerValue: number, upperValue: number) {\n const difference = upperValue - lowerValue;\n const progress = input - lowerValue;\n\n if (difference === 0) {\n return 0;\n } else if (base === 1) {\n return progress / difference;\n } else {\n return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);\n }\n}\n\nexport default Interpolate;\n","// @flow\n\nimport assert from 'assert';\n\nimport {checkSubtype, ValueType} from '../types.js';\nimport ResolvedImage from '../types/resolved_image.js';\n\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type {Type} from '../types.js';\n\nclass Coalesce implements Expression {\n type: Type;\n args: Array<Expression>;\n\n constructor(type: Type, args: Array<Expression>) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Coalesce {\n if (args.length < 2) {\n return context.error(\"Expectected at least one argument.\");\n }\n let outputType: Type = (null: any);\n const expectedType = context.expectedType;\n if (expectedType && expectedType.kind !== 'value') {\n outputType = expectedType;\n }\n const parsedArgs = [];\n\n for (const arg of args.slice(1)) {\n const parsed = context.parse(arg, 1 + parsedArgs.length, outputType, undefined, {typeAnnotation: 'omit'});\n if (!parsed) return null;\n outputType = outputType || parsed.type;\n parsedArgs.push(parsed);\n }\n assert(outputType);\n\n // Above, we parse arguments without inferred type annotation so that\n // they don't produce a runtime error for `null` input, which would\n // preempt the desired null-coalescing behavior.\n // Thus, if any of our arguments would have needed an annotation, we\n // need to wrap the enclosing coalesce expression with it instead.\n const needsAnnotation = expectedType &&\n parsedArgs.some(arg => checkSubtype(expectedType, arg.type));\n\n return needsAnnotation ?\n new Coalesce(ValueType, parsedArgs) :\n new Coalesce((outputType: any), parsedArgs);\n }\n\n evaluate(ctx: EvaluationContext): any | null {\n let result = null;\n let argCount = 0;\n let firstImage;\n for (const arg of this.args) {\n argCount++;\n result = arg.evaluate(ctx);\n // we need to keep track of the first requested image in a coalesce statement\n // if coalesce can't find a valid image, we return the first image so styleimagemissing can fire\n if (result && result instanceof ResolvedImage && !result.available) {\n // set to first image\n if (!firstImage) {\n firstImage = result;\n }\n result = null;\n // if we reach the end, return the first image\n if (argCount === this.args.length) {\n return firstImage;\n }\n }\n\n if (result !== null) break;\n }\n return result;\n }\n\n eachChild(fn: (_: Expression) => void) {\n this.args.forEach(fn);\n }\n\n outputDefined(): boolean {\n return this.args.every(arg => arg.outputDefined());\n }\n\n serialize(): SerializedExpression {\n const serialized = [\"coalesce\"];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Coalesce;\n","// @flow\n\nimport type {Type} from '../types.js';\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\n\nclass Let implements Expression {\n type: Type;\n bindings: Array<[string, Expression]>;\n result: Expression;\n\n constructor(bindings: Array<[string, Expression]>, result: Expression) {\n this.type = result.type;\n this.bindings = [].concat(bindings);\n this.result = result;\n }\n\n evaluate(ctx: EvaluationContext): any {\n return this.result.evaluate(ctx);\n }\n\n eachChild(fn: (_: Expression) => void) {\n for (const binding of this.bindings) {\n fn(binding[1]);\n }\n fn(this.result);\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Let {\n if (args.length < 4)\n return context.error(`Expected at least 3 arguments, but found ${args.length - 1} instead.`);\n\n const bindings: Array<[string, Expression]> = [];\n for (let i = 1; i < args.length - 1; i += 2) {\n const name = args[i];\n\n if (typeof name !== 'string') {\n return context.error(`Expected string, but found ${typeof name} instead.`, i);\n }\n\n if (/[^a-zA-Z0-9_]/.test(name)) {\n return context.error(`Variable names must contain only alphanumeric characters or '_'.`, i);\n }\n\n const value = context.parse(args[i + 1], i + 1);\n if (!value) return null;\n\n bindings.push([name, value]);\n }\n\n const result = context.parse(args[args.length - 1], args.length - 1, context.expectedType, bindings);\n if (!result) return null;\n\n return new Let(bindings, result);\n }\n\n outputDefined(): boolean {\n return this.result.outputDefined();\n }\n\n serialize(): SerializedExpression {\n const serialized = [\"let\"];\n for (const [name, expr] of this.bindings) {\n serialized.push(name, expr.serialize());\n }\n serialized.push(this.result.serialize());\n return serialized;\n }\n}\n\nexport default Let;\n","// @flow\n\nimport {array, ValueType, NumberType} from '../types.js';\n\nimport RuntimeError from '../runtime_error.js';\n\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type {Type, ArrayType} from '../types.js';\nimport type {Value} from '../values.js';\n\nclass At implements Expression {\n type: Type;\n index: Expression;\n input: Expression;\n\n constructor(type: Type, index: Expression, input: Expression) {\n this.type = type;\n this.index = index;\n this.input = input;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?At {\n if (args.length !== 3)\n return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`);\n\n const index = context.parse(args[1], 1, NumberType);\n const input = context.parse(args[2], 2, array(context.expectedType || ValueType));\n\n if (!index || !input) return null;\n\n const t: ArrayType = (input.type: any);\n return new At(t.itemType, index, input);\n }\n\n evaluate(ctx: EvaluationContext): Value {\n const index = ((this.index.evaluate(ctx): any): number);\n const array = ((this.input.evaluate(ctx): any): Array<Value>);\n\n if (index < 0) {\n throw new RuntimeError(`Array index out of bounds: ${index} < 0.`);\n }\n\n if (index >= array.length) {\n throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`);\n }\n\n if (index !== Math.floor(index)) {\n throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`);\n }\n\n return array[index];\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.index);\n fn(this.input);\n }\n\n outputDefined(): boolean {\n return false;\n }\n\n serialize(): SerializedExpression {\n return [\"at\", this.index.serialize(), this.input.serialize()];\n }\n}\n\nexport default At;\n","// @flow\n\nimport {BooleanType, StringType, ValueType, NullType, toString, NumberType, isValidType, isValidNativeType} from '../types.js';\nimport RuntimeError from '../runtime_error.js';\nimport {typeOf} from '../values.js';\n\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type {Type} from '../types.js';\n\nclass In implements Expression {\n type: Type;\n needle: Expression;\n haystack: Expression;\n\n constructor(needle: Expression, haystack: Expression) {\n this.type = BooleanType;\n this.needle = needle;\n this.haystack = haystack;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?In {\n if (args.length !== 3) {\n return context.error(`Expected 2 arguments, but found ${args.length - 1} instead.`);\n }\n\n const needle = context.parse(args[1], 1, ValueType);\n\n const haystack = context.parse(args[2], 2, ValueType);\n\n if (!needle || !haystack) return null;\n\n if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) {\n return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString(needle.type)} instead`);\n }\n\n return new In(needle, haystack);\n }\n\n evaluate(ctx: EvaluationContext): boolean {\n const needle = (this.needle.evaluate(ctx): any);\n const haystack = (this.haystack.evaluate(ctx): any);\n\n if (haystack == null) return false;\n\n if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) {\n throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString(typeOf(needle))} instead.`);\n }\n\n if (!isValidNativeType(haystack, ['string', 'array'])) {\n throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString(typeOf(haystack))} instead.`);\n }\n\n return haystack.indexOf(needle) >= 0;\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.needle);\n fn(this.haystack);\n }\n\n outputDefined(): boolean {\n return true;\n }\n\n serialize(): SerializedExpression {\n return [\"in\", this.needle.serialize(), this.haystack.serialize()];\n }\n}\n\nexport default In;\n","// @flow\n\nimport {BooleanType, StringType, ValueType, NullType, toString, NumberType, isValidType, isValidNativeType} from '../types.js';\nimport RuntimeError from '../runtime_error.js';\nimport {typeOf} from '../values.js';\n\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type {Type} from '../types.js';\n\nclass IndexOf implements Expression {\n type: Type;\n needle: Expression;\n haystack: Expression;\n fromIndex: ?Expression;\n\n constructor(needle: Expression, haystack: Expression, fromIndex?: Expression) {\n this.type = NumberType;\n this.needle = needle;\n this.haystack = haystack;\n this.fromIndex = fromIndex;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?IndexOf {\n if (args.length <= 2 || args.length >= 5) {\n return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`);\n }\n\n const needle = context.parse(args[1], 1, ValueType);\n\n const haystack = context.parse(args[2], 2, ValueType);\n\n if (!needle || !haystack) return null;\n if (!isValidType(needle.type, [BooleanType, StringType, NumberType, NullType, ValueType])) {\n return context.error(`Expected first argument to be of type boolean, string, number or null, but found ${toString(needle.type)} instead`);\n }\n\n if (args.length === 4) {\n const fromIndex = context.parse(args[3], 3, NumberType);\n if (!fromIndex) return null;\n return new IndexOf(needle, haystack, fromIndex);\n } else {\n return new IndexOf(needle, haystack);\n }\n }\n\n evaluate(ctx: EvaluationContext): any {\n const needle = (this.needle.evaluate(ctx): any);\n const haystack = (this.haystack.evaluate(ctx): any);\n\n if (!isValidNativeType(needle, ['boolean', 'string', 'number', 'null'])) {\n throw new RuntimeError(`Expected first argument to be of type boolean, string, number or null, but found ${toString(typeOf(needle))} instead.`);\n }\n\n if (!isValidNativeType(haystack, ['string', 'array'])) {\n throw new RuntimeError(`Expected second argument to be of type array or string, but found ${toString(typeOf(haystack))} instead.`);\n }\n\n if (this.fromIndex) {\n const fromIndex = (this.fromIndex.evaluate(ctx): number);\n return haystack.indexOf(needle, fromIndex);\n }\n\n return haystack.indexOf(needle);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.needle);\n fn(this.haystack);\n if (this.fromIndex) {\n fn(this.fromIndex);\n }\n }\n\n outputDefined(): boolean {\n return false;\n }\n\n serialize(): SerializedExpression {\n if (this.fromIndex != null && this.fromIndex !== undefined) {\n const fromIndex = this.fromIndex.serialize();\n return [\"index-of\", this.needle.serialize(), this.haystack.serialize(), fromIndex];\n }\n return [\"index-of\", this.needle.serialize(), this.haystack.serialize()];\n }\n}\n\nexport default IndexOf;\n","// @flow\n\nimport assert from 'assert';\n\nimport {typeOf} from '../values.js';\nimport {ValueType, type Type} from '../types.js';\n\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\n\n// Map input label values to output expression index\ntype Cases = {[number | string]: number};\n\nclass Match implements Expression {\n type: Type;\n inputType: Type;\n\n input: Expression;\n cases: Cases;\n outputs: Array<Expression>;\n otherwise: Expression;\n\n constructor(inputType: Type, outputType: Type, input: Expression, cases: Cases, outputs: Array<Expression>, otherwise: Expression) {\n this.inputType = inputType;\n this.type = outputType;\n this.input = input;\n this.cases = cases;\n this.outputs = outputs;\n this.otherwise = otherwise;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Match {\n if (args.length < 5)\n return context.error(`Expected at least 4 arguments, but found only ${args.length - 1}.`);\n if (args.length % 2 !== 1)\n return context.error(`Expected an even number of arguments.`);\n\n let inputType;\n let outputType: ?Type;\n if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n const cases = {};\n const outputs = [];\n for (let i = 2; i < args.length - 1; i += 2) {\n let labels = args[i];\n const value = args[i + 1];\n\n if (!Array.isArray(labels)) {\n labels = [labels];\n }\n\n const labelContext = context.concat(i);\n if (labels.length === 0) {\n return labelContext.error('Expected at least one branch label.');\n }\n\n for (const label of labels) {\n if (typeof label !== 'number' && typeof label !== 'string') {\n return labelContext.error(`Branch labels must be numbers or strings.`);\n } else if (typeof label === 'number' && Math.abs(label) > Number.MAX_SAFE_INTEGER) {\n return labelContext.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);\n\n } else if (typeof label === 'number' && Math.floor(label) !== label) {\n return labelContext.error(`Numeric branch labels must be integer values.`);\n\n } else if (!inputType) {\n inputType = typeOf(label);\n } else if (labelContext.checkSubtype(inputType, typeOf(label))) {\n return null;\n }\n\n if (typeof cases[String(label)] !== 'undefined') {\n return labelContext.error('Branch labels must be unique.');\n }\n\n cases[String(label)] = outputs.length;\n }\n\n const result = context.parse(value, i, outputType);\n if (!result) return null;\n outputType = outputType || result.type;\n outputs.push(result);\n }\n\n const input = context.parse(args[1], 1, ValueType);\n if (!input) return null;\n\n const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);\n if (!otherwise) return null;\n\n assert(inputType && outputType);\n\n if (input.type.kind !== 'value' && context.concat(1).checkSubtype((inputType: any), input.type)) {\n return null;\n }\n\n return new Match((inputType: any), (outputType: any), input, cases, outputs, otherwise);\n }\n\n evaluate(ctx: EvaluationContext): any {\n const input = (this.input.evaluate(ctx): any);\n const output = (typeOf(input) === this.inputType && this.outputs[this.cases[input]]) || this.otherwise;\n return output.evaluate(ctx);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n this.outputs.forEach(fn);\n fn(this.otherwise);\n }\n\n outputDefined(): boolean {\n return this.outputs.every(out => out.outputDefined()) && this.otherwise.outputDefined();\n }\n\n serialize(): SerializedExpression {\n const serialized = [\"match\", this.input.serialize()];\n\n // Sort so serialization has an arbitrary defined order, even though\n // branch order doesn't affect evaluation\n const sortedLabels = Object.keys(this.cases).sort();\n\n // Group branches by unique match expression to support condensed\n // serializations of the form [case1, case2, ...] -> matchExpression\n const groupedByOutput: Array<[number, Array<number | string>]> = [];\n const outputLookup: {[index: number]: number} = {}; // lookup index into groupedByOutput for a given output expression\n for (const label of sortedLabels) {\n const outputIndex = outputLookup[this.cases[label]];\n if (outputIndex === undefined) {\n // First time seeing this output, add it to the end of the grouped list\n outputLookup[this.cases[label]] = groupedByOutput.length;\n groupedByOutput.push([this.cases[label], [label]]);\n } else {\n // We've seen this expression before, add the label to that output's group\n groupedByOutput[outputIndex][1].push(label);\n }\n }\n\n const coerceLabel = (label: number | string) => this.inputType.kind === 'number' ? Number(label) : label;\n\n for (const [outputIndex, labels] of groupedByOutput) {\n if (labels.length === 1) {\n // Only a single label matches this output expression\n serialized.push(coerceLabel(labels[0]));\n } else {\n // Array of literal labels pointing to this output expression\n serialized.push(labels.map(coerceLabel));\n }\n serialized.push(this.outputs[outputIndex].serialize());\n }\n serialized.push(this.otherwise.serialize());\n return serialized;\n }\n}\n\nexport default Match;\n","// @flow\n\nimport assert from 'assert';\n\nimport {BooleanType} from '../types.js';\n\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type {Type} from '../types.js';\n\ntype Branches = Array<[Expression, Expression]>;\n\nclass Case implements Expression {\n type: Type;\n\n branches: Branches;\n otherwise: Expression;\n\n constructor(type: Type, branches: Branches, otherwise: Expression) {\n this.type = type;\n this.branches = branches;\n this.otherwise = otherwise;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Case {\n if (args.length < 4)\n return context.error(`Expected at least 3 arguments, but found only ${args.length - 1}.`);\n if (args.length % 2 !== 0)\n return context.error(`Expected an odd number of arguments.`);\n\n let outputType: ?Type;\n if (context.expectedType && context.expectedType.kind !== 'value') {\n outputType = context.expectedType;\n }\n\n const branches = [];\n for (let i = 1; i < args.length - 1; i += 2) {\n const test = context.parse(args[i], i, BooleanType);\n if (!test) return null;\n\n const result = context.parse(args[i + 1], i + 1, outputType);\n if (!result) return null;\n\n branches.push([test, result]);\n\n outputType = outputType || result.type;\n }\n\n const otherwise = context.parse(args[args.length - 1], args.length - 1, outputType);\n if (!otherwise) return null;\n\n assert(outputType);\n return new Case((outputType: any), branches, otherwise);\n }\n\n evaluate(ctx: EvaluationContext): any {\n for (const [test, expression] of this.branches) {\n if (test.evaluate(ctx)) {\n return expression.evaluate(ctx);\n }\n }\n return this.otherwise.evaluate(ctx);\n }\n\n eachChild(fn: (_: Expression) => void) {\n for (const [test, expression] of this.branches) {\n fn(test);\n fn(expression);\n }\n fn(this.otherwise);\n }\n\n outputDefined(): boolean {\n return this.branches.every(([_, out]) => out.outputDefined()) && this.otherwise.outputDefined();\n }\n\n serialize(): SerializedExpression {\n const serialized = [\"case\"];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Case;\n","// @flow\n\nimport {ValueType, NumberType, StringType, array, toString, isValidType, isValidNativeType} from '../types.js';\nimport RuntimeError from '../runtime_error.js';\nimport {typeOf} from '../values.js';\n\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type {Type} from '../types.js';\n\nclass Slice implements Expression {\n type: Type;\n input: Expression;\n beginIndex: Expression;\n endIndex: ?Expression;\n\n constructor(type: Type, input: Expression, beginIndex: Expression, endIndex?: Expression) {\n this.type = type;\n this.input = input;\n this.beginIndex = beginIndex;\n this.endIndex = endIndex;\n\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Slice {\n if (args.length <= 2 || args.length >= 5) {\n return context.error(`Expected 3 or 4 arguments, but found ${args.length - 1} instead.`);\n }\n\n const input = context.parse(args[1], 1, ValueType);\n const beginIndex = context.parse(args[2], 2, NumberType);\n\n if (!input || !beginIndex) return null;\n\n if (!isValidType(input.type, [array(ValueType), StringType, ValueType])) {\n return context.error(`Expected first argument to be of type array or string, but found ${toString(input.type)} instead`);\n }\n\n if (args.length === 4) {\n const endIndex = context.parse(args[3], 3, NumberType);\n if (!endIndex) return null;\n return new Slice(input.type, input, beginIndex, endIndex);\n } else {\n return new Slice(input.type, input, beginIndex);\n }\n }\n\n evaluate(ctx: EvaluationContext): any {\n const input = (this.input.evaluate(ctx): any);\n const beginIndex = (this.beginIndex.evaluate(ctx): number);\n\n if (!isValidNativeType(input, ['string', 'array'])) {\n throw new RuntimeError(`Expected first argument to be of type array or string, but found ${toString(typeOf(input))} instead.`);\n }\n\n if (this.endIndex) {\n const endIndex = (this.endIndex.evaluate(ctx): number);\n return input.slice(beginIndex, endIndex);\n }\n\n return input.slice(beginIndex);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n fn(this.beginIndex);\n if (this.endIndex) {\n fn(this.endIndex);\n }\n }\n\n outputDefined(): boolean {\n return false;\n }\n\n serialize(): SerializedExpression {\n if (this.endIndex != null && this.endIndex !== undefined) {\n const endIndex = this.endIndex.serialize();\n return [\"slice\", this.input.serialize(), this.beginIndex.serialize(), endIndex];\n }\n return [\"slice\", this.input.serialize(), this.beginIndex.serialize()];\n }\n}\n\nexport default Slice;\n","// @flow\n\nimport {toString, ValueType, BooleanType, CollatorType} from '../types.js';\nimport Assertion from './assertion.js';\nimport {typeOf} from '../values.js';\nimport RuntimeError from '../runtime_error.js';\n\nimport type {Expression, SerializedExpression, ExpressionRegistration} from '../expression.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type {Type} from '../types.js';\n\ntype ComparisonOperator = '==' | '!=' | '<' | '>' | '<=' | '>=' ;\n\nfunction isComparableType(op: ComparisonOperator, type: Type) {\n if (op === '==' || op === '!=') {\n // equality operator\n return type.kind === 'boolean' ||\n type.kind === 'string' ||\n type.kind === 'number' ||\n type.kind === 'null' ||\n type.kind === 'value';\n } else {\n // ordering operator\n return type.kind === 'string' ||\n type.kind === 'number' ||\n type.kind === 'value';\n }\n}\n\nfunction eq(ctx: EvaluationContext, a: any, b: any): boolean { return a === b; }\nfunction neq(ctx: EvaluationContext, a: any, b: any): boolean { return a !== b; }\nfunction lt(ctx: EvaluationContext, a: any, b: any): boolean { return a < b; }\nfunction gt(ctx: EvaluationContext, a: any, b: any): boolean { return a > b; }\nfunction lteq(ctx: EvaluationContext, a: any, b: any): boolean { return a <= b; }\nfunction gteq(ctx: EvaluationContext, a: any, b: any): boolean { return a >= b; }\n\nfunction eqCollate(ctx: EvaluationContext, a: any, b: any, c: any): boolean { return c.compare(a, b) === 0; }\nfunction neqCollate(ctx: EvaluationContext, a: any, b: any, c: any): boolean { return !eqCollate(ctx, a, b, c); }\nfunction ltCollate(ctx: EvaluationContext, a: any, b: any, c: any): boolean { return c.compare(a, b) < 0; }\nfunction gtCollate(ctx: EvaluationContext, a: any, b: any, c: any): boolean { return c.compare(a, b) > 0; }\nfunction lteqCollate(ctx: EvaluationContext, a: any, b: any, c: any): boolean { return c.compare(a, b) <= 0; }\nfunction gteqCollate(ctx: EvaluationContext, a: any, b: any, c: any): boolean { return c.compare(a, b) >= 0; }\n\n/**\n * Special form for comparison operators, implementing the signatures:\n * - (T, T, ?Collator) => boolean\n * - (T, value, ?Collator) => boolean\n * - (value, T, ?Collator) => boolean\n *\n * For inequalities, T must be either value, string, or number. For ==/!=, it\n * can also be boolean or null.\n *\n * Equality semantics are equivalent to Javascript's strict equality (===/!==)\n * -- i.e., when the arguments' types don't match, == evaluates to false, != to\n * true.\n *\n * When types don't match in an ordering comparison, a runtime error is thrown.\n *\n * @private\n */\nfunction makeComparison(op: ComparisonOperator, compareBasic: (EvaluationContext, any, any) => boolean, compareWithCollator: (EvaluationContext, any, any, any) => boolean): ExpressionRegistration {\n const isOrderComparison = op !== '==' && op !== '!=';\n\n // $FlowFixMe[method-unbinding]\n return class Comparison implements Expression {\n type: Type;\n lhs: Expression;\n rhs: Expression;\n collator: ?Expression;\n hasUntypedArgument: boolean;\n\n constructor(lhs: Expression, rhs: Expression, collator: ?Expression) {\n this.type = BooleanType;\n this.lhs = lhs;\n this.rhs = rhs;\n this.collator = collator;\n this.hasUntypedArgument = lhs.type.kind === 'value' || rhs.type.kind === 'value';\n }\n\n // $FlowFixMe[method-unbinding]\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Expression {\n if (args.length !== 3 && args.length !== 4)\n return context.error(`Expected two or three arguments.`);\n\n const op: ComparisonOperator = (args[0]: any);\n\n let lhs = context.parse(args[1], 1, ValueType);\n if (!lhs) return null;\n if (!isComparableType(op, lhs.type)) {\n return context.concat(1).error(`\"${op}\" comparisons are not supported for type '${toString(lhs.type)}'.`);\n }\n let rhs = context.parse(args[2], 2, ValueType);\n if (!rhs) return null;\n if (!isComparableType(op, rhs.type)) {\n return context.concat(2).error(`\"${op}\" comparisons are not supported for type '${toString(rhs.type)}'.`);\n }\n\n if (\n lhs.type.kind !== rhs.type.kind &&\n lhs.type.kind !== 'value' &&\n rhs.type.kind !== 'value'\n ) {\n return context.error(`Cannot compare types '${toString(lhs.type)}' and '${toString(rhs.type)}'.`);\n }\n\n if (isOrderComparison) {\n // typing rules specific to less/greater than operators\n if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') {\n // (value, T)\n lhs = new Assertion(rhs.type, [lhs]);\n } else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') {\n // (T, value)\n rhs = new Assertion(lhs.type, [rhs]);\n }\n }\n\n let collator = null;\n if (args.length === 4) {\n if (\n lhs.type.kind !== 'string' &&\n rhs.type.kind !== 'string' &&\n lhs.type.kind !== 'value' &&\n rhs.type.kind !== 'value'\n ) {\n return context.error(`Cannot use collator to compare non-string types.`);\n }\n collator = context.parse(args[3], 3, CollatorType);\n if (!collator) return null;\n }\n\n return new Comparison(lhs, rhs, collator);\n }\n\n evaluate(ctx: EvaluationContext): boolean {\n const lhs = this.lhs.evaluate(ctx);\n const rhs = this.rhs.evaluate(ctx);\n\n if (isOrderComparison && this.hasUntypedArgument) {\n const lt = typeOf(lhs);\n const rt = typeOf(rhs);\n // check that type is string or number, and equal\n if (lt.kind !== rt.kind || !(lt.kind === 'string' || lt.kind === 'number')) {\n throw new RuntimeError(`Expected arguments for \"${op}\" to be (string, string) or (number, number), but found (${lt.kind}, ${rt.kind}) instead.`);\n }\n }\n\n if (this.collator && !isOrderComparison && this.hasUntypedArgument) {\n const lt = typeOf(lhs);\n const rt = typeOf(rhs);\n if (lt.kind !== 'string' || rt.kind !== 'string') {\n return compareBasic(ctx, lhs, rhs);\n }\n }\n\n return this.collator ?\n compareWithCollator(ctx, lhs, rhs, this.collator.evaluate(ctx)) :\n compareBasic(ctx, lhs, rhs);\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.lhs);\n fn(this.rhs);\n if (this.collator) {\n fn(this.collator);\n }\n }\n\n outputDefined(): boolean {\n return true;\n }\n\n serialize(): SerializedExpression {\n const serialized = [op];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n };\n}\n\nexport const Equals: $Call<typeof makeComparison, '==', typeof eq, typeof eqCollate> = makeComparison('==', eq, eqCollate);\nexport const NotEquals: $Call<typeof makeComparison, '!=', typeof neq, typeof neqCollate> = makeComparison('!=', neq, neqCollate);\nexport const LessThan: $Call<typeof makeComparison, '<', typeof lt, typeof ltCollate> = makeComparison('<', lt, ltCollate);\nexport const GreaterThan: $Call<typeof makeComparison, '>', typeof gt, typeof gtCollate> = makeComparison('>', gt, gtCollate);\nexport const LessThanOrEqual: $Call<typeof makeComparison, '<=', typeof lteq, typeof lteqCollate> = makeComparison('<=', lteq, lteqCollate);\nexport const GreaterThanOrEqual: $Call<typeof makeComparison, '>=', typeof gteq, typeof gteqCollate> = makeComparison('>=', gteq, gteqCollate);\n","// @flow\n\nimport {StringType, NumberType} from '../types.js';\n\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type {Type} from '../types.js';\n\ndeclare var Intl: {\n NumberFormat: Class<Intl$NumberFormat>\n};\n\ndeclare class Intl$NumberFormat {\n constructor (\n locales?: string | string[],\n options?: NumberFormatOptions\n ): Intl$NumberFormat;\n\n static (\n locales?: string | string[],\n options?: NumberFormatOptions\n ): Intl$NumberFormat;\n\n format(a: number): string;\n\n resolvedOptions(): any;\n}\n\ntype NumberFormatOptions = {\n style?: 'decimal' | 'currency' | 'percent' | 'unit';\n currency?: null | string;\n unit?: null | string;\n minimumFractionDigits?: null | string;\n maximumFractionDigits?: null | string;\n};\n\nexport default class NumberFormat implements Expression {\n type: Type;\n number: Expression;\n locale: Expression | null; // BCP 47 language tag\n currency: Expression | null; // ISO 4217 currency code, required if style=currency\n unit: Expression | null; // Simple units sanctioned for use in ECMAScript, required if style=unit. https://tc39.es/proposal-unified-intl-numberformat/section6/locales-currencies-tz_proposed_out.html#sec-issanctionedsimpleunitidentifier\n minFractionDigits: Expression | null; // Default 0\n maxFractionDigits: Expression | null; // Default 3\n\n constructor(number: Expression,\n locale: Expression | null,\n currency: Expression | null,\n unit: Expression | null,\n minFractionDigits: Expression | null,\n maxFractionDigits: Expression | null) {\n this.type = StringType;\n this.number = number;\n this.locale = locale;\n this.currency = currency;\n this.unit = unit;\n this.minFractionDigits = minFractionDigits;\n this.maxFractionDigits = maxFractionDigits;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Expression {\n if (args.length !== 3)\n return context.error(`Expected two arguments.`);\n\n const number = context.parse(args[1], 1, NumberType);\n if (!number) return null;\n\n const options = (args[2]: any);\n if (typeof options !== \"object\" || Array.isArray(options))\n return context.error(`NumberFormat options argument must be an object.`);\n\n let locale = null;\n if (options['locale']) {\n locale = context.parse(options['locale'], 1, StringType);\n if (!locale) return null;\n }\n\n let currency = null;\n if (options['currency']) {\n currency = context.parse(options['currency'], 1, StringType);\n if (!currency) return null;\n }\n\n let unit = null;\n if (options['unit']) {\n unit = context.parse(options['unit'], 1, StringType);\n if (!unit) return null;\n }\n\n let minFractionDigits = null;\n if (options['min-fraction-digits']) {\n minFractionDigits = context.parse(options['min-fraction-digits'], 1, NumberType);\n if (!minFractionDigits) return null;\n }\n\n let maxFractionDigits = null;\n if (options['max-fraction-digits']) {\n maxFractionDigits = context.parse(options['max-fraction-digits'], 1, NumberType);\n if (!maxFractionDigits) return null;\n }\n\n return new NumberFormat(number, locale, currency, unit, minFractionDigits, maxFractionDigits);\n }\n\n evaluate(ctx: EvaluationContext): string {\n return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [],\n {\n style:\n (this.currency && \"currency\") ||\n (this.unit && \"unit\") ||\n \"decimal\",\n currency: this.currency ? this.currency.evaluate(ctx) : undefined,\n unit: this.unit ? this.unit.evaluate(ctx) : undefined,\n minimumFractionDigits: this.minFractionDigits ? this.minFractionDigits.evaluate(ctx) : undefined,\n maximumFractionDigits: this.maxFractionDigits ? this.maxFractionDigits.evaluate(ctx) : undefined,\n }).format(this.number.evaluate(ctx));\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.number);\n if (this.locale) {\n fn(this.locale);\n }\n if (this.currency) {\n fn(this.currency);\n }\n if (this.unit) {\n fn(this.unit);\n }\n if (this.minFractionDigits) {\n fn(this.minFractionDigits);\n }\n if (this.maxFractionDigits) {\n fn(this.maxFractionDigits);\n }\n }\n\n outputDefined(): boolean {\n return false;\n }\n\n serialize(): SerializedExpression {\n const options = {};\n if (this.locale) {\n options['locale'] = this.locale.serialize();\n }\n if (this.currency) {\n options['currency'] = this.currency.serialize();\n }\n if (this.unit) {\n options['unit'] = this.unit.serialize();\n }\n if (this.minFractionDigits) {\n options['min-fraction-digits'] = this.minFractionDigits.serialize();\n }\n if (this.maxFractionDigits) {\n options['max-fraction-digits'] = this.maxFractionDigits.serialize();\n }\n return [\"number-format\", this.number.serialize(), options];\n }\n}\n","// @flow\n\nimport {NumberType, toString} from '../types.js';\n\nimport {typeOf} from '../values.js';\nimport RuntimeError from '../runtime_error.js';\n\nimport type {Expression, SerializedExpression} from '../expression.js';\nimport type ParsingContext from '../parsing_context.js';\nimport type EvaluationContext from '../evaluation_context.js';\nimport type {Type} from '../types.js';\n\nclass Length implements Expression {\n type: Type;\n input: Expression;\n\n constructor(input: Expression) {\n this.type = NumberType;\n this.input = input;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Length {\n if (args.length !== 2)\n return context.error(`Expected 1 argument, but found ${args.length - 1} instead.`);\n\n const input = context.parse(args[1], 1);\n if (!input) return null;\n\n if (input.type.kind !== 'array' && input.type.kind !== 'string' && input.type.kind !== 'value')\n return context.error(`Expected argument of type string or array, but found ${toString(input.type)} instead.`);\n\n return new Length(input);\n }\n\n evaluate(ctx: EvaluationContext): any | number {\n const input = this.input.evaluate(ctx);\n if (typeof input === 'string') {\n return input.length;\n } else if (Array.isArray(input)) {\n return input.length;\n } else {\n throw new RuntimeError(`Expected value to be of type string or array, but found ${toString(typeOf(input))} instead.`);\n }\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.input);\n }\n\n outputDefined(): boolean {\n return false;\n }\n\n serialize(): SerializedExpression {\n const serialized = [\"length\"];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n}\n\nexport default Length;\n","// @flow\n\nimport {\n type Type,\n NumberType,\n StringType,\n BooleanType,\n ColorType,\n ObjectType,\n ValueType,\n ErrorType,\n CollatorType,\n array,\n toString as typeToString\n} from '../types.js';\n\nimport {typeOf, Color, validateRGBA, toString as valueToString} from '../values.js';\nimport CompoundExpression from '../compound_expression.js';\nimport RuntimeError from '../runtime_error.js';\nimport Let from './let.js';\nimport Var from './var.js';\nimport Literal from './literal.js';\nimport Assertion from './assertion.js';\nimport Coercion from './coercion.js';\nimport At from './at.js';\nimport In from './in.js';\nimport IndexOf from './index_of.js';\nimport Match from './match.js';\nimport Case from './case.js';\nimport Slice from './slice.js';\nimport Step from './step.js';\nimport Interpolate from './interpolate.js';\nimport Coalesce from './coalesce.js';\nimport {\n Equals,\n NotEquals,\n LessThan,\n GreaterThan,\n LessThanOrEqual,\n GreaterThanOrEqual\n} from './comparison.js';\nimport CollatorExpression from './collator.js';\nimport NumberFormat from './number_format.js';\nimport FormatExpression from './format.js';\nimport ImageExpression from './image.js';\nimport Length from './length.js';\nimport Within from './within.js';\n\nimport type EvaluationContext from '../evaluation_context.js';\nimport type {Varargs} from '../compound_expression.js';\nimport type {Expression, ExpressionRegistry} from '../expression.js';\n\nconst expressions: ExpressionRegistry = {\n // special forms\n '==': Equals,\n '!=': NotEquals,\n '>': GreaterThan,\n '<': LessThan,\n '>=': GreaterThanOrEqual,\n '<=': LessThanOrEqual,\n // $FlowFixMe[method-unbinding]\n 'array': Assertion,\n // $FlowFixMe[method-unbinding]\n 'at': At,\n 'boolean': Assertion,\n // $FlowFixMe[method-unbinding]\n 'case': Case,\n // $FlowFixMe[method-unbinding]\n 'coalesce': Coalesce,\n // $FlowFixMe[method-unbinding]\n 'collator': CollatorExpression,\n // $FlowFixMe[method-unbinding]\n 'format': FormatExpression,\n // $FlowFixMe[method-unbinding]\n 'image': ImageExpression,\n // $FlowFixMe[method-unbinding]\n 'in': In,\n // $FlowFixMe[method-unbinding]\n 'index-of': IndexOf,\n // $FlowFixMe[method-unbinding]\n 'interpolate': Interpolate,\n 'interpolate-hcl': Interpolate,\n 'interpolate-lab': Interpolate,\n // $FlowFixMe[method-unbinding]\n 'length': Length,\n // $FlowFixMe[method-unbinding]\n 'let': Let,\n // $FlowFixMe[method-unbinding]\n 'literal': Literal,\n // $FlowFixMe[method-unbinding]\n 'match': Match,\n 'number': Assertion,\n // $FlowFixMe[method-unbinding]\n 'number-format': NumberFormat,\n 'object': Assertion,\n // $FlowFixMe[method-unbinding]\n 'slice': Slice,\n // $FlowFixMe[method-unbinding]\n 'step': Step,\n 'string': Assertion,\n // $FlowFixMe[method-unbinding]\n 'to-boolean': Coercion,\n 'to-color': Coercion,\n 'to-number': Coercion,\n 'to-string': Coercion,\n // $FlowFixMe[method-unbinding]\n 'var': Var,\n // $FlowFixMe[method-unbinding]\n 'within': Within\n};\n\nfunction rgba(ctx: EvaluationContext, [r, g, b, a]: Array<Expression>) {\n r = r.evaluate(ctx);\n g = g.evaluate(ctx);\n b = b.evaluate(ctx);\n const alpha = a ? a.evaluate(ctx) : 1;\n const error = validateRGBA(r, g, b, alpha);\n if (error) throw new RuntimeError(error);\n return new Color(r / 255 * alpha, g / 255 * alpha, b / 255 * alpha, alpha);\n}\n\nfunction has(key: string, obj: {[string]: any}): boolean {\n return key in obj;\n}\n\nfunction get(key: string, obj: {[string]: any}) {\n const v = obj[key];\n return typeof v === 'undefined' ? null : v;\n}\n\nfunction binarySearch(v: any, a: {[number]: any}, i: number, j: number) {\n while (i <= j) {\n const m = (i + j) >> 1;\n if (a[m] === v)\n return true;\n if (a[m] > v)\n j = m - 1;\n else\n i = m + 1;\n }\n return false;\n}\n\nfunction varargs(type: Type): Varargs {\n return {type};\n}\n\nCompoundExpression.register(expressions, {\n 'error': [\n ErrorType,\n [StringType],\n (ctx, [v]) => { throw new RuntimeError(v.evaluate(ctx)); }\n ],\n 'typeof': [\n StringType,\n [ValueType],\n (ctx, [v]) => typeToString(typeOf(v.evaluate(ctx)))\n ],\n 'to-rgba': [\n array(NumberType, 4),\n [ColorType],\n (ctx, [v]) => {\n return v.evaluate(ctx).toArray();\n }\n ],\n 'rgb': [\n ColorType,\n [NumberType, NumberType, NumberType],\n rgba\n ],\n 'rgba': [\n ColorType,\n [NumberType, NumberType, NumberType, NumberType],\n rgba\n ],\n 'has': {\n type: BooleanType,\n overloads: [\n [\n [StringType],\n (ctx, [key]) => has(key.evaluate(ctx), ctx.properties())\n ], [\n [StringType, ObjectType],\n (ctx, [key, obj]) => has(key.evaluate(ctx), obj.evaluate(ctx))\n ]\n ]\n },\n 'get': {\n type: ValueType,\n overloads: [\n [\n [StringType],\n (ctx, [key]) => get(key.evaluate(ctx), ctx.properties())\n ], [\n [StringType, ObjectType],\n (ctx, [key, obj]) => get(key.evaluate(ctx), obj.evaluate(ctx))\n ]\n ]\n },\n 'feature-state': [\n ValueType,\n [StringType],\n (ctx, [key]) => get(key.evaluate(ctx), ctx.featureState || {})\n ],\n 'properties': [\n ObjectType,\n [],\n (ctx) => ctx.properties()\n ],\n 'geometry-type': [\n StringType,\n [],\n (ctx) => ctx.geometryType()\n ],\n 'id': [\n ValueType,\n [],\n (ctx) => ctx.id()\n ],\n 'zoom': [\n NumberType,\n [],\n (ctx) => ctx.globals.zoom\n ],\n 'pitch': [\n NumberType,\n [],\n (ctx) => ctx.globals.pitch || 0\n ],\n 'distance-from-center': [\n NumberType,\n [],\n (ctx) => ctx.distanceFromCenter()\n ],\n 'heatmap-density': [\n NumberType,\n [],\n (ctx) => ctx.globals.heatmapDensity || 0\n ],\n 'line-progress': [\n NumberType,\n [],\n (ctx) => ctx.globals.lineProgress || 0\n ],\n 'sky-radial-progress': [\n NumberType,\n [],\n (ctx) => ctx.globals.skyRadialProgress || 0\n ],\n 'accumulated': [\n ValueType,\n [],\n (ctx) => ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated\n ],\n '+': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => {\n let result = 0;\n for (const arg of args) {\n result += arg.evaluate(ctx);\n }\n return result;\n }\n ],\n '*': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => {\n let result = 1;\n for (const arg of args) {\n result *= arg.evaluate(ctx);\n }\n return result;\n }\n ],\n '-': {\n type: NumberType,\n overloads: [\n [\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx)\n ], [\n [NumberType],\n (ctx, [a]) => -a.evaluate(ctx)\n ]\n ]\n },\n '/': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx)\n ],\n '%': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx)\n ],\n 'ln2': [\n NumberType,\n [],\n () => Math.LN2\n ],\n 'pi': [\n NumberType,\n [],\n () => Math.PI\n ],\n 'e': [\n NumberType,\n [],\n () => Math.E\n ],\n '^': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx))\n ],\n 'sqrt': [\n NumberType,\n [NumberType],\n (ctx, [x]) => Math.sqrt(x.evaluate(ctx))\n ],\n 'log10': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10\n ],\n 'ln': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx))\n ],\n 'log2': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2\n ],\n 'sin': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.sin(n.evaluate(ctx))\n ],\n 'cos': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.cos(n.evaluate(ctx))\n ],\n 'tan': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.tan(n.evaluate(ctx))\n ],\n 'asin': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.asin(n.evaluate(ctx))\n ],\n 'acos': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.acos(n.evaluate(ctx))\n ],\n 'atan': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.atan(n.evaluate(ctx))\n ],\n 'min': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => Math.min(...args.map(arg => arg.evaluate(ctx)))\n ],\n 'max': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => Math.max(...args.map(arg => arg.evaluate(ctx)))\n ],\n 'abs': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.abs(n.evaluate(ctx))\n ],\n 'round': [\n NumberType,\n [NumberType],\n (ctx, [n]) => {\n const v = n.evaluate(ctx);\n // Javascript's Math.round() rounds towards +Infinity for halfway\n // values, even when they're negative. It's more common to round\n // away from 0 (e.g., this is what python and C++ do)\n return v < 0 ? -Math.round(-v) : Math.round(v);\n }\n ],\n 'floor': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.floor(n.evaluate(ctx))\n ],\n 'ceil': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.ceil(n.evaluate(ctx))\n ],\n 'filter-==': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => ctx.properties()[(k: any).value] === (v: any).value\n ],\n 'filter-id-==': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => ctx.id() === (v: any).value\n ],\n 'filter-type-==': [\n BooleanType,\n [StringType],\n (ctx, [v]) => ctx.geometryType() === (v: any).value\n ],\n 'filter-<': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a < b;\n }\n ],\n 'filter-id-<': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a < b;\n }\n ],\n 'filter->': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a > b;\n }\n ],\n 'filter-id->': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a > b;\n }\n ],\n 'filter-<=': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a <= b;\n }\n ],\n 'filter-id-<=': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a <= b;\n }\n ],\n 'filter->=': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a >= b;\n }\n ],\n 'filter-id->=': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a >= b;\n }\n ],\n 'filter-has': [\n BooleanType,\n [ValueType],\n (ctx, [k]) => (k: any).value in ctx.properties()\n ],\n 'filter-has-id': [\n BooleanType,\n [],\n (ctx) => (ctx.id() !== null && ctx.id() !== undefined)\n ],\n 'filter-type-in': [\n BooleanType,\n [array(StringType)],\n (ctx, [v]) => (v: any).value.indexOf(ctx.geometryType()) >= 0\n ],\n 'filter-id-in': [\n BooleanType,\n [array(ValueType)],\n (ctx, [v]) => (v: any).value.indexOf(ctx.id()) >= 0\n ],\n 'filter-in-small': [\n BooleanType,\n [StringType, array(ValueType)],\n // assumes v is an array literal\n (ctx, [k, v]) => (v: any).value.indexOf(ctx.properties()[(k: any).value]) >= 0\n ],\n 'filter-in-large': [\n BooleanType,\n [StringType, array(ValueType)],\n // assumes v is a array literal with values sorted in ascending order and of a single type\n (ctx, [k, v]) => binarySearch(ctx.properties()[(k: any).value], (v: any).value, 0, (v: any).value.length - 1)\n ],\n 'all': {\n type: BooleanType,\n overloads: [\n [\n [BooleanType, BooleanType],\n (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx)\n ],\n [\n varargs(BooleanType),\n (ctx, args) => {\n for (const arg of args) {\n if (!arg.evaluate(ctx))\n return false;\n }\n return true;\n }\n ]\n ]\n },\n 'any': {\n type: BooleanType,\n overloads: [\n [\n [BooleanType, BooleanType],\n (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx)\n ],\n [\n varargs(BooleanType),\n (ctx, args) => {\n for (const arg of args) {\n if (arg.evaluate(ctx))\n return true;\n }\n return false;\n }\n ]\n ]\n },\n '!': [\n BooleanType,\n [BooleanType],\n (ctx, [b]) => !b.evaluate(ctx)\n ],\n 'is-supported-script': [\n BooleanType,\n [StringType],\n // At parse time this will always return true, so we need to exclude this expression with isGlobalPropertyConstant\n (ctx, [s]) => {\n const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript;\n if (isSupportedScript) {\n return isSupportedScript(s.evaluate(ctx));\n }\n return true;\n }\n ],\n 'upcase': [\n StringType,\n [StringType],\n (ctx, [s]) => s.evaluate(ctx).toUpperCase()\n ],\n 'downcase': [\n StringType,\n [StringType],\n (ctx, [s]) => s.evaluate(ctx).toLowerCase()\n ],\n 'concat': [\n StringType,\n varargs(ValueType),\n (ctx, args) => args.map(arg => valueToString(arg.evaluate(ctx))).join('')\n ],\n 'resolved-locale': [\n StringType,\n [CollatorType],\n (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale()\n ]\n});\n\nexport default expressions;\n","// @flow\n\n/**\n * A type used for returning and propagating errors. The first element of the union\n * represents success and contains a value, and the second represents an error and\n * contains an error value.\n * @private\n */\nexport type Result<T, E> =\n | {| result: 'success', value: T |}\n | {| result: 'error', value: E |};\n\nexport function success<T, E>(value: T): Result<T, E> {\n return {result: 'success', value};\n}\n\nexport function error<T, E>(value: E): Result<T, E> {\n return {result: 'error', value};\n}\n","// @flow\n\nimport type {StylePropertySpecification} from '../style-spec.js';\n\nexport function supportsPropertyExpression(spec: StylePropertySpecification): boolean {\n return spec['property-type'] === 'data-driven';\n}\n\nexport function supportsZoomExpression(spec: StylePropertySpecification): boolean {\n return !!spec.expression && spec.expression.parameters.indexOf('zoom') > -1;\n}\n\nexport function supportsInterpolation(spec: StylePropertySpecification): boolean {\n return !!spec.expression && spec.expression.interpolated;\n}\n","// @flow\n\nexport default function getType(val: mixed): string {\n if (val instanceof Number) {\n return 'number';\n } else if (val instanceof String) {\n return 'string';\n } else if (val instanceof Boolean) {\n return 'boolean';\n } else if (Array.isArray(val)) {\n return 'array';\n } else if (val === null) {\n return 'null';\n } else {\n return typeof val;\n }\n}\n","\nimport * as colorSpaces from '../util/color_spaces.js';\nimport Color from '../util/color.js';\nimport extend from '../util/extend.js';\nimport getType from '../util/get_type.js';\nimport * as interpolate from '../util/interpolate.js';\nimport Interpolate from '../expression/definitions/interpolate.js';\nimport Formatted from '../expression/types/formatted.js';\nimport ResolvedImage from '../expression/types/resolved_image.js';\nimport {supportsInterpolation} from '../util/properties.js';\nimport {findStopLessThanOrEqualTo} from '../expression/stops.js';\n\nexport function isFunction(value) {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction identityFunction(x) {\n return x;\n}\n\nexport function createFunction(parameters, propertySpec) {\n const isColor = propertySpec.type === 'color';\n const zoomAndFeatureDependent = parameters.stops && typeof parameters.stops[0][0] === 'object';\n const featureDependent = zoomAndFeatureDependent || parameters.property !== undefined;\n const zoomDependent = zoomAndFeatureDependent || !featureDependent;\n const type = parameters.type || (supportsInterpolation(propertySpec) ? 'exponential' : 'interval');\n\n if (isColor) {\n parameters = extend({}, parameters);\n\n if (parameters.stops) {\n parameters.stops = parameters.stops.map((stop) => {\n return [stop[0], Color.parse(stop[1])];\n });\n }\n\n if (parameters.default) {\n parameters.default = Color.parse(parameters.default);\n } else {\n parameters.default = Color.parse(propertySpec.default);\n }\n }\n\n if (parameters.colorSpace && parameters.colorSpace !== 'rgb' && !colorSpaces[parameters.colorSpace]) { // eslint-disable-line import/namespace\n throw new Error(`Unknown color space: ${parameters.colorSpace}`);\n }\n\n let innerFun;\n let hashedStops;\n let categoricalKeyType;\n if (type === 'exponential') {\n innerFun = evaluateExponentialFunction;\n } else if (type === 'interval') {\n innerFun = evaluateIntervalFunction;\n } else if (type === 'categorical') {\n innerFun = evaluateCategoricalFunction;\n\n // For categorical functions, generate an Object as a hashmap of the stops for fast searching\n hashedStops = Object.create(null);\n for (const stop of parameters.stops) {\n hashedStops[stop[0]] = stop[1];\n }\n\n // Infer key type based on first stop key-- used to encforce strict type checking later\n categoricalKeyType = typeof parameters.stops[0][0];\n\n } else if (type === 'identity') {\n innerFun = evaluateIdentityFunction;\n } else {\n throw new Error(`Unknown function type \"${type}\"`);\n }\n\n if (zoomAndFeatureDependent) {\n const featureFunctions = {};\n const zoomStops = [];\n for (let s = 0; s < parameters.stops.length; s++) {\n const stop = parameters.stops[s];\n const zoom = stop[0].zoom;\n if (featureFunctions[zoom] === undefined) {\n featureFunctions[zoom] = {\n zoom,\n type: parameters.type,\n property: parameters.property,\n default: parameters.default,\n stops: []\n };\n zoomStops.push(zoom);\n }\n featureFunctions[zoom].stops.push([stop[0].value, stop[1]]);\n }\n\n const featureFunctionStops = [];\n for (const z of zoomStops) {\n featureFunctionStops.push([featureFunctions[z].zoom, createFunction(featureFunctions[z], propertySpec)]);\n }\n\n const interpolationType = {name: 'linear'};\n return {\n kind: 'composite',\n interpolationType,\n interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType),\n zoomStops: featureFunctionStops.map(s => s[0]),\n evaluate({zoom}, properties) {\n return evaluateExponentialFunction({\n stops: featureFunctionStops,\n base: parameters.base\n }, propertySpec, zoom).evaluate(zoom, properties);\n }\n };\n } else if (zoomDependent) {\n const interpolationType = type === 'exponential' ?\n {name: 'exponential', base: parameters.base !== undefined ? parameters.base : 1} : null;\n return {\n kind: 'camera',\n interpolationType,\n interpolationFactor: Interpolate.interpolationFactor.bind(undefined, interpolationType),\n zoomStops: parameters.stops.map(s => s[0]),\n evaluate: ({zoom}) => innerFun(parameters, propertySpec, zoom, hashedStops, categoricalKeyType)\n };\n } else {\n return {\n kind: 'source',\n evaluate(_, feature) {\n const value = feature && feature.properties ? feature.properties[parameters.property] : undefined;\n if (value === undefined) {\n return coalesce(parameters.default, propertySpec.default);\n }\n return innerFun(parameters, propertySpec, value, hashedStops, categoricalKeyType);\n }\n };\n }\n}\n\nfunction coalesce(a, b, c) {\n if (a !== undefined) return a;\n if (b !== undefined) return b;\n if (c !== undefined) return c;\n}\n\nfunction evaluateCategoricalFunction(parameters, propertySpec, input, hashedStops, keyType) {\n const evaluated = typeof input === keyType ? hashedStops[input] : undefined; // Enforce strict typing on input\n return coalesce(evaluated, parameters.default, propertySpec.default);\n}\n\nfunction evaluateIntervalFunction(parameters, propertySpec, input) {\n // Edge cases\n if (getType(input) !== 'number') return coalesce(parameters.default, propertySpec.default);\n const n = parameters.stops.length;\n if (n === 1) return parameters.stops[0][1];\n if (input <= parameters.stops[0][0]) return parameters.stops[0][1];\n if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1];\n\n const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input);\n\n return parameters.stops[index][1];\n}\n\nfunction evaluateExponentialFunction(parameters, propertySpec, input) {\n const base = parameters.base !== undefined ? parameters.base : 1;\n\n // Edge cases\n if (getType(input) !== 'number') return coalesce(parameters.default, propertySpec.default);\n const n = parameters.stops.length;\n if (n === 1) return parameters.stops[0][1];\n if (input <= parameters.stops[0][0]) return parameters.stops[0][1];\n if (input >= parameters.stops[n - 1][0]) return parameters.stops[n - 1][1];\n\n const index = findStopLessThanOrEqualTo(parameters.stops.map((stop) => stop[0]), input);\n const t = interpolationFactor(\n input, base,\n parameters.stops[index][0],\n parameters.stops[index + 1][0]);\n\n const outputLower = parameters.stops[index][1];\n const outputUpper = parameters.stops[index + 1][1];\n let interp = interpolate[propertySpec.type] || identityFunction; // eslint-disable-line import/namespace\n\n if (parameters.colorSpace && parameters.colorSpace !== 'rgb') {\n const colorspace = colorSpaces[parameters.colorSpace]; // eslint-disable-line import/namespace\n interp = (a, b) => colorspace.reverse(colorspace.interpolate(colorspace.forward(a), colorspace.forward(b), t));\n }\n\n if (typeof outputLower.evaluate === 'function') {\n return {\n evaluate(...args) {\n const evaluatedLower = outputLower.evaluate.apply(undefined, args);\n const evaluatedUpper = outputUpper.evaluate.apply(undefined, args);\n // Special case for fill-outline-color, which has no spec default.\n if (evaluatedLower === undefined || evaluatedUpper === undefined) {\n return undefined;\n }\n return interp(evaluatedLower, evaluatedUpper, t);\n }\n };\n }\n\n return interp(outputLower, outputUpper, t);\n}\n\nfunction evaluateIdentityFunction(parameters, propertySpec, input) {\n if (propertySpec.type === 'color') {\n input = Color.parse(input);\n } else if (propertySpec.type === 'formatted') {\n input = Formatted.fromString(input.toString());\n } else if (propertySpec.type === 'resolvedImage') {\n input = ResolvedImage.fromString(input.toString());\n } else if (getType(input) !== propertySpec.type && (propertySpec.type !== 'enum' || !propertySpec.values[input])) {\n input = undefined;\n }\n return coalesce(input, parameters.default, propertySpec.default);\n}\n\n/**\n * Returns a ratio that can be used to interpolate between exponential function\n * stops.\n *\n * How it works:\n * Two consecutive stop values define a (scaled and shifted) exponential\n * function `f(x) = a * base^x + b`, where `base` is the user-specified base,\n * and `a` and `b` are constants affording sufficient degrees of freedom to fit\n * the function to the given stops.\n *\n * Here's a bit of algebra that lets us compute `f(x)` directly from the stop\n * values without explicitly solving for `a` and `b`:\n *\n * First stop value: `f(x0) = y0 = a * base^x0 + b`\n * Second stop value: `f(x1) = y1 = a * base^x1 + b`\n * => `y1 - y0 = a(base^x1 - base^x0)`\n * => `a = (y1 - y0)/(base^x1 - base^x0)`\n *\n * Desired value: `f(x) = y = a * base^x + b`\n * => `f(x) = y0 + a * (base^x - base^x0)`\n *\n * From the above, we can replace the `a` in `a * (base^x - base^x0)` and do a\n * little algebra:\n * ```\n * a * (base^x - base^x0) = (y1 - y0)/(base^x1 - base^x0) * (base^x - base^x0)\n * = (y1 - y0) * (base^x - base^x0) / (base^x1 - base^x0)\n * ```\n *\n * If we let `(base^x - base^x0) / (base^x1 base^x0)`, then we have\n * `f(x) = y0 + (y1 - y0) * ratio`. In other words, `ratio` may be treated as\n * an interpolation factor between the two stops' output values.\n *\n * (Note: a slightly different form for `ratio`,\n * `(base^(x-x0) - 1) / (base^(x1-x0) - 1) `, is equivalent, but requires fewer\n * expensive `Math.pow()` operations.)\n *\n * @private\n */\nfunction interpolationFactor(input, base, lowerValue, upperValue) {\n const difference = upperValue - lowerValue;\n const progress = input - lowerValue;\n\n if (difference === 0) {\n return 0;\n } else if (base === 1) {\n return progress / difference;\n } else {\n return (Math.pow(base, progress) - 1) / (Math.pow(base, difference) - 1);\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport extend from '../util/extend.js';\nimport ParsingError from './parsing_error.js';\nimport ParsingContext from './parsing_context.js';\nimport EvaluationContext from './evaluation_context.js';\nimport CompoundExpression from './compound_expression.js';\nimport Step from './definitions/step.js';\nimport Interpolate from './definitions/interpolate.js';\nimport Coalesce from './definitions/coalesce.js';\nimport Let from './definitions/let.js';\nimport definitions from './definitions/index.js';\nimport * as isConstant from './is_constant.js';\nimport RuntimeError from './runtime_error.js';\nimport {success, error} from '../util/result.js';\nimport {supportsPropertyExpression, supportsZoomExpression, supportsInterpolation} from '../util/properties.js';\n\nimport type {Type, EvaluationKind} from './types.js';\nimport type {Value} from './values.js';\nimport type {Expression} from './expression.js';\nimport type {StylePropertySpecification} from '../style-spec.js';\nimport type {Result} from '../util/result.js';\nimport type {InterpolationType} from './definitions/interpolate.js';\nimport type {PropertyValueSpecification} from '../types.js';\nimport type {FormattedSection} from './types/formatted.js';\nimport type Point from '@mapbox/point-geometry';\nimport type {CanonicalTileID} from '../../source/tile_id.js';\nimport type {FeatureDistanceData} from '../feature_filter/index.js';\n\nexport interface Feature {\n +type: 1 | 2 | 3 | 'Unknown' | 'Point' | 'LineString' | 'Polygon';\n +id?: number | null;\n +properties: {[_: string]: any};\n +patterns?: {[_: string]: string};\n +geometry?: Array<Array<Point>>;\n}\n\nexport type FeatureState = {[_: string]: any};\n\nexport interface GlobalProperties {\n +zoom: number;\n +pitch?: number;\n +heatmapDensity?: number;\n +lineProgress?: number;\n +skyRadialProgress?: number;\n +isSupportedScript?: (_: string) => boolean;\n +accumulated?: Value;\n}\n\nexport class StyleExpression {\n expression: Expression;\n\n _evaluator: EvaluationContext;\n _defaultValue: Value;\n _warningHistory: {[key: string]: boolean};\n _enumValues: ?{[_: string]: any};\n\n constructor(expression: Expression, propertySpec: ?StylePropertySpecification) {\n this.expression = expression;\n this._warningHistory = {};\n this._evaluator = new EvaluationContext();\n this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null;\n this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null;\n }\n\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection, featureTileCoord?: Point, featureDistanceData?: FeatureDistanceData): any {\n this._evaluator.globals = globals;\n this._evaluator.feature = feature;\n this._evaluator.featureState = featureState;\n this._evaluator.canonical = canonical || null;\n this._evaluator.availableImages = availableImages || null;\n this._evaluator.formattedSection = formattedSection;\n this._evaluator.featureTileCoord = featureTileCoord || null;\n this._evaluator.featureDistanceData = featureDistanceData || null;\n\n return this.expression.evaluate(this._evaluator);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection, featureTileCoord?: Point, featureDistanceData?: FeatureDistanceData): any {\n this._evaluator.globals = globals;\n this._evaluator.feature = feature || null;\n this._evaluator.featureState = featureState || null;\n this._evaluator.canonical = canonical || null;\n this._evaluator.availableImages = availableImages || null;\n this._evaluator.formattedSection = formattedSection || null;\n this._evaluator.featureTileCoord = featureTileCoord || null;\n this._evaluator.featureDistanceData = featureDistanceData || null;\n\n try {\n const val = this.expression.evaluate(this._evaluator);\n // eslint-disable-next-line no-self-compare\n if (val === null || val === undefined || (typeof val === 'number' && val !== val)) {\n return this._defaultValue;\n }\n if (this._enumValues && !(val in this._enumValues)) {\n throw new RuntimeError(`Expected value to be one of ${Object.keys(this._enumValues).map(v => JSON.stringify(v)).join(', ')}, but found ${JSON.stringify(val)} instead.`);\n }\n return val;\n } catch (e) {\n if (!this._warningHistory[e.message]) {\n this._warningHistory[e.message] = true;\n if (typeof console !== 'undefined') {\n console.warn(e.message);\n }\n }\n return this._defaultValue;\n }\n }\n}\n\nexport function isExpression(expression: mixed): boolean {\n return Array.isArray(expression) && expression.length > 0 &&\n typeof expression[0] === 'string' && expression[0] in definitions;\n}\n\n/**\n * Parse and typecheck the given style spec JSON expression. If\n * options.defaultValue is provided, then the resulting StyleExpression's\n * `evaluate()` method will handle errors by logging a warning (once per\n * message) and returning the default value. Otherwise, it will throw\n * evaluation errors.\n *\n * @private\n */\nexport function createExpression(expression: mixed, propertySpec: ?StylePropertySpecification): Result<StyleExpression, Array<ParsingError>> {\n const parser = new ParsingContext(definitions, [], propertySpec ? getExpectedType(propertySpec) : undefined);\n\n // For string-valued properties, coerce to string at the top level rather than asserting.\n const parsed = parser.parse(expression, undefined, undefined, undefined,\n propertySpec && propertySpec.type === 'string' ? {typeAnnotation: 'coerce'} : undefined);\n\n if (!parsed) {\n assert(parser.errors.length > 0);\n return error(parser.errors);\n }\n\n return success(new StyleExpression(parsed, propertySpec));\n}\n\nexport class ZoomConstantExpression<Kind: EvaluationKind> {\n kind: Kind;\n isStateDependent: boolean;\n _styleExpression: StyleExpression;\n\n constructor(kind: Kind, expression: StyleExpression) {\n this.kind = kind;\n this._styleExpression = expression;\n this.isStateDependent = kind !== ('constant': EvaluationKind) && !isConstant.isStateConstant(expression.expression);\n }\n\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n}\n\nexport class ZoomDependentExpression<Kind: EvaluationKind> {\n kind: Kind;\n zoomStops: Array<number>;\n isStateDependent: boolean;\n\n _styleExpression: StyleExpression;\n interpolationType: ?InterpolationType;\n\n constructor(kind: Kind, expression: StyleExpression, zoomStops: Array<number>, interpolationType?: InterpolationType) {\n this.kind = kind;\n this.zoomStops = zoomStops;\n this._styleExpression = expression;\n this.isStateDependent = kind !== ('camera': EvaluationKind) && !isConstant.isStateConstant(expression.expression);\n this.interpolationType = interpolationType;\n }\n\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n\n interpolationFactor(input: number, lower: number, upper: number): number {\n if (this.interpolationType) {\n return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper);\n } else {\n return 0;\n }\n }\n}\n\nexport type ConstantExpression = interface {\n kind: 'constant',\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>) => any,\n}\n\nexport type SourceExpression = interface {\n kind: 'source',\n isStateDependent: boolean,\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection) => any,\n};\n\nexport type CameraExpression = interface {\n kind: 'camera',\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>) => any,\n +interpolationFactor: (input: number, lower: number, upper: number) => number,\n zoomStops: Array<number>,\n interpolationType: ?InterpolationType\n};\n\nexport interface CompositeExpression {\n kind: 'composite';\n isStateDependent: boolean;\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection) => any;\n +interpolationFactor: (input: number, lower: number, upper: number) => number;\n zoomStops: Array<number>;\n interpolationType: ?InterpolationType;\n}\n\nexport type StylePropertyExpression =\n | ConstantExpression\n | SourceExpression\n | CameraExpression\n | CompositeExpression;\n\nexport function createPropertyExpression(expression: mixed, propertySpec: StylePropertySpecification): Result<StylePropertyExpression, Array<ParsingError>> {\n expression = createExpression(expression, propertySpec);\n if (expression.result === 'error') {\n return expression;\n }\n\n const parsed = expression.value.expression;\n\n const isFeatureConstant = isConstant.isFeatureConstant(parsed);\n if (!isFeatureConstant && !supportsPropertyExpression(propertySpec)) {\n return error([new ParsingError('', 'data expressions not supported')]);\n }\n\n const isZoomConstant = isConstant.isGlobalPropertyConstant(parsed, ['zoom', 'pitch', 'distance-from-center']);\n if (!isZoomConstant && !supportsZoomExpression(propertySpec)) {\n return error([new ParsingError('', 'zoom expressions not supported')]);\n }\n\n const zoomCurve = findZoomCurve(parsed);\n if (!zoomCurve && !isZoomConstant) {\n return error([new ParsingError('', '\"zoom\" expression may only be used as input to a top-level \"step\" or \"interpolate\" expression.')]);\n } else if (zoomCurve instanceof ParsingError) {\n return error([zoomCurve]);\n } else if (zoomCurve instanceof Interpolate && !supportsInterpolation(propertySpec)) {\n return error([new ParsingError('', '\"interpolate\" expressions cannot be used with this property')]);\n }\n\n if (!zoomCurve) {\n return success(isFeatureConstant ?\n // $FlowFixMe[method-unbinding]\n (new ZoomConstantExpression('constant', expression.value): ConstantExpression) :\n // $FlowFixMe[method-unbinding]\n (new ZoomConstantExpression('source', expression.value): SourceExpression));\n }\n\n const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined;\n\n return success(isFeatureConstant ?\n // $FlowFixMe[method-unbinding]\n (new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType): CameraExpression) :\n // $FlowFixMe[method-unbinding]\n (new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType): CompositeExpression));\n}\n\nimport {isFunction, createFunction} from '../function/index.js';\nimport {Color} from './values.js';\n\n// serialization wrapper for old-style stop functions normalized to the\n// expression interface\nexport class StylePropertyFunction<T> {\n _parameters: PropertyValueSpecification<T>;\n _specification: StylePropertySpecification;\n\n kind: EvaluationKind;\n evaluate: (globals: GlobalProperties, feature?: Feature) => any;\n interpolationFactor: ?(input: number, lower: number, upper: number) => number;\n zoomStops: ?Array<number>;\n\n constructor(parameters: PropertyValueSpecification<T>, specification: StylePropertySpecification) {\n this._parameters = parameters;\n this._specification = specification;\n extend(this, createFunction(this._parameters, this._specification));\n }\n\n static deserialize(serialized: {_parameters: PropertyValueSpecification<T>, _specification: StylePropertySpecification}): StylePropertyFunction<T> {\n return new StylePropertyFunction(serialized._parameters, serialized._specification);\n }\n\n static serialize(input: StylePropertyFunction<T>): {_parameters: PropertyValueSpecification<T>, _specification: StylePropertySpecification} {\n return {\n _parameters: input._parameters,\n _specification: input._specification\n };\n }\n}\n\nexport function normalizePropertyExpression<T>(value: PropertyValueSpecification<T>, specification: StylePropertySpecification): StylePropertyExpression {\n if (isFunction(value)) {\n return (new StylePropertyFunction(value, specification): any);\n\n } else if (isExpression(value)) {\n const expression = createPropertyExpression(value, specification);\n if (expression.result === 'error') {\n // this should have been caught in validation\n throw new Error(expression.value.map(err => `${err.key}: ${err.message}`).join(', '));\n }\n return expression.value;\n\n } else {\n let constant: any = value;\n if (typeof value === 'string' && specification.type === 'color') {\n constant = Color.parse(value);\n }\n return {\n kind: 'constant',\n evaluate: () => constant\n };\n }\n}\n\n// Zoom-dependent expressions may only use [\"zoom\"] as the input to a top-level \"step\" or \"interpolate\"\n// expression (collectively referred to as a \"curve\"). The curve may be wrapped in one or more \"let\" or\n// \"coalesce\" expressions.\nfunction findZoomCurve(expression: Expression): Step | Interpolate | ParsingError | null {\n let result = null;\n if (expression instanceof Let) {\n result = findZoomCurve(expression.result);\n\n } else if (expression instanceof Coalesce) {\n for (const arg of expression.args) {\n result = findZoomCurve(arg);\n if (result) {\n break;\n }\n }\n\n } else if ((expression instanceof Step || expression instanceof Interpolate) &&\n expression.input instanceof CompoundExpression &&\n expression.input.name === 'zoom') {\n\n result = expression;\n }\n\n if (result instanceof ParsingError) {\n return result;\n }\n\n expression.eachChild((child) => {\n const childResult = findZoomCurve(child);\n if (childResult instanceof ParsingError) {\n result = childResult;\n } else if (!result && childResult) {\n result = new ParsingError('', '\"zoom\" expression may only be used as input to a top-level \"step\" or \"interpolate\" expression.');\n } else if (result && childResult && result !== childResult) {\n result = new ParsingError('', 'Only one zoom-based \"step\" or \"interpolate\" subexpression may be used in an expression.');\n }\n });\n\n return result;\n}\n\nimport {ColorType, StringType, NumberType, BooleanType, ValueType, FormattedType, ResolvedImageType, array} from './types.js';\n\nfunction getExpectedType(spec: StylePropertySpecification): Type {\n const types = {\n color: ColorType,\n string: StringType,\n number: NumberType,\n enum: StringType,\n boolean: BooleanType,\n formatted: FormattedType,\n resolvedImage: ResolvedImageType\n };\n\n if (spec.type === 'array') {\n return array(types[spec.value] || ValueType, spec.length);\n }\n\n return types[spec.type];\n}\n\nfunction getDefaultValue(spec: StylePropertySpecification): Value {\n if (spec.type === 'color' && (isFunction(spec.default) || Array.isArray(spec.default))) {\n // Special case for heatmap-color: it uses the 'default:' to define a\n // default color ramp, but createExpression expects a simple value to fall\n // back to in case of runtime errors\n return new Color(0, 0, 0, 0);\n } else if (spec.type === 'color') {\n return Color.parse(spec.default) || null;\n } else if (spec.default === undefined) {\n return null;\n } else {\n return spec.default;\n }\n}\n","// @flow strict\n\ntype Config = {|\n API_URL: string,\n API_URL_REGEX: RegExp,\n API_TILEJSON_REGEX: RegExp,\n API_FONTS_REGEX: RegExp,\n API_SPRITE_REGEX: RegExp,\n API_STYLE_REGEX: RegExp,\n API_CDN_URL_REGEX: RegExp,\n EVENTS_URL: ?string,\n SESSION_PATH: string,\n FEEDBACK_URL: string,\n REQUIRE_ACCESS_TOKEN: boolean,\n TILE_URL_VERSION: string,\n RASTER_URL_PREFIX: string,\n ACCESS_TOKEN: ?string,\n MAX_PARALLEL_IMAGE_REQUESTS: number\n|};\n\nlet mapboxHTTPURLRegex;\n\nconst config: Config = {\n API_URL: 'https://api.mapbox.com',\n get API_URL_REGEX () {\n if (mapboxHTTPURLRegex == null) {\n const prodMapboxHTTPURLRegex = /^((https?:)?\\/\\/)?([^\\/]+\\.)?mapbox\\.c(n|om)(\\/|\\?|$)/i;\n try {\n mapboxHTTPURLRegex = (process.env.API_URL_REGEX != null) ? new RegExp(process.env.API_URL_REGEX) : prodMapboxHTTPURLRegex;\n } catch (e) {\n mapboxHTTPURLRegex = prodMapboxHTTPURLRegex;\n }\n }\n\n return mapboxHTTPURLRegex;\n },\n get API_TILEJSON_REGEX() {\n // https://docs.mapbox.com/api/maps/mapbox-tiling-service/#retrieve-tilejson-metadata\n return /^((https?:)?\\/\\/)?([^\\/]+\\.)?mapbox\\.c(n|om)(\\/v[0-9]*\\/.*\\.json.*$)/i;\n },\n get API_SPRITE_REGEX() {\n // https://docs.mapbox.com/api/maps/styles/#retrieve-a-sprite-image-or-json\n return /^((https?:)?\\/\\/)?([^\\/]+\\.)?mapbox\\.c(n|om)(\\/styles\\/v[0-9]*\\/)(.*\\/sprite.*\\..*$)/i;\n },\n get API_FONTS_REGEX() {\n // https://docs.mapbox.com/api/maps/fonts/#retrieve-font-glyph-ranges\n return /^((https?:)?\\/\\/)?([^\\/]+\\.)?mapbox\\.c(n|om)(\\/fonts\\/v[0-9]*\\/)(.*\\.pbf.*$)/i;\n },\n get API_STYLE_REGEX() {\n // https://docs.mapbox.com/api/maps/styles/#retrieve-a-style\n return /^((https?:)?\\/\\/)?([^\\/]+\\.)?mapbox\\.c(n|om)(\\/styles\\/v[0-9]*\\/)(.*$)/i;\n },\n get API_CDN_URL_REGEX() {\n return /^((https?:)?\\/\\/)?api\\.mapbox\\.c(n|om)(\\/mapbox-gl-js\\/)(.*$)/i;\n },\n get EVENTS_URL() {\n if (!config.API_URL) { return null; }\n try {\n const url = new URL(config.API_URL);\n if (url.hostname === 'api.mapbox.cn') {\n return 'https://events.mapbox.cn/events/v2';\n } else if (url.hostname === 'api.mapbox.com') {\n return 'https://events.mapbox.com/events/v2';\n } else {\n return null;\n }\n } catch (e) {\n return null;\n }\n },\n SESSION_PATH: '/map-sessions/v1',\n FEEDBACK_URL: 'https://apps.mapbox.com/feedback',\n TILE_URL_VERSION: 'v4',\n RASTER_URL_PREFIX: 'raster/v1',\n REQUIRE_ACCESS_TOKEN: true,\n ACCESS_TOKEN: null,\n MAX_PARALLEL_IMAGE_REQUESTS: 16\n};\n\nexport default config;\n","// @flow strict\n\nimport window from './window.js';\n\nconst exported = {\n supported: false,\n testSupport\n};\n\nexport default exported;\n\nlet glForTesting;\nlet webpCheckComplete = false;\nlet webpImgTest;\nlet webpImgTestOnloadComplete = false;\n\nif (window.document) {\n webpImgTest = window.document.createElement('img');\n webpImgTest.onload = function() {\n if (glForTesting) testWebpTextureUpload(glForTesting);\n glForTesting = null;\n webpImgTestOnloadComplete = true;\n };\n webpImgTest.onerror = function() {\n webpCheckComplete = true;\n glForTesting = null;\n };\n webpImgTest.src = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=';\n}\n\nfunction testSupport(gl: WebGLRenderingContext) {\n if (webpCheckComplete || !webpImgTest) return;\n\n // HTMLImageElement.complete is set when an image is done loading it's source\n // regardless of whether the load was successful or not.\n // It's possible for an error to set HTMLImageElement.complete to true which would trigger\n // testWebpTextureUpload and mistakenly set exported.supported to true in browsers which don't support webp\n // To avoid this, we set a flag in the image's onload handler and only call testWebpTextureUpload\n // after a successful image load event.\n if (webpImgTestOnloadComplete) {\n testWebpTextureUpload(gl);\n } else {\n glForTesting = gl;\n\n }\n}\n\nfunction testWebpTextureUpload(gl: WebGLRenderingContext) {\n // Edge 18 supports WebP but not uploading a WebP image to a gl texture\n // Test support for this before allowing WebP images.\n // https://github.com/mapbox/mapbox-gl-js/issues/7671\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n\n try {\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, webpImgTest);\n\n // The error does not get triggered in Edge if the context is lost\n if (gl.isContextLost()) return;\n\n exported.supported = true;\n } catch (e) {\n // Catch \"Unspecified Error.\" in Edge 18.\n }\n\n gl.deleteTexture(texture);\n\n webpCheckComplete = true;\n}\n","// @flow\n\nimport window from './window.js';\nimport {version as sdkVersion} from '../../package.json';\nimport {\n isMapboxHTTPStyleURL,\n isMapboxHTTPTileJSONURL,\n isMapboxHTTPSpriteURL,\n isMapboxHTTPFontsURL,\n isMapboxHTTPCDNURL\n} from './mapbox.js';\n\ntype LivePerformanceMetrics = {\n counters: Array<Object>,\n metadata: Array<Object>,\n attributes: Array<Object>\n};\n\nexport type LivePerformanceData = {\n interactionRange: [number, number],\n visibilityHidden: number,\n width: number,\n height: number,\n terrainEnabled: boolean,\n fogEnabled: boolean,\n projection: string,\n zoom: number,\n renderer: ?string,\n vendor: ?string\n};\n\nexport const PerformanceMarkers = {\n create: 'create',\n load: 'load',\n fullLoad: 'fullLoad'\n};\n\nexport const LivePerformanceUtils = {\n mark(marker: $Keys<typeof PerformanceMarkers>) {\n window.performance.mark(marker);\n },\n measure(name: string, begin?: string, end?: string) {\n window.performance.measure(name, begin, end);\n }\n};\n\nfunction categorize(arr: Array<PerformanceResourceTiming>, fn: (entry: PerformanceResourceTiming) => string): {[string]: Array<PerformanceResourceTiming>} {\n const obj = {};\n if (arr) {\n for (const item of arr) {\n const category = fn(item);\n if (obj[category] === undefined) {\n obj[category] = [];\n }\n obj[category].push(item);\n }\n }\n return obj;\n}\n\nfunction getCountersPerResourceType(resourceTimers: { [string]: Array<PerformanceResourceTiming> }) {\n const obj = {};\n if (resourceTimers) {\n for (const category in resourceTimers) {\n if (category !== 'other') {\n for (const timer of resourceTimers[category]) {\n const min = `${category}ResolveRangeMin`;\n const max = `${category}ResolveRangeMax`;\n const reqCount = `${category}RequestCount`;\n const reqCachedCount = `${category}RequestCachedCount`;\n\n // Resource -TransferStart and -TransferEnd represent the wall time\n // between the start of a request to when the data is available\n obj[min] = Math.min(obj[min] || +Infinity, timer.startTime);\n obj[max] = Math.max(obj[max] || -Infinity, timer.responseEnd);\n\n const increment = (key: string) => {\n if (obj[key] === undefined) {\n obj[key] = 0;\n }\n ++obj[key];\n };\n\n const transferSizeSupported = timer.transferSize !== undefined;\n if (transferSizeSupported) {\n const resourceFetchedFromCache = (timer.transferSize === 0);\n if (resourceFetchedFromCache) {\n increment(reqCachedCount);\n }\n }\n increment(reqCount);\n }\n }\n }\n }\n return obj;\n}\n\nfunction getResourceCategory(entry: PerformanceResourceTiming): string {\n const url = entry.name.split('?')[0];\n\n if (isMapboxHTTPCDNURL(url) && url.includes('mapbox-gl.js')) return 'javascript';\n if (isMapboxHTTPCDNURL(url) && url.includes('mapbox-gl.css')) return 'css';\n if (isMapboxHTTPFontsURL(url)) return 'fontRange';\n if (isMapboxHTTPSpriteURL(url)) return 'sprite';\n if (isMapboxHTTPStyleURL(url)) return 'style';\n if (isMapboxHTTPTileJSONURL(url)) return 'tilejson';\n\n return 'other';\n}\n\nfunction getStyle(resourceTimers: Array<PerformanceEntry>): ?string {\n if (resourceTimers) {\n for (const timer of resourceTimers) {\n const url = timer.name.split('?')[0];\n if (isMapboxHTTPStyleURL(url)) {\n const split = url.split('/').slice(-2);\n if (split.length === 2) {\n return `mapbox://styles/${split[0]}/${split[1]}`;\n }\n }\n }\n }\n}\n\nexport function getLivePerformanceMetrics(data: LivePerformanceData): LivePerformanceMetrics {\n const resourceTimers = window.performance.getEntriesByType('resource');\n const markerTimers = window.performance.getEntriesByType('mark');\n const resourcesByType = categorize(resourceTimers, getResourceCategory);\n const counters = getCountersPerResourceType(resourcesByType);\n const devicePixelRatio = window.devicePixelRatio;\n const connection = window.navigator.connection || window.navigator.mozConnection || window.navigator.webkitConnection;\n const metrics = {counters: [], metadata: [], attributes: []};\n\n // Please read carefully before adding or modifying the following metrics:\n // https://github.com/mapbox/gl-js-team/blob/main/docs/live_performance_metrics.md\n const addMetric = (arr: Array<{| name: string, value: string |}>, name: string, value: ?(number | string)) => {\n if (value !== undefined && value !== null) {\n arr.push({name, value: value.toString()});\n }\n };\n\n for (const counter in counters) {\n addMetric(metrics.counters, counter, counters[counter]);\n }\n if (data.interactionRange[0] !== +Infinity && data.interactionRange[1] !== -Infinity) {\n addMetric(metrics.counters, \"interactionRangeMin\", data.interactionRange[0]);\n addMetric(metrics.counters, \"interactionRangeMax\", data.interactionRange[1]);\n }\n if (markerTimers) {\n for (const marker of Object.keys(PerformanceMarkers)) {\n const markerName = PerformanceMarkers[marker];\n const markerTimer = markerTimers.find((entry) => entry.name === markerName);\n if (markerTimer) {\n addMetric(metrics.counters, markerName, markerTimer.startTime);\n }\n }\n }\n addMetric(metrics.counters, \"visibilityHidden\", data.visibilityHidden);\n\n addMetric(metrics.attributes, \"style\", getStyle(resourceTimers));\n addMetric(metrics.attributes, \"terrainEnabled\", data.terrainEnabled ? \"true\" : \"false\");\n addMetric(metrics.attributes, \"fogEnabled\", data.fogEnabled ? \"true\" : \"false\");\n addMetric(metrics.attributes, \"projection\", data.projection);\n addMetric(metrics.attributes, \"zoom\", data.zoom);\n\n addMetric(metrics.metadata, \"devicePixelRatio\", devicePixelRatio);\n addMetric(metrics.metadata, \"connectionEffectiveType\", connection ? connection.effectiveType : undefined);\n addMetric(metrics.metadata, \"navigatorUserAgent\", window.navigator.userAgent);\n addMetric(metrics.metadata, \"screenWidth\", window.screen.width);\n addMetric(metrics.metadata, \"screenHeight\", window.screen.height);\n addMetric(metrics.metadata, \"windowWidth\", window.innerWidth);\n addMetric(metrics.metadata, \"windowHeight\", window.innerHeight);\n addMetric(metrics.metadata, \"mapWidth\", data.width / devicePixelRatio);\n addMetric(metrics.metadata, \"mapHeight\", data.height / devicePixelRatio);\n addMetric(metrics.metadata, \"webglRenderer\", data.renderer);\n addMetric(metrics.metadata, \"webglVendor\", data.vendor);\n addMetric(metrics.metadata, \"sdkVersion\", sdkVersion);\n addMetric(metrics.metadata, \"sdkIdentifier\", \"mapbox-gl-js\");\n\n return metrics;\n}\n","// @flow\n\n/***** START WARNING REMOVAL OR MODIFICATION OF THE\n* FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******\n* The following code is used to access Mapbox's APIs. Removal or modification\n* of this code can result in higher fees and/or\n* termination of your account with Mapbox.\n*\n* Under the Mapbox Terms of Service, you may not use this code to access Mapbox\n* Mapping APIs other than through Mapbox SDKs.\n*\n* The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps\n* and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/\n******************************************************************************/\n\nimport config from './config.js';\nimport window from './window.js';\nimport webpSupported from './webp_supported.js';\nimport {createSkuToken, SKU_ID} from './sku_token.js';\nimport {version as sdkVersion} from '../../package.json';\nimport {uuid, validateUuid, storageAvailable, b64DecodeUnicode, b64EncodeUnicode, warnOnce, extend} from './util.js';\nimport {postData, ResourceType, getData} from './ajax.js';\nimport {getLivePerformanceMetrics} from '../util/live_performance.js';\nimport type {LivePerformanceData} from '../util/live_performance.js';\nimport type {RequestParameters} from './ajax.js';\nimport type {Cancelable} from '../types/cancelable.js';\nimport type {TileJSON} from '../types/tilejson.js';\nimport assert from 'assert';\n\ntype ResourceTypeEnum = $Keys<typeof ResourceType>;\nexport type RequestTransformFunction = (url: string, resourceType?: ResourceTypeEnum) => RequestParameters;\n\ntype UrlObject = {|\n protocol: string,\n authority: string,\n path: string,\n params: Array<string>\n|};\n\ntype EventCallback = (err: ?Error) => void;\n\nexport const AUTH_ERR_MSG: string = 'NO_ACCESS_TOKEN';\n\nexport class RequestManager {\n _skuToken: string;\n _skuTokenExpiresAt: number;\n _transformRequestFn: ?RequestTransformFunction;\n _customAccessToken: ?string;\n _silenceAuthErrors: boolean;\n\n constructor(transformRequestFn?: RequestTransformFunction, customAccessToken?: string, silenceAuthErrors: ?boolean) {\n this._transformRequestFn = transformRequestFn;\n this._customAccessToken = customAccessToken;\n this._silenceAuthErrors = !!silenceAuthErrors;\n this._createSkuToken();\n }\n\n _createSkuToken() {\n const skuToken = createSkuToken();\n this._skuToken = skuToken.token;\n this._skuTokenExpiresAt = skuToken.tokenExpiresAt;\n }\n\n _isSkuTokenExpired(): boolean {\n return Date.now() > this._skuTokenExpiresAt;\n }\n\n transformRequest(url: string, type: ResourceTypeEnum): RequestParameters {\n if (this._transformRequestFn) {\n return this._transformRequestFn(url, type) || {url};\n }\n\n return {url};\n }\n\n normalizeStyleURL(url: string, accessToken?: string): string {\n if (!isMapboxURL(url)) return url;\n const urlObject = parseUrl(url);\n urlObject.path = `/styles/v1${urlObject.path}`;\n return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);\n }\n\n normalizeGlyphsURL(url: string, accessToken?: string): string {\n if (!isMapboxURL(url)) return url;\n const urlObject = parseUrl(url);\n urlObject.path = `/fonts/v1${urlObject.path}`;\n return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);\n }\n\n normalizeSourceURL(url: string, accessToken?: ?string, language?: ?string, worldview?: ?string): string {\n if (!isMapboxURL(url)) return url;\n const urlObject = parseUrl(url);\n urlObject.path = `/v4/${urlObject.authority}.json`;\n // TileJSON requests need a secure flag appended to their URLs so\n // that the server knows to send SSL-ified resource references.\n urlObject.params.push('secure');\n if (language) {\n urlObject.params.push(`language=${language}`);\n }\n if (worldview) {\n urlObject.params.push(`worldview=${worldview}`);\n }\n\n return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);\n }\n\n normalizeSpriteURL(url: string, format: string, extension: string, accessToken?: string): string {\n const urlObject = parseUrl(url);\n if (!isMapboxURL(url)) {\n urlObject.path += `${format}${extension}`;\n return formatUrl(urlObject);\n }\n urlObject.path = `/styles/v1${urlObject.path}/sprite${format}${extension}`;\n return this._makeAPIURL(urlObject, this._customAccessToken || accessToken);\n }\n\n normalizeTileURL(tileURL: string, use2x?: boolean, rasterTileSize?: number): string {\n if (this._isSkuTokenExpired()) {\n this._createSkuToken();\n }\n\n if (tileURL && !isMapboxURL(tileURL)) return tileURL;\n\n const urlObject = parseUrl(tileURL);\n const imageExtensionRe = /(\\.(png|jpg)\\d*)(?=$)/;\n const extension = webpSupported.supported ? '.webp' : '$1';\n\n // The v4 mapbox tile API supports 512x512 image tiles but they must be requested as '@2x' tiles.\n const use2xAs512 = rasterTileSize && urlObject.authority !== 'raster' && rasterTileSize === 512;\n\n const suffix = use2x || use2xAs512 ? '@2x' : '';\n urlObject.path = urlObject.path.replace(imageExtensionRe, `${suffix}${extension}`);\n\n if (urlObject.authority === 'raster') {\n urlObject.path = `/${config.RASTER_URL_PREFIX}${urlObject.path}`;\n } else {\n const tileURLAPIPrefixRe = /^.+\\/v4\\//;\n urlObject.path = urlObject.path.replace(tileURLAPIPrefixRe, '/');\n urlObject.path = `/${config.TILE_URL_VERSION}${urlObject.path}`;\n }\n\n const accessToken = this._customAccessToken || getAccessToken(urlObject.params) || config.ACCESS_TOKEN;\n if (config.REQUIRE_ACCESS_TOKEN && accessToken && this._skuToken) {\n urlObject.params.push(`sku=${this._skuToken}`);\n }\n\n return this._makeAPIURL(urlObject, accessToken);\n }\n\n canonicalizeTileURL(url: string, removeAccessToken: boolean): string {\n // matches any file extension specified by a dot and one or more alphanumeric characters\n const extensionRe = /\\.[\\w]+$/;\n\n const urlObject = parseUrl(url);\n // Make sure that we are dealing with a valid Mapbox tile URL.\n // Has to begin with /v4/ or /raster/v1, with a valid filename + extension\n if (!urlObject.path.match(/^(\\/v4\\/|\\/raster\\/v1\\/)/) || !urlObject.path.match(extensionRe)) {\n // Not a proper Mapbox tile URL.\n return url;\n }\n // Reassemble the canonical URL from the parts we've parsed before.\n let result = \"mapbox://\";\n if (urlObject.path.match(/^\\/raster\\/v1\\//)) {\n // If the tile url has /raster/v1/, make the final URL mapbox://raster/....\n const rasterPrefix = `/${config.RASTER_URL_PREFIX}/`;\n result += `raster/${urlObject.path.replace(rasterPrefix, '')}`;\n } else {\n const tilesPrefix = `/${config.TILE_URL_VERSION}/`;\n result += `tiles/${urlObject.path.replace(tilesPrefix, '')}`;\n }\n\n // Append the query string, minus the access token parameter.\n let params = urlObject.params;\n if (removeAccessToken) {\n params = params.filter(p => !p.match(/^access_token=/));\n }\n if (params.length) result += `?${params.join('&')}`;\n return result;\n }\n\n canonicalizeTileset(tileJSON: TileJSON, sourceURL?: string): Array<string> {\n const removeAccessToken = sourceURL ? isMapboxURL(sourceURL) : false;\n const canonical = [];\n for (const url of tileJSON.tiles || []) {\n if (isMapboxHTTPURL(url)) {\n canonical.push(this.canonicalizeTileURL(url, removeAccessToken));\n } else {\n canonical.push(url);\n }\n }\n return canonical;\n }\n\n _makeAPIURL(urlObject: UrlObject, accessToken: string | null | void): string {\n const help = 'See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes';\n const apiUrlObject = parseUrl(config.API_URL);\n urlObject.protocol = apiUrlObject.protocol;\n urlObject.authority = apiUrlObject.authority;\n\n if (urlObject.protocol === 'http') {\n const i = urlObject.params.indexOf('secure');\n if (i >= 0) urlObject.params.splice(i, 1);\n }\n\n if (apiUrlObject.path !== '/') {\n urlObject.path = `${apiUrlObject.path}${urlObject.path}`;\n }\n\n if (!config.REQUIRE_ACCESS_TOKEN) return formatUrl(urlObject);\n\n accessToken = accessToken || config.ACCESS_TOKEN;\n if (!this._silenceAuthErrors) {\n if (!accessToken)\n throw new Error(`An API access token is required to use Mapbox GL. ${help}`);\n if (accessToken[0] === 's')\n throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${help}`);\n }\n\n urlObject.params = urlObject.params.filter((d) => d.indexOf('access_token') === -1);\n urlObject.params.push(`access_token=${accessToken || ''}`);\n return formatUrl(urlObject);\n }\n}\n\nexport function isMapboxURL(url: string): boolean {\n return url.indexOf('mapbox:') === 0;\n}\n\nexport function isMapboxHTTPURL(url: string): boolean {\n return config.API_URL_REGEX.test(url);\n}\n\nexport function isMapboxHTTPCDNURL(url: string): boolean {\n return config.API_CDN_URL_REGEX.test(url);\n}\n\nexport function isMapboxHTTPStyleURL(url: string): boolean {\n return config.API_STYLE_REGEX.test(url) && !isMapboxHTTPSpriteURL(url);\n}\n\nexport function isMapboxHTTPTileJSONURL(url: string): boolean {\n return config.API_TILEJSON_REGEX.test(url);\n}\n\nexport function isMapboxHTTPSpriteURL(url: string): boolean {\n return config.API_SPRITE_REGEX.test(url);\n}\n\nexport function isMapboxHTTPFontsURL(url: string): boolean {\n return config.API_FONTS_REGEX.test(url);\n}\n\nexport function hasCacheDefeatingSku(url: string): boolean {\n return url.indexOf('sku=') > 0 && isMapboxHTTPURL(url);\n}\n\nfunction getAccessToken(params: Array<string>): string | null {\n for (const param of params) {\n const match = param.match(/^access_token=(.*)$/);\n if (match) {\n return match[1];\n }\n }\n return null;\n}\n\nconst urlRe = /^(\\w+):\\/\\/([^/?]*)(\\/[^?]+)?\\??(.+)?/;\n\nfunction parseUrl(url: string): UrlObject {\n const parts = url.match(urlRe);\n if (!parts) {\n throw new Error('Unable to parse URL object');\n }\n return {\n protocol: parts[1],\n authority: parts[2],\n path: parts[3] || '/',\n params: parts[4] ? parts[4].split('&') : []\n };\n}\n\nfunction formatUrl(obj: UrlObject): string {\n const params = obj.params.length ? `?${obj.params.join('&')}` : '';\n return `${obj.protocol}://${obj.authority}${obj.path}${params}`;\n}\n\nconst telemEventKey = 'mapbox.eventData';\n\nfunction parseAccessToken(accessToken: ?string) {\n if (!accessToken) {\n return null;\n }\n\n const parts = accessToken.split('.');\n if (!parts || parts.length !== 3) {\n return null;\n }\n\n try {\n const jsonData = JSON.parse(b64DecodeUnicode(parts[1]));\n return jsonData;\n } catch (e) {\n return null;\n }\n}\n\ntype TelemetryEventType = 'appUserTurnstile' | 'map.load' | 'map.auth' | 'gljs.performance';\n\nclass TelemetryEvent {\n eventData: any;\n anonId: ?string;\n queue: Array<any>;\n type: TelemetryEventType;\n pendingRequest: ?Cancelable;\n _customAccessToken: ?string;\n\n constructor(type: TelemetryEventType) {\n this.type = type;\n this.anonId = null;\n this.eventData = {};\n this.queue = [];\n this.pendingRequest = null;\n }\n\n getStorageKey(domain: ?string): string {\n const tokenData = parseAccessToken(config.ACCESS_TOKEN);\n let u = '';\n if (tokenData && tokenData['u']) {\n u = b64EncodeUnicode(tokenData['u']);\n } else {\n u = config.ACCESS_TOKEN || '';\n }\n return domain ?\n `${telemEventKey}.${domain}:${u}` :\n `${telemEventKey}:${u}`;\n }\n\n fetchEventData() {\n const isLocalStorageAvailable = storageAvailable('localStorage');\n const storageKey = this.getStorageKey();\n const uuidKey = this.getStorageKey('uuid');\n\n if (isLocalStorageAvailable) {\n //Retrieve cached data\n try {\n const data = window.localStorage.getItem(storageKey);\n if (data) {\n this.eventData = JSON.parse(data);\n }\n\n const uuid = window.localStorage.getItem(uuidKey);\n if (uuid) this.anonId = uuid;\n } catch (e) {\n warnOnce('Unable to read from LocalStorage');\n }\n }\n }\n\n saveEventData() {\n const isLocalStorageAvailable = storageAvailable('localStorage');\n const storageKey = this.getStorageKey();\n const uuidKey = this.getStorageKey('uuid');\n if (isLocalStorageAvailable) {\n try {\n window.localStorage.setItem(uuidKey, this.anonId);\n if (Object.keys(this.eventData).length >= 1) {\n window.localStorage.setItem(storageKey, JSON.stringify(this.eventData));\n }\n } catch (e) {\n warnOnce('Unable to write to LocalStorage');\n }\n }\n\n }\n\n processRequests(_: ?string) {}\n\n /*\n * If any event data should be persisted after the POST request, the callback should modify eventData`\n * to the values that should be saved. For this reason, the callback should be invoked prior to the call\n * to TelemetryEvent#saveData\n */\n postEvent(timestamp: number, additionalPayload: {[_: string]: any}, callback: EventCallback, customAccessToken?: ?string) {\n if (!config.EVENTS_URL) return;\n const eventsUrlObject: UrlObject = parseUrl(config.EVENTS_URL);\n eventsUrlObject.params.push(`access_token=${customAccessToken || config.ACCESS_TOKEN || ''}`);\n\n const payload: Object = {\n event: this.type,\n created: new Date(timestamp).toISOString()\n };\n\n const finalPayload = additionalPayload ? extend(payload, additionalPayload) : payload;\n const request: RequestParameters = {\n url: formatUrl(eventsUrlObject),\n headers: {\n 'Content-Type': 'text/plain' //Skip the pre-flight OPTIONS request\n },\n body: JSON.stringify([finalPayload])\n };\n\n this.pendingRequest = postData(request, (error) => {\n this.pendingRequest = null;\n callback(error);\n this.saveEventData();\n this.processRequests(customAccessToken);\n });\n }\n\n queueRequest(event: any, customAccessToken?: ?string) {\n this.queue.push(event);\n this.processRequests(customAccessToken);\n }\n}\n\nexport class PerformanceEvent extends TelemetryEvent {\n constructor() {\n super('gljs.performance');\n }\n\n postPerformanceEvent(customAccessToken: ?string, performanceData: LivePerformanceData) {\n if (config.EVENTS_URL) {\n if (customAccessToken || config.ACCESS_TOKEN) {\n this.queueRequest({timestamp: Date.now(), performanceData}, customAccessToken);\n }\n }\n }\n\n processRequests(customAccessToken?: ?string) {\n if (this.pendingRequest || this.queue.length === 0) {\n return;\n }\n\n const {timestamp, performanceData} = this.queue.shift();\n\n const additionalPayload = getLivePerformanceMetrics(performanceData);\n\n // Server will only process string for these entries\n for (const metadata of additionalPayload.metadata) {\n assert(typeof metadata.value === 'string');\n }\n for (const counter of additionalPayload.counters) {\n assert(typeof counter.value === 'string');\n }\n for (const attribute of additionalPayload.attributes) {\n assert(typeof attribute.value === 'string');\n }\n\n this.postEvent(timestamp, additionalPayload, () => {}, customAccessToken);\n }\n}\n\nexport class MapLoadEvent extends TelemetryEvent {\n +success: {[_: number]: boolean};\n skuToken: string;\n errorCb: EventCallback;\n\n constructor() {\n super('map.load');\n this.success = {};\n this.skuToken = '';\n }\n\n postMapLoadEvent(mapId: number, skuToken: string, customAccessToken: ?string, callback: EventCallback) {\n this.skuToken = skuToken;\n this.errorCb = callback;\n\n if (config.EVENTS_URL) {\n if (customAccessToken || config.ACCESS_TOKEN) {\n this.queueRequest({id: mapId, timestamp: Date.now()}, customAccessToken);\n } else {\n this.errorCb(new Error(AUTH_ERR_MSG));\n }\n }\n }\n\n processRequests(customAccessToken?: ?string) {\n if (this.pendingRequest || this.queue.length === 0) return;\n const {id, timestamp} = this.queue.shift();\n\n // Only one load event should fire per map\n if (id && this.success[id]) return;\n\n if (!this.anonId) {\n this.fetchEventData();\n }\n\n if (!validateUuid(this.anonId)) {\n this.anonId = uuid();\n }\n\n const additionalPayload = {\n sdkIdentifier: 'mapbox-gl-js',\n sdkVersion,\n skuId: SKU_ID,\n skuToken: this.skuToken,\n userId: this.anonId\n };\n\n this.postEvent(timestamp, additionalPayload, (err) => {\n if (err) {\n this.errorCb(err);\n } else {\n if (id) this.success[id] = true;\n }\n\n }, customAccessToken);\n }\n}\n\nexport class MapSessionAPI extends TelemetryEvent {\n +success: {[_: number]: boolean};\n skuToken: string;\n errorCb: EventCallback;\n\n constructor() {\n super('map.auth');\n this.success = {};\n this.skuToken = '';\n }\n\n getSession(timestamp: number, token: string, callback: EventCallback, customAccessToken?: ?string) {\n if (!config.API_URL || !config.SESSION_PATH) return;\n const authUrlObject: UrlObject = parseUrl(config.API_URL + config.SESSION_PATH);\n authUrlObject.params.push(`sku=${token || ''}`);\n authUrlObject.params.push(`access_token=${customAccessToken || config.ACCESS_TOKEN || ''}`);\n\n const request: RequestParameters = {\n url: formatUrl(authUrlObject),\n headers: {\n 'Content-Type': 'text/plain', //Skip the pre-flight OPTIONS request\n }\n };\n\n this.pendingRequest = getData(request, (error) => {\n this.pendingRequest = null;\n callback(error);\n this.saveEventData();\n this.processRequests(customAccessToken);\n });\n }\n\n getSessionAPI(mapId: number, skuToken: string, customAccessToken: ?string, callback: EventCallback) {\n this.skuToken = skuToken;\n this.errorCb = callback;\n\n if (config.SESSION_PATH && config.API_URL) {\n if (customAccessToken || config.ACCESS_TOKEN) {\n this.queueRequest({id: mapId, timestamp: Date.now()}, customAccessToken);\n } else {\n this.errorCb(new Error(AUTH_ERR_MSG));\n }\n }\n }\n\n processRequests(customAccessToken?: ?string) {\n if (this.pendingRequest || this.queue.length === 0) return;\n const {id, timestamp} = this.queue.shift();\n\n // Only one load event should fire per map\n if (id && this.success[id]) return;\n\n this.getSession(timestamp, this.skuToken, (err) => {\n if (err) {\n this.errorCb(err);\n } else {\n if (id) this.success[id] = true;\n }\n }, customAccessToken);\n }\n}\n\nexport class TurnstileEvent extends TelemetryEvent {\n constructor(customAccessToken?: ?string) {\n super('appUserTurnstile');\n this._customAccessToken = customAccessToken;\n }\n\n postTurnstileEvent(tileUrls: Array<string>, customAccessToken?: ?string) {\n //Enabled only when Mapbox Access Token is set and a source uses\n // mapbox tiles.\n if (config.EVENTS_URL &&\n config.ACCESS_TOKEN &&\n Array.isArray(tileUrls) &&\n tileUrls.some(url => isMapboxURL(url) || isMapboxHTTPURL(url))) {\n this.queueRequest(Date.now(), customAccessToken);\n }\n }\n\n processRequests(customAccessToken?: ?string) {\n if (this.pendingRequest || this.queue.length === 0) {\n return;\n }\n\n if (!this.anonId || !this.eventData.lastSuccess || !this.eventData.tokenU) {\n //Retrieve cached data\n this.fetchEventData();\n }\n\n const tokenData = parseAccessToken(config.ACCESS_TOKEN);\n const tokenU = tokenData ? tokenData['u'] : config.ACCESS_TOKEN;\n //Reset event data cache if the access token owner changed.\n let dueForEvent = tokenU !== this.eventData.tokenU;\n\n if (!validateUuid(this.anonId)) {\n this.anonId = uuid();\n dueForEvent = true;\n }\n\n const nextUpdate = this.queue.shift();\n // Record turnstile event once per calendar day.\n if (this.eventData.lastSuccess) {\n const lastUpdate = new Date(this.eventData.lastSuccess);\n const nextDate = new Date(nextUpdate);\n const daysElapsed = (nextUpdate - this.eventData.lastSuccess) / (24 * 60 * 60 * 1000);\n dueForEvent = dueForEvent || daysElapsed >= 1 || daysElapsed < -1 || lastUpdate.getDate() !== nextDate.getDate();\n } else {\n dueForEvent = true;\n }\n\n if (!dueForEvent) {\n this.processRequests();\n return;\n }\n\n const additionalPayload = {\n sdkIdentifier: 'mapbox-gl-js',\n sdkVersion,\n skuId: SKU_ID,\n \"enabled.telemetry\": false,\n userId: this.anonId\n };\n\n this.postEvent(nextUpdate, additionalPayload, (err) => {\n if (!err) {\n this.eventData.lastSuccess = nextUpdate;\n this.eventData.tokenU = tokenU;\n }\n }, customAccessToken);\n }\n}\n\nconst turnstileEvent_ = new TurnstileEvent();\n// $FlowFixMe[method-unbinding]\nexport const postTurnstileEvent: (tileUrls: Array<string>, customAccessToken?: ?string) => void = turnstileEvent_.postTurnstileEvent.bind(turnstileEvent_);\n\nconst mapLoadEvent_ = new MapLoadEvent();\n// $FlowFixMe[method-unbinding]\nexport const postMapLoadEvent: (number, string, ?string, EventCallback) => void = mapLoadEvent_.postMapLoadEvent.bind(mapLoadEvent_);\n\nexport const performanceEvent_: PerformanceEvent = new PerformanceEvent();\n// $FlowFixMe[method-unbinding]\nexport const postPerformanceEvent: (?string, LivePerformanceData) => void = performanceEvent_.postPerformanceEvent.bind(performanceEvent_);\n\nconst mapSessionAPI_ = new MapSessionAPI();\n// $FlowFixMe[method-unbinding]\nexport const getMapSessionAPI: (number, string, ?string, EventCallback) => void = mapSessionAPI_.getSessionAPI.bind(mapSessionAPI_);\n\nconst authenticatedMaps = new Set();\nexport function storeAuthState(gl: WebGLRenderingContext, state: boolean) {\n if (state) {\n authenticatedMaps.add(gl);\n } else {\n authenticatedMaps.delete(gl);\n }\n}\n\nexport function isMapAuthenticated(gl: WebGLRenderingContext): boolean {\n return authenticatedMaps.has(gl);\n}\n\nexport function removeAuthState(gl: WebGLRenderingContext) {\n authenticatedMaps.delete(gl);\n}\n\n/***** END WARNING - REMOVAL OR MODIFICATION OF THE\nPRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******/\n","// @flow\n\n/***** START WARNING REMOVAL OR MODIFICATION OF THE\n* FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******\n* The following code is used to access Mapbox's APIs. Removal or modification\n* of this code can result in higher fees and/or\n* termination of your account with Mapbox.\n*\n* Under the Mapbox Terms of Service, you may not use this code to access Mapbox\n* Mapping APIs other than through Mapbox SDKs.\n*\n* The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps\n* and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/\n******************************************************************************/\n\ntype SkuTokenObject = {|\n token: string,\n tokenExpiresAt: number\n|};\n\nconst SKU_ID = '01';\n\nfunction createSkuToken(): SkuTokenObject {\n // SKU_ID and TOKEN_VERSION are specified by an internal schema and should not change\n const TOKEN_VERSION = '1';\n const base62chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n // sessionRandomizer is a randomized 10-digit base-62 number\n let sessionRandomizer = '';\n for (let i = 0; i < 10; i++) {\n sessionRandomizer += base62chars[Math.floor(Math.random() * 62)];\n }\n const expiration = 12 * 60 * 60 * 1000; // 12 hours\n const token = [TOKEN_VERSION, SKU_ID, sessionRandomizer].join('');\n const tokenExpiresAt = Date.now() + expiration;\n\n return {token, tokenExpiresAt};\n}\n\nexport {createSkuToken, SKU_ID};\n\n/***** END WARNING - REMOVAL OR MODIFICATION OF THE\nPRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******/\n","// @flow\n\nimport {warnOnce, parseCacheControl} from './util.js';\nimport window from './window.js';\n\nimport type Dispatcher from './dispatcher.js';\n\nconst CACHE_NAME = 'mapbox-tiles';\nlet cacheLimit = 500; // 50MB / (100KB/tile) ~= 500 tiles\nlet cacheCheckThreshold = 50;\n\nconst MIN_TIME_UNTIL_EXPIRY = 1000 * 60 * 7; // 7 minutes. Skip caching tiles with a short enough max age.\n\nexport type ResponseOptions = {\n status: number,\n statusText: string,\n headers: Headers\n};\n\n// We're using a global shared cache object. Normally, requesting ad-hoc Cache objects is fine, but\n// Safari has a memory leak in which it fails to release memory when requesting keys() from a Cache\n// object. See https://bugs.webkit.org/show_bug.cgi?id=203991 for more information.\nlet sharedCache: ?Promise<Cache>;\n\nfunction getCaches() {\n try {\n return window.caches;\n } catch (e) {\n // <iframe sandbox> triggers exceptions when trying to access window.caches\n // Chrome: DOMException, Safari: SecurityError, Firefox: NS_ERROR_FAILURE\n // Seems more robust to catch all exceptions instead of trying to match only these.\n }\n}\n\nfunction cacheOpen() {\n const caches = getCaches();\n if (caches && !sharedCache) {\n sharedCache = window.caches.open(CACHE_NAME);\n }\n}\n\n// We're never closing the cache, but our unit tests rely on changing out the global window.caches\n// object, so we have a function specifically for unit tests that allows resetting the shared cache.\nexport function cacheClose() {\n sharedCache = undefined;\n}\n\nlet responseConstructorSupportsReadableStream;\nfunction prepareBody(response: Response, callback: ((body: ?(Blob | ReadableStream)) => void)) {\n if (responseConstructorSupportsReadableStream === undefined) {\n try {\n new Response(new ReadableStream()); // eslint-disable-line no-undef\n responseConstructorSupportsReadableStream = true;\n } catch (e) {\n // Edge\n responseConstructorSupportsReadableStream = false;\n }\n }\n\n if (responseConstructorSupportsReadableStream) {\n callback(response.body);\n } else {\n response.blob().then(callback);\n }\n}\n\nexport function cachePut(request: Request, response: Response, requestTime: number) {\n cacheOpen();\n if (!sharedCache) return;\n\n const options: ResponseOptions = {\n status: response.status,\n statusText: response.statusText,\n headers: new window.Headers()\n };\n response.headers.forEach((v, k) => options.headers.set(k, v));\n\n const cacheControl = parseCacheControl(response.headers.get('Cache-Control') || '');\n if (cacheControl['no-store']) {\n return;\n }\n if (cacheControl['max-age']) {\n options.headers.set('Expires', new Date(requestTime + cacheControl['max-age'] * 1000).toUTCString());\n }\n\n const expires = options.headers.get('Expires');\n if (!expires) return;\n const timeUntilExpiry = new Date(expires).getTime() - requestTime;\n if (timeUntilExpiry < MIN_TIME_UNTIL_EXPIRY) return;\n\n prepareBody(response, body => {\n const clonedResponse = new window.Response(body, options);\n\n cacheOpen();\n if (!sharedCache) return;\n sharedCache\n .then(cache => cache.put(stripQueryParameters(request.url), clonedResponse))\n .catch(e => warnOnce(e.message));\n });\n}\n\nfunction getQueryParameters(url: string) {\n const paramStart = url.indexOf('?');\n return paramStart > 0 ? url.slice(paramStart + 1).split('&') : [];\n}\n\nfunction stripQueryParameters(url: string) {\n const start = url.indexOf('?');\n if (start < 0) return url;\n\n // preserve `language` and `worldview` params if any\n const params = getQueryParameters(url);\n const filteredParams = params.filter(param => {\n const entry = param.split('=');\n return entry[0] === 'language' || entry[0] === 'worldview';\n });\n\n if (filteredParams.length) {\n return `${url.slice(0, start)}?${filteredParams.join('&')}`;\n }\n\n return url.slice(0, start);\n}\n\nexport function cacheGet(request: Request, callback: (error: ?any, response: ?Response, fresh: ?boolean) => void): void {\n cacheOpen();\n if (!sharedCache) return callback(null);\n\n const strippedURL = stripQueryParameters(request.url);\n\n ((sharedCache: any): Promise<Cache>)\n .then(cache => {\n // manually strip URL instead of `ignoreSearch: true` because of a known\n // performance issue in Chrome https://github.com/mapbox/mapbox-gl-js/issues/8431\n cache.match(strippedURL)\n .then(response => {\n const fresh = isFresh(response);\n\n // Reinsert into cache so that order of keys in the cache is the order of access.\n // This line makes the cache a LRU instead of a FIFO cache.\n cache.delete(strippedURL);\n if (fresh) {\n cache.put(strippedURL, response.clone());\n }\n\n callback(null, response, fresh);\n })\n .catch(callback);\n })\n .catch(callback);\n\n}\n\nfunction isFresh(response: Response) {\n if (!response) return false;\n const expires = new Date(response.headers.get('Expires') || 0);\n const cacheControl = parseCacheControl(response.headers.get('Cache-Control') || '');\n return expires > Date.now() && !cacheControl['no-cache'];\n}\n\n// `Infinity` triggers a cache check after the first tile is loaded\n// so that a check is run at least once on each page load.\nlet globalEntryCounter = Infinity;\n\n// The cache check gets run on a worker. The reason for this is that\n// profiling sometimes shows this as taking up significant time on the\n// thread it gets called from. And sometimes it doesn't. It *may* be\n// fine to run this on the main thread but out of caution this is being\n// dispatched on a worker. This can be investigated further in the future.\nexport function cacheEntryPossiblyAdded(dispatcher: Dispatcher) {\n globalEntryCounter++;\n if (globalEntryCounter > cacheCheckThreshold) {\n dispatcher.getActor().send('enforceCacheSizeLimit', cacheLimit);\n globalEntryCounter = 0;\n }\n}\n\n// runs on worker, see above comment\nexport function enforceCacheSizeLimit(limit: number) {\n cacheOpen();\n if (!sharedCache) return;\n\n sharedCache\n .then(cache => {\n cache.keys().then(keys => {\n for (let i = 0; i < keys.length - limit; i++) {\n cache.delete(keys[i]);\n }\n });\n });\n}\n\nexport function clearTileCache(callback?: (err: ?Error) => void) {\n const caches = getCaches();\n if (!caches) return;\n\n const promise = window.caches.delete(CACHE_NAME);\n if (callback) {\n promise.catch(callback).then(() => callback());\n }\n}\n\nexport function setCacheLimits(limit: number, checkThreshold: number) {\n cacheLimit = limit;\n cacheCheckThreshold = checkThreshold;\n}\n","// @flow\n\nimport window from './window.js';\nimport {extend, warnOnce, isWorker} from './util.js';\nimport {isMapboxHTTPURL, hasCacheDefeatingSku} from './mapbox.js';\nimport config from './config.js';\nimport assert from 'assert';\nimport {cacheGet, cachePut} from './tile_request_cache.js';\nimport webpSupported from './webp_supported.js';\n\nimport type {Callback} from '../types/callback.js';\nimport type {Cancelable} from '../types/cancelable.js';\n\n/**\n * The type of a resource.\n * @private\n * @readonly\n * @enum {string}\n */\nconst ResourceType = {\n Unknown: 'Unknown',\n Style: 'Style',\n Source: 'Source',\n Tile: 'Tile',\n Glyphs: 'Glyphs',\n SpriteImage: 'SpriteImage',\n SpriteJSON: 'SpriteJSON',\n Image: 'Image'\n};\nexport {ResourceType};\n\nif (typeof Object.freeze == 'function') {\n Object.freeze(ResourceType);\n}\n\n/**\n * A `RequestParameters` object to be returned from Map.options.transformRequest callbacks.\n * @typedef {Object} RequestParameters\n * @property {string} url The URL to be requested.\n * @property {Object} headers The headers to be sent with the request.\n * @property {string} method Request method `'GET' | 'POST' | 'PUT'`.\n * @property {string} body Request body.\n * @property {string} type Response body type to be returned `'string' | 'json' | 'arrayBuffer'`.\n * @property {string} credentials `'same-origin'|'include'` Use 'include' to send cookies with cross-origin requests.\n * @property {boolean} collectResourceTiming If true, Resource Timing API information will be collected for these transformed requests and returned in a resourceTiming property of relevant data events.\n * @property {string} referrerPolicy A string representing the request's referrerPolicy. For more information and possible values, see the [Referrer-Policy HTTP header page](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy).\n * @example\n * // use transformRequest to modify requests that begin with `http://myHost`\n * const map = new Map({\n * container: 'map',\n * style: 'mapbox://styles/mapbox/streets-v11',\n * transformRequest: (url, resourceType) => {\n * if (resourceType === 'Source' && url.indexOf('http://myHost') > -1) {\n * return {\n * url: url.replace('http', 'https'),\n * headers: {'my-custom-header': true},\n * credentials: 'include' // Include cookies for cross-origin requests\n * };\n * }\n * }\n * });\n *\n */\nexport type RequestParameters = {\n url: string,\n headers?: Object,\n method?: 'GET' | 'POST' | 'PUT',\n body?: string,\n type?: 'string' | 'json' | 'arrayBuffer',\n credentials?: 'same-origin' | 'include',\n collectResourceTiming?: boolean,\n referrerPolicy?: ReferrerPolicyType\n}\n\nexport type ResponseCallback<T> = (error: ?Error, data: ?T, cacheControl: ?string, expires: ?string) => void;\n\nexport class AJAXError extends Error {\n status: number;\n url: string;\n constructor(message: string, status: number, url: string) {\n if (status === 401 && isMapboxHTTPURL(url)) {\n message += ': you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes';\n }\n super(message);\n this.status = status;\n this.url = url;\n }\n\n toString(): string {\n return `${this.name}: ${this.message} (${this.status}): ${this.url}`;\n }\n}\n\n// Ensure that we're sending the correct referrer from blob URL worker bundles.\n// For files loaded from the local file system, `location.origin` will be set\n// to the string(!) \"null\" (Firefox), or \"file://\" (Chrome, Safari, Edge, IE),\n// and we will set an empty referrer. Otherwise, we're using the document's URL.\n/* global self */\nexport const getReferrer: (() => string) = isWorker() ?\n () => self.worker && self.worker.referrer :\n () => (window.location.protocol === 'blob:' ? window.parent : window).location.href;\n\n// Determines whether a URL is a file:// URL. This is obviously the case if it begins\n// with file://. Relative URLs are also file:// URLs iff the original document was loaded\n// via a file:// URL.\nconst isFileURL = (url: string) => /^file:/.test(url) || (/^file:/.test(getReferrer()) && !/^\\w+:/.test(url));\n\nfunction makeFetchRequest(requestParameters: RequestParameters, callback: ResponseCallback<any>): Cancelable {\n const controller = new window.AbortController();\n const request = new window.Request(requestParameters.url, {\n method: requestParameters.method || 'GET',\n body: requestParameters.body,\n credentials: requestParameters.credentials,\n headers: requestParameters.headers,\n referrer: getReferrer(),\n referrerPolicy: requestParameters.referrerPolicy,\n signal: controller.signal\n });\n let complete = false;\n let aborted = false;\n\n const cacheIgnoringSearch = hasCacheDefeatingSku(request.url);\n\n if (requestParameters.type === 'json') {\n request.headers.set('Accept', 'application/json');\n }\n\n const validateOrFetch = (err: ?Error, cachedResponse: ?Response, responseIsFresh: ?boolean) => {\n if (aborted) return;\n\n if (err) {\n // Do fetch in case of cache error.\n // HTTP pages in Edge trigger a security error that can be ignored.\n if (err.message !== 'SecurityError') {\n warnOnce(err.toString());\n }\n }\n\n if (cachedResponse && responseIsFresh) {\n return finishRequest(cachedResponse);\n }\n\n if (cachedResponse) {\n // We can't do revalidation with 'If-None-Match' because then the\n // request doesn't have simple cors headers.\n }\n\n const requestTime = Date.now();\n\n window.fetch(request).then(response => {\n if (response.ok) {\n const cacheableResponse = cacheIgnoringSearch ? response.clone() : null;\n return finishRequest(response, cacheableResponse, requestTime);\n } else {\n return callback(new AJAXError(response.statusText, response.status, requestParameters.url));\n }\n }).catch(error => {\n if (error.name === 'AbortError') {\n // silence expected AbortError\n return;\n }\n callback(new Error(`${error.message} ${requestParameters.url}`));\n });\n };\n\n const finishRequest = (response: Response, cacheableResponse: ?Response, requestTime: ?number) => {\n (\n requestParameters.type === 'arrayBuffer' ? response.arrayBuffer() :\n requestParameters.type === 'json' ? response.json() :\n response.text()\n ).then(result => {\n if (aborted) return;\n if (cacheableResponse && requestTime) {\n // The response needs to be inserted into the cache after it has completely loaded.\n // Until it is fully loaded there is a chance it will be aborted. Aborting while\n // reading the body can cause the cache insertion to error. We could catch this error\n // in most browsers but in Firefox it seems to sometimes crash the tab. Adding\n // it to the cache here avoids that error.\n cachePut(request, cacheableResponse, requestTime);\n }\n complete = true;\n callback(null, result, response.headers.get('Cache-Control'), response.headers.get('Expires'));\n }).catch(err => {\n if (!aborted) callback(new Error(err.message));\n });\n };\n\n if (cacheIgnoringSearch) {\n cacheGet(request, validateOrFetch);\n } else {\n validateOrFetch(null, null);\n }\n\n return {cancel: () => {\n aborted = true;\n if (!complete) controller.abort();\n }};\n}\n\nfunction makeXMLHttpRequest(requestParameters: RequestParameters, callback: ResponseCallback<any>): Cancelable {\n const xhr: XMLHttpRequest = new window.XMLHttpRequest();\n\n xhr.open(requestParameters.method || 'GET', requestParameters.url, true);\n if (requestParameters.type === 'arrayBuffer') {\n xhr.responseType = 'arraybuffer';\n }\n for (const k in requestParameters.headers) {\n xhr.setRequestHeader(k, requestParameters.headers[k]);\n }\n if (requestParameters.type === 'json') {\n xhr.responseType = 'text';\n xhr.setRequestHeader('Accept', 'application/json');\n }\n xhr.withCredentials = requestParameters.credentials === 'include';\n xhr.onerror = () => {\n callback(new Error(xhr.statusText));\n };\n xhr.onload = () => {\n if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response !== null) {\n let data: mixed = xhr.response;\n if (requestParameters.type === 'json') {\n // We're manually parsing JSON here to get better error messages.\n try {\n data = JSON.parse(xhr.response);\n } catch (err) {\n return callback(err);\n }\n }\n callback(null, data, xhr.getResponseHeader('Cache-Control'), xhr.getResponseHeader('Expires'));\n } else {\n callback(new AJAXError(xhr.statusText, xhr.status, requestParameters.url));\n }\n };\n xhr.send(requestParameters.body);\n return {cancel: () => xhr.abort()};\n}\n\nexport const makeRequest = function(requestParameters: RequestParameters, callback: ResponseCallback<any>): Cancelable {\n // We're trying to use the Fetch API if possible. However, in some situations we can't use it:\n // - Safari exposes window.AbortController, but it doesn't work actually abort any requests in\n // older versions (see https://bugs.webkit.org/show_bug.cgi?id=174980#c2). In this case,\n // we dispatch the request to the main thread so that we can get an accurate referrer header.\n // - Requests for resources with the file:// URI scheme don't work with the Fetch API either. In\n // this case we unconditionally use XHR on the current thread since referrers don't matter.\n if (!isFileURL(requestParameters.url)) {\n if (window.fetch && window.Request && window.AbortController && window.Request.prototype.hasOwnProperty('signal')) {\n return makeFetchRequest(requestParameters, callback);\n }\n if (isWorker() && self.worker && self.worker.actor) {\n const queueOnMainThread = true;\n return self.worker.actor.send('getResource', requestParameters, callback, undefined, queueOnMainThread);\n }\n }\n return makeXMLHttpRequest(requestParameters, callback);\n};\n\nexport const getJSON = function(requestParameters: RequestParameters, callback: ResponseCallback<Object>): Cancelable {\n return makeRequest(extend(requestParameters, {type: 'json'}), callback);\n};\n\nexport const getArrayBuffer = function(requestParameters: RequestParameters, callback: ResponseCallback<ArrayBuffer>): Cancelable {\n return makeRequest(extend(requestParameters, {type: 'arrayBuffer'}), callback);\n};\n\nexport const postData = function(requestParameters: RequestParameters, callback: ResponseCallback<string>): Cancelable {\n return makeRequest(extend(requestParameters, {method: 'POST'}), callback);\n};\n\nexport const getData = function(requestParameters: RequestParameters, callback: ResponseCallback<string>): Cancelable {\n return makeRequest(extend(requestParameters, {method: 'GET'}), callback);\n};\n\nfunction sameOrigin(url: string) {\n const a: HTMLAnchorElement = window.document.createElement('a');\n a.href = url;\n return a.protocol === window.document.location.protocol && a.host === window.document.location.host;\n}\n\nconst transparentPngUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAAC0lEQVQYV2NgAAIAAAUAAarVyFEAAAAASUVORK5CYII=';\n\nfunction arrayBufferToImage(data: ArrayBuffer, callback: Callback<HTMLImageElement>) {\n const img: HTMLImageElement = new window.Image();\n const URL = window.URL;\n img.onload = () => {\n callback(null, img);\n URL.revokeObjectURL(img.src);\n // prevent image dataURI memory leak in Safari;\n // but don't free the image immediately because it might be uploaded in the next frame\n // https://github.com/mapbox/mapbox-gl-js/issues/10226\n img.onload = null;\n window.requestAnimationFrame(() => { img.src = transparentPngUrl; });\n };\n img.onerror = () => callback(new Error('Could not load image. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.'));\n const blob: Blob = new window.Blob([new Uint8Array(data)], {type: 'image/png'});\n img.src = data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl;\n}\n\nfunction arrayBufferToImageBitmap(data: ArrayBuffer, callback: Callback<ImageBitmap>) {\n const blob: Blob = new window.Blob([new Uint8Array(data)], {type: 'image/png'});\n window.createImageBitmap(blob).then((imgBitmap) => {\n callback(null, imgBitmap);\n }).catch((e) => {\n callback(new Error(`Could not load image because of ${e.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`));\n });\n}\n\nlet imageQueue, numImageRequests;\nexport const resetImageRequestQueue = () => {\n imageQueue = [];\n numImageRequests = 0;\n};\nresetImageRequestQueue();\n\nexport const getImage = function(requestParameters: RequestParameters, callback: ResponseCallback<HTMLImageElement | ImageBitmap>): Cancelable {\n if (webpSupported.supported) {\n if (!requestParameters.headers) {\n requestParameters.headers = {};\n }\n requestParameters.headers.accept = 'image/webp,*/*';\n }\n\n // limit concurrent image loads to help with raster sources performance on big screens\n if (numImageRequests >= config.MAX_PARALLEL_IMAGE_REQUESTS) {\n const queued = {\n requestParameters,\n callback,\n cancelled: false,\n // $FlowFixMe[object-this-reference]\n cancel() { this.cancelled = true; }\n };\n imageQueue.push(queued);\n return queued;\n }\n numImageRequests++;\n\n let advanced = false;\n const advanceImageRequestQueue = () => {\n if (advanced) return;\n advanced = true;\n numImageRequests--;\n assert(numImageRequests >= 0);\n while (imageQueue.length && numImageRequests < config.MAX_PARALLEL_IMAGE_REQUESTS) { // eslint-disable-line\n const request = imageQueue.shift();\n const {requestParameters, callback, cancelled} = request;\n if (!cancelled) {\n // $FlowFixMe[cannot-write] - Flow can't infer that cancel is a writable property\n request.cancel = getImage(requestParameters, callback).cancel;\n }\n }\n };\n\n // request the image with XHR to work around caching issues\n // see https://github.com/mapbox/mapbox-gl-js/issues/1470\n const request = getArrayBuffer(requestParameters, (err: ?Error, data: ?ArrayBuffer, cacheControl: ?string, expires: ?string) => {\n\n advanceImageRequestQueue();\n\n if (err) {\n callback(err);\n } else if (data) {\n if (window.createImageBitmap) {\n arrayBufferToImageBitmap(data, (err, imgBitmap) => callback(err, imgBitmap, cacheControl, expires));\n } else {\n arrayBufferToImage(data, (err, img) => callback(err, img, cacheControl, expires));\n }\n }\n });\n\n return {\n cancel: () => {\n request.cancel();\n advanceImageRequestQueue();\n }\n };\n};\n\nexport const getVideo = function(urls: Array<string>, callback: Callback<HTMLVideoElement>): Cancelable {\n const video: HTMLVideoElement = window.document.createElement('video');\n video.muted = true;\n video.onloadstart = function() {\n callback(null, video);\n };\n for (let i = 0; i < urls.length; i++) {\n const s: HTMLSourceElement = window.document.createElement('source');\n if (!sameOrigin(urls[i])) {\n video.crossOrigin = 'Anonymous';\n }\n s.src = urls[i];\n video.appendChild(s);\n }\n return {cancel: () => {}};\n};\n","// @flow\n\nimport assert from 'assert';\n\nimport Grid from 'grid-index';\nimport Color from '../style-spec/util/color.js';\nimport {StylePropertyFunction, StyleExpression, ZoomDependentExpression, ZoomConstantExpression} from '../style-spec/expression/index.js';\nimport CompoundExpression from '../style-spec/expression/compound_expression.js';\nimport expressions from '../style-spec/expression/definitions/index.js';\nimport ResolvedImage from '../style-spec/expression/types/resolved_image.js';\nimport window from './window.js';\nimport {AJAXError} from './ajax.js';\n\nimport type {Transferable} from '../types/transferable.js';\n\ntype SerializedObject = interface { [_: string]: Serialized };\nexport type Serialized =\n | null\n | void\n | boolean\n | number\n | string\n | Boolean\n | Number\n | String\n | Date\n | RegExp\n | ArrayBuffer\n | $ArrayBufferView\n | ImageData\n | Array<Serialized>\n | SerializedObject;\n\ntype Registry = {\n [_: string]: {\n klass: Class<any>,\n omit: $ReadOnlyArray<string>\n }\n};\n\ntype RegisterOptions<T> = {\n omit?: $ReadOnlyArray<$Keys<T>>\n}\n\nconst registry: Registry = {};\n\n/**\n * Register the given class as serializable.\n *\n * @param options\n * @param options.omit List of properties to omit from serialization (e.g., cached/computed properties)\n *\n * @private\n */\nexport function register<T: any>(klass: Class<T>, name: string, options: RegisterOptions<T> = {}) {\n assert(name, 'Can\\'t register a class without a name.');\n assert(!registry[name], `${name} is already registered.`);\n (Object.defineProperty: any)(klass, '_classRegistryKey', {\n value: name,\n writeable: false\n });\n registry[name] = {\n klass,\n omit: options.omit || []\n };\n}\n\nregister(Object, 'Object');\n\ntype SerializedGrid = { buffer: ArrayBuffer };\n\n(Grid: any).serialize = function serialize(grid: Grid, transferables?: Array<Transferable>): SerializedGrid {\n const buffer = grid.toArrayBuffer();\n if (transferables) {\n transferables.push(buffer);\n }\n return {buffer};\n};\n\n(Grid: any).deserialize = function deserialize(serialized: SerializedGrid): Grid {\n return new Grid(serialized.buffer);\n};\n\nObject.defineProperty(Grid, 'name', {value: 'Grid'});\n\nregister(Grid, 'Grid');\n\nregister(Color, 'Color');\nregister(Error, 'Error');\nregister(AJAXError, 'AJAXError');\nregister(ResolvedImage, 'ResolvedImage');\nregister(StylePropertyFunction, 'StylePropertyFunction');\nregister(StyleExpression, 'StyleExpression', {omit: ['_evaluator']});\n\nregister(ZoomDependentExpression, 'ZoomDependentExpression');\nregister(ZoomConstantExpression, 'ZoomConstantExpression');\nregister(CompoundExpression, 'CompoundExpression', {omit: ['_evaluate']});\nfor (const name in expressions) {\n if (!registry[(expressions[name]: any)._classRegistryKey]) register(expressions[name], `Expression${name}`);\n}\n\nfunction isArrayBuffer(val: any): boolean {\n return val && typeof ArrayBuffer !== 'undefined' &&\n (val instanceof ArrayBuffer || (val.constructor && val.constructor.name === 'ArrayBuffer'));\n}\n\nfunction isImageBitmap(val: any): boolean {\n return window.ImageBitmap &&\n val instanceof window.ImageBitmap;\n}\n\n/**\n * Serialize the given object for transfer to or from a web worker.\n *\n * For non-builtin types, recursively serialize each property (possibly\n * omitting certain properties - see register()), and package the result along\n * with the constructor's `name` so that the appropriate constructor can be\n * looked up in `deserialize()`.\n *\n * If a `transferables` array is provided, add any transferable objects (i.e.,\n * any ArrayBuffers or ArrayBuffer views) to the list. (If a copy is needed,\n * this should happen in the client code, before using serialize().)\n *\n * @private\n */\nexport function serialize(input: mixed, transferables: ?Array<Transferable>): Serialized {\n if (input === null ||\n input === undefined ||\n typeof input === 'boolean' ||\n typeof input === 'number' ||\n typeof input === 'string' ||\n input instanceof Boolean ||\n input instanceof Number ||\n input instanceof String ||\n input instanceof Date ||\n input instanceof RegExp) {\n return input;\n }\n\n if (isArrayBuffer(input) || isImageBitmap(input)) {\n if (transferables) {\n transferables.push(((input: any): ArrayBuffer));\n }\n return (input: any);\n }\n\n if (ArrayBuffer.isView(input)) {\n const view: $ArrayBufferView = (input: any);\n if (transferables) {\n transferables.push(view.buffer);\n }\n return view;\n }\n\n if (input instanceof window.ImageData) {\n if (transferables) {\n transferables.push(input.data.buffer);\n }\n return input;\n }\n\n if (Array.isArray(input)) {\n const serialized: Array<Serialized> = [];\n for (const item of input) {\n serialized.push(serialize(item, transferables));\n }\n return serialized;\n }\n\n if (typeof input === 'object') {\n const klass = (input.constructor: any);\n const name = klass._classRegistryKey;\n if (!name) {\n throw new Error(`can't serialize object of unregistered class ${name}`);\n }\n assert(registry[name]);\n\n const properties: SerializedObject = klass.serialize ?\n // (Temporary workaround) allow a class to provide static\n // `serialize()` and `deserialize()` methods to bypass the generic\n // approach.\n // This temporary workaround lets us use the generic serialization\n // approach for objects whose members include instances of dynamic\n // StructArray types. Once we refactor StructArray to be static,\n // we can remove this complexity.\n (klass.serialize(input, transferables): SerializedObject) : {};\n\n if (!klass.serialize) {\n for (const key in input) {\n // any cast due to https://github.com/facebook/flow/issues/5393\n if (!(input: any).hasOwnProperty(key)) continue;\n if (registry[name].omit.indexOf(key) >= 0) continue;\n const property = (input: any)[key];\n properties[key] = serialize(property, transferables);\n }\n if (input instanceof Error) {\n properties['message'] = input.message;\n }\n } else {\n // make sure statically serialized object survives transfer of $name property\n assert(!transferables || properties !== transferables[transferables.length - 1]);\n }\n\n if (properties['$name']) {\n throw new Error('$name property is reserved for worker serialization logic.');\n }\n if (name !== 'Object') {\n properties['$name'] = name;\n }\n\n return properties;\n }\n\n throw new Error(`can't serialize object of type ${typeof input}`);\n}\n\nexport function deserialize(input: Serialized): mixed {\n if (input === null ||\n input === undefined ||\n typeof input === 'boolean' ||\n typeof input === 'number' ||\n typeof input === 'string' ||\n input instanceof Boolean ||\n input instanceof Number ||\n input instanceof String ||\n input instanceof Date ||\n input instanceof RegExp ||\n isArrayBuffer(input) ||\n isImageBitmap(input) ||\n ArrayBuffer.isView(input) ||\n input instanceof window.ImageData) {\n return input;\n }\n\n if (Array.isArray(input)) {\n return input.map(deserialize);\n }\n\n if (typeof input === 'object') {\n const name = (input: any).$name || 'Object';\n\n const {klass} = registry[name];\n if (!klass) {\n throw new Error(`can't deserialize unregistered class ${name}`);\n }\n\n if (klass.deserialize) {\n return (klass.deserialize: typeof deserialize)(input);\n }\n\n const result: {[_: string]: any} = Object.create(klass.prototype);\n\n for (const key of Object.keys(input)) {\n // $FlowFixMe[incompatible-type]\n if (key === '$name') continue;\n const value = (input: SerializedObject)[key];\n result[key] = deserialize(value);\n }\n\n return result;\n }\n\n throw new Error(`can't deserialize object of type ${typeof input}`);\n}\n","// @flow\n\n/**\n * Invokes the wrapped function in a non-blocking way when trigger() is called. Invocation requests\n * are ignored until the function was actually invoked.\n *\n * @private\n */\nclass ThrottledInvoker {\n _channel: ?MessageChannel;\n _triggered: boolean;\n _callback: Function\n\n constructor(callback: Function) {\n this._callback = callback;\n this._triggered = false;\n if (typeof MessageChannel !== 'undefined') {\n this._channel = new MessageChannel();\n this._channel.port2.onmessage = () => {\n this._triggered = false;\n this._callback();\n };\n }\n }\n\n trigger() {\n if (!this._triggered) {\n this._triggered = true;\n if (this._channel) {\n this._channel.port1.postMessage(true);\n } else {\n setTimeout(() => {\n this._triggered = false;\n this._callback();\n }, 0);\n }\n }\n }\n\n remove() {\n this._channel = undefined;\n this._callback = () => {};\n }\n}\n\nexport default ThrottledInvoker;\n","// @flow\n\nimport window from '../util/window.js';\nimport {\n PerformanceMarkers,\n LivePerformanceUtils\n} from '../util/live_performance.js';\nconst performance = window.performance;\n\nperformance.mark('library-evaluate');\n\nimport {isWorker} from '../util/util.js';\nimport type {RequestParameters} from '../util/ajax.js';\n\nexport type PerformanceMetrics = {\n loadTime: number,\n fullLoadTime: number,\n percentDroppedFrames: number,\n parseTile: number,\n parseTile1: number,\n parseTile2: number,\n workerTask: number,\n workerInitialization: number,\n workerEvaluateScript: number,\n workerIdle: number,\n workerIdlePercent: number,\n placementTime: number,\n timelines: Array<Object>\n};\n\nexport type PerformanceMark = {mark: string, name: string};\n\nlet fullLoadFinished = false;\nlet placementTime = 0;\n\nexport const PerformanceUtils = {\n mark(marker: $Keys<typeof PerformanceMarkers>) {\n LivePerformanceUtils.mark(marker);\n\n if (marker === PerformanceMarkers.fullLoad) {\n fullLoadFinished = true;\n }\n },\n measure(name: string, begin?: string, end?: string) {\n LivePerformanceUtils.measure(name, begin, end);\n },\n beginMeasure(name: string): PerformanceMark {\n const mark = name;\n performance.mark(mark);\n return {\n mark,\n name\n };\n },\n endMeasure(m: PerformanceMark) {\n performance.measure(m.name, m.mark);\n },\n recordPlacementTime(time: number) {\n // Ignore placementTimes during loading\n if (!fullLoadFinished) {\n return;\n }\n\n placementTime += time;\n },\n frame(timestamp: number, isRenderFrame: boolean) {\n performance.mark('frame', {\n detail: {\n timestamp,\n isRenderFrame\n }\n });\n },\n clearMetrics() {\n placementTime = 0;\n fullLoadFinished = false;\n\n performance.clearMeasures('loadTime');\n performance.clearMeasures('fullLoadTime');\n\n for (const marker in PerformanceMarkers) {\n performance.clearMarks(PerformanceMarkers[marker]);\n }\n },\n\n getPerformanceMetrics(): PerformanceMetrics {\n const metrics = {};\n\n performance.measure('loadTime', PerformanceMarkers.create, PerformanceMarkers.load);\n performance.measure('fullLoadTime', PerformanceMarkers.create, PerformanceMarkers.fullLoad);\n\n const measures = performance.getEntriesByType('measure');\n for (const measure of measures) {\n metrics[measure.name] = (metrics[measure.name] || 0) + measure.duration;\n }\n\n metrics.placementTime = placementTime;\n\n return metrics;\n },\n\n getWorkerPerformanceMetrics(): { timeOrigin: string, entries: Array<Object>, scope: string } {\n const entries = performance.getEntries().map(entry => {\n const result = entry.toJSON();\n if (entry.detail) {\n Object.assign(result, {\n detail: entry.detail\n });\n }\n return result;\n });\n return {\n scope: isWorker() ? 'Worker' : 'Window',\n timeOrigin: performance.timeOrigin,\n entries\n };\n }\n};\n\nexport function getPerformanceMeasurement(request: ?RequestParameters): Array<PerformanceEntry> {\n const url = request ? request.url.toString() : undefined;\n return performance.getEntriesByName(url);\n}\n\nexport default performance;\n","// @flow\n\nimport ThrottledInvoker from './throttled_invoker.js';\nimport {bindAll, isWorker} from './util.js';\nimport {PerformanceUtils} from './performance.js';\n\nimport type {Cancelable} from '../types/cancelable.js';\n\ntype TaskMetadata = {\n type: 'message' | 'maybePrepare' | 'parseTile',\n isSymbolTile: ?boolean,\n zoom?: number\n};\n\ntype TaskFunction = () => void;\n\ntype Task = {\n fn: TaskFunction,\n metadata: TaskMetadata,\n priority: number,\n id: number\n};\n\nclass Scheduler {\n\n tasks: { [number]: Task };\n taskQueue: Array<number>;\n invoker: ThrottledInvoker;\n nextId: number;\n\n constructor() {\n this.tasks = {};\n this.taskQueue = [];\n bindAll(['process'], this);\n // $FlowFixMe[method-unbinding]\n this.invoker = new ThrottledInvoker(this.process);\n\n this.nextId = 0;\n }\n\n add(fn: TaskFunction, metadata: TaskMetadata): Cancelable {\n const id = this.nextId++;\n const priority = getPriority(metadata);\n\n if (priority === 0) {\n // Process tasks with priority 0 immediately. Do not yield to the event loop.\n const m = isWorker() ? PerformanceUtils.beginMeasure('workerTask') : undefined;\n try {\n fn();\n } finally {\n if (m) PerformanceUtils.endMeasure(m);\n }\n return {\n cancel: () => {}\n };\n }\n\n this.tasks[id] = {fn, metadata, priority, id};\n this.taskQueue.push(id);\n this.invoker.trigger();\n return {\n cancel: () => {\n delete this.tasks[id];\n }\n };\n }\n\n process() {\n const m = isWorker() ? PerformanceUtils.beginMeasure('workerTask') : undefined;\n try {\n this.taskQueue = this.taskQueue.filter(id => !!this.tasks[id]);\n\n if (!this.taskQueue.length) {\n return;\n }\n const id = this.pick();\n if (id === null) return;\n\n const task = this.tasks[id];\n delete this.tasks[id];\n // Schedule another process call if we know there's more to process _before_ invoking the\n // current task. This is necessary so that processing continues even if the current task\n // doesn't execute successfully.\n if (this.taskQueue.length) {\n this.invoker.trigger();\n }\n if (!task) {\n // If the task ID doesn't have associated task data anymore, it was canceled.\n return;\n }\n\n task.fn();\n } finally {\n if (m) PerformanceUtils.endMeasure(m);\n }\n }\n\n pick(): null | number {\n let minIndex = null;\n let minPriority = Infinity;\n for (let i = 0; i < this.taskQueue.length; i++) {\n const id = this.taskQueue[i];\n const task = this.tasks[id];\n if (task.priority < minPriority) {\n minPriority = task.priority;\n minIndex = i;\n }\n }\n if (minIndex === null) return null;\n const id = this.taskQueue[minIndex];\n this.taskQueue.splice(minIndex, 1);\n return id;\n }\n\n remove() {\n this.invoker.remove();\n }\n}\n\nfunction getPriority({type, isSymbolTile, zoom}: TaskMetadata): number {\n zoom = zoom || 0;\n if (type === 'message') return 0;\n if (type === 'maybePrepare' && !isSymbolTile) return 100 - zoom;\n if (type === 'parseTile' && !isSymbolTile) return 200 - zoom;\n if (type === 'parseTile' && isSymbolTile) return 300 - zoom;\n if (type === 'maybePrepare' && isSymbolTile) return 400 - zoom;\n return 500;\n}\n\nexport default Scheduler;\n","// @flow\n\nimport {bindAll, isWorker, isSafari} from './util.js';\nimport window from './window.js';\nimport {serialize, deserialize} from './web_worker_transfer.js';\nimport Scheduler from './scheduler.js';\n\nimport type {Transferable} from '../types/transferable.js';\nimport type {Cancelable} from '../types/cancelable.js';\n\n/**\n * An implementation of the [Actor design pattern](http://en.wikipedia.org/wiki/Actor_model)\n * that maintains the relationship between asynchronous tasks and the objects\n * that spin them off - in this case, tasks like parsing parts of styles,\n * owned by the styles\n *\n * @param {WebWorker} target\n * @param {WebWorker} parent\n * @param {string|number} mapId A unique identifier for the Map instance using this Actor.\n * @private\n */\nclass Actor {\n target: any;\n parent: any;\n mapId: ?number;\n callbacks: { number: any };\n name: string;\n cancelCallbacks: { number: Cancelable };\n globalScope: any;\n scheduler: Scheduler;\n\n constructor(target: any, parent: any, mapId: ?number) {\n this.target = target;\n this.parent = parent;\n this.mapId = mapId;\n this.callbacks = {};\n this.cancelCallbacks = {};\n bindAll(['receive'], this);\n // $FlowFixMe[method-unbinding]\n this.target.addEventListener('message', this.receive, false);\n this.globalScope = isWorker() ? target : window;\n this.scheduler = new Scheduler();\n }\n\n /**\n * Sends a message from a main-thread map to a Worker or from a Worker back to\n * a main-thread map instance.\n *\n * @param type The name of the target method to invoke or '[source-type].[source-name].name' for a method on a WorkerSource.\n * @param targetMapId A particular mapId to which to send this message.\n * @private\n */\n send(type: string, data: mixed, callback: ?Function, targetMapId: ?string, mustQueue: boolean = false, callbackMetadata?: Object): ?Cancelable {\n // We're using a string ID instead of numbers because they are being used as object keys\n // anyway, and thus stringified implicitly. We use random IDs because an actor may receive\n // message from multiple other actors which could run in different execution context. A\n // linearly increasing ID could produce collisions.\n const id = Math.round((Math.random() * 1e18)).toString(36).substring(0, 10);\n if (callback) {\n callback.metadata = callbackMetadata;\n this.callbacks[id] = callback;\n }\n const buffers: ?Array<Transferable> = isSafari(this.globalScope) ? undefined : [];\n this.target.postMessage({\n id,\n type,\n hasCallback: !!callback,\n targetMapId,\n mustQueue,\n sourceMapId: this.mapId,\n data: serialize(data, buffers)\n }, buffers);\n return {\n cancel: () => {\n if (callback) {\n // Set the callback to null so that it never fires after the request is aborted.\n delete this.callbacks[id];\n }\n this.target.postMessage({\n id,\n type: '<cancel>',\n targetMapId,\n sourceMapId: this.mapId\n });\n }\n };\n }\n\n receive(message: Object) {\n const data = message.data,\n id = data.id;\n\n if (!id) {\n return;\n }\n\n if (data.targetMapId && this.mapId !== data.targetMapId) {\n return;\n }\n\n if (data.type === '<cancel>') {\n // Remove the original request from the queue. This is only possible if it\n // hasn't been kicked off yet. The id will remain in the queue, but because\n // there is no associated task, it will be dropped once it's time to execute it.\n const cancel = this.cancelCallbacks[id];\n delete this.cancelCallbacks[id];\n if (cancel) {\n cancel.cancel();\n }\n } else {\n if (data.mustQueue || isWorker()) {\n // for worker tasks that are often cancelled, such as loadTile, store them before actually\n // processing them. This is necessary because we want to keep receiving <cancel> messages.\n // Some tasks may take a while in the worker thread, so before executing the next task\n // in our queue, postMessage preempts this and <cancel> messages can be processed.\n // We're using a MessageChannel object to get throttle the process() flow to one at a time.\n const callback = this.callbacks[id];\n const metadata = (callback && callback.metadata) || {type: \"message\"};\n this.cancelCallbacks[id] = this.scheduler.add(() => this.processTask(id, data), metadata);\n } else {\n // In the main thread, process messages immediately so that other work does not slip in\n // between getting partial data back from workers.\n this.processTask(id, data);\n }\n }\n }\n\n processTask(id: number, task: any) {\n if (task.type === '<response>') {\n // The done() function in the counterpart has been called, and we are now\n // firing the callback in the originating actor, if there is one.\n const callback = this.callbacks[id];\n delete this.callbacks[id];\n if (callback) {\n // If we get a response, but don't have a callback, the request was canceled.\n if (task.error) {\n callback(deserialize(task.error));\n } else {\n callback(null, deserialize(task.data));\n }\n }\n } else {\n const buffers: ?Array<Transferable> = isSafari(this.globalScope) ? undefined : [];\n const done = task.hasCallback ? (err: ?Error, data: mixed) => {\n delete this.cancelCallbacks[id];\n this.target.postMessage({\n id,\n type: '<response>',\n sourceMapId: this.mapId,\n error: err ? serialize(err) : null,\n data: serialize(data, buffers)\n }, buffers);\n } : (_) => {\n };\n\n const params = (deserialize(task.data): any);\n if (this.parent[task.type]) {\n // task.type == 'loadTile', 'removeTile', etc.\n this.parent[task.type](task.sourceMapId, params, done);\n } else if (this.parent.getWorkerSource) {\n // task.type == sourcetype.method\n const keys = task.type.split('.');\n const scope = (this.parent: any).getWorkerSource(task.sourceMapId, keys[0], params.source);\n scope[keys[1]](params, done);\n } else {\n // No function was found.\n done(new Error(`Could not find function ${task.type}`));\n }\n }\n }\n\n remove() {\n this.scheduler.remove();\n // $FlowFixMe[method-unbinding]\n this.target.removeEventListener('message', this.receive, false);\n }\n}\n\nexport default Actor;\n","// @flow\n\nimport {extend} from './util.js';\nimport type {MapEvent} from '../ui/events.js';\n\ntype Listener = (Object) => any;\ntype Listeners = {[_: string]: Array<Listener> };\n\nfunction _addEventListener(type: string, listener: Listener, listenerList: Listeners) {\n const listenerExists = listenerList[type] && listenerList[type].indexOf(listener) !== -1;\n if (!listenerExists) {\n listenerList[type] = listenerList[type] || [];\n listenerList[type].push(listener);\n }\n}\n\nfunction _removeEventListener(type: string, listener: Listener, listenerList: Listeners) {\n if (listenerList && listenerList[type]) {\n const index = listenerList[type].indexOf(listener);\n if (index !== -1) {\n listenerList[type].splice(index, 1);\n }\n }\n}\n\nexport class Event {\n +type: string;\n\n constructor(type: string, data: Object = {}) {\n extend(this, data);\n this.type = type;\n }\n}\n\ninterface ErrorLike {\n message: string;\n}\n\nexport class ErrorEvent extends Event {\n error: ErrorLike;\n\n constructor(error: ErrorLike, data: Object = {}) {\n super('error', extend({error}, data));\n }\n}\n\n/**\n * `Evented` mixes methods into other classes for event capabilities.\n *\n * Unless you are developing a plugin you will most likely use these methods through classes like `Map` or `Popup`.\n *\n * For lists of events you can listen for, see API documentation for specific classes: [`Map`](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-events), [`Marker`](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-events), [`Popup`](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-events), and [`GeolocationControl`](https://docs.mapbox.com/mapbox-gl-js/api/map/#map-events).\n *\n * @mixin Evented\n */\nexport class Evented {\n _listeners: Listeners;\n _oneTimeListeners: Listeners;\n _eventedParent: ?Evented;\n _eventedParentData: ?(Object | () => Object);\n\n /**\n * Adds a listener to a specified event type.\n *\n * @param {string} type The event type to add a listen for.\n * @param {Function} listener The function to be called when the event is fired.\n * The listener function is called with the data object passed to `fire`,\n * extended with `target` and `type` properties.\n * @returns {Object} Returns itself to allow for method chaining.\n */\n on(type: MapEvent, listener: Listener): this {\n this._listeners = this._listeners || {};\n _addEventListener(type, listener, this._listeners);\n\n return this;\n }\n\n /**\n * Removes a previously registered event listener.\n *\n * @param {string} type The event type to remove listeners for.\n * @param {Function} listener The listener function to remove.\n * @returns {Object} Returns itself to allow for method chaining.\n */\n off(type: MapEvent, listener: Listener): this {\n _removeEventListener(type, listener, this._listeners);\n _removeEventListener(type, listener, this._oneTimeListeners);\n\n return this;\n }\n\n /**\n * Adds a listener that will be called only once to a specified event type.\n *\n * The listener will be called first time the event fires after the listener is registered.\n *\n * @param {string} type The event type to listen for.\n * @param {Function} listener (Optional) The function to be called when the event is fired once.\n * If not provided, returns a Promise that will be resolved when the event is fired once.\n * @returns {Object} Returns `this` | Promise.\n */\n once(type: MapEvent, listener?: Listener): this | Promise<Event> {\n if (!listener) {\n return new Promise(resolve => this.once(type, resolve));\n }\n\n this._oneTimeListeners = this._oneTimeListeners || {};\n _addEventListener(type, listener, this._oneTimeListeners);\n\n return this;\n }\n\n fire(event: Event, properties?: Object): this {\n // Compatibility with (type: string, properties: Object) signature from previous versions.\n // See https://github.com/mapbox/mapbox-gl-js/issues/6522,\n // https://github.com/mapbox/mapbox-gl-draw/issues/766\n if (typeof event === 'string') {\n event = new Event(event, properties || {});\n }\n\n const type = event.type;\n\n if (this.listens(type)) {\n (event: any).target = this;\n\n // make sure adding or removing listeners inside other listeners won't cause an infinite loop\n const listeners = this._listeners && this._listeners[type] ? this._listeners[type].slice() : [];\n\n for (const listener of listeners) {\n listener.call(this, event);\n }\n\n const oneTimeListeners = this._oneTimeListeners && this._oneTimeListeners[type] ? this._oneTimeListeners[type].slice() : [];\n for (const listener of oneTimeListeners) {\n _removeEventListener(type, listener, this._oneTimeListeners);\n listener.call(this, event);\n }\n\n const parent = this._eventedParent;\n if (parent) {\n extend(\n event,\n typeof this._eventedParentData === 'function' ? this._eventedParentData() : this._eventedParentData\n );\n parent.fire(event);\n }\n\n // To ensure that no error events are dropped, print them to the\n // console if they have no listeners.\n } else if (event instanceof ErrorEvent) {\n console.error(event.error);\n }\n\n return this;\n }\n\n /**\n * Returns true if this instance of Evented or any forwarded instances of Evented have a listener for the specified type.\n *\n * @param {string} type The event type.\n * @returns {boolean} Returns `true` if there is at least one registered listener for specified event type, `false` otherwise.\n * @private\n */\n listens(type: string): boolean {\n return !!(\n (this._listeners && this._listeners[type] && this._listeners[type].length > 0) ||\n (this._oneTimeListeners && this._oneTimeListeners[type] && this._oneTimeListeners[type].length > 0) ||\n (this._eventedParent && this._eventedParent.listens(type))\n );\n }\n\n /**\n * Bubble all events fired by this instance of Evented to this parent instance of Evented.\n *\n * @returns {Object} `this`\n * @private\n */\n setEventedParent(parent: ?Evented, data?: Object | () => Object): this {\n this._eventedParent = parent;\n this._eventedParentData = data;\n\n return this;\n }\n}\n","// @flow\n\n// Turn jsonlint-lines-primitives objects into primitive objects\nexport function unbundle(value: mixed): mixed {\n if (value instanceof Number || value instanceof String || value instanceof Boolean) {\n return value.valueOf();\n } else {\n return value;\n }\n}\n\nexport function deepUnbundle(value: mixed): mixed {\n if (Array.isArray(value)) {\n return value.map(deepUnbundle);\n } else if (value instanceof Object && !(value instanceof Number || value instanceof String || value instanceof Boolean)) {\n const unbundledValue: { [key: string]: mixed } = {};\n for (const key in value) {\n unbundledValue[key] = deepUnbundle(value[key]);\n }\n return unbundledValue;\n }\n\n return unbundle(value);\n}\n","// @flow\n\n// Note: Do not inherit from Error. It breaks when transpiling to ES5.\n\nexport default class ValidationError {\n message: string;\n identifier: ?string;\n line: ?number;\n\n constructor(key: ?string, value: ?{ __line__: number }, message: string, identifier: ?string) {\n this.message = (key ? `${key}: ` : '') + message;\n if (identifier) this.identifier = identifier;\n\n if (value !== null && value !== undefined && value.__line__) {\n this.line = value.__line__;\n }\n }\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error.js';\nimport getType from '../util/get_type.js';\nimport validateSpec from './validate.js';\n\nimport type {ValidationOptions} from './validate.js';\n\ntype Options = ValidationOptions & {\n objectElementValidators?: Function;\n};\n\nexport default function validateObject(options: Options): Array<ValidationError> {\n const key = options.key;\n const object = options.value;\n const elementSpecs = options.valueSpec || {};\n const elementValidators = options.objectElementValidators || {};\n const style = options.style;\n const styleSpec = options.styleSpec;\n let errors = [];\n\n const type = getType(object);\n if (type !== 'object') {\n return [new ValidationError(key, object, `object expected, ${type} found`)];\n }\n\n for (const objectKey in object) {\n const elementSpecKey = objectKey.split('.')[0]; // treat 'paint.*' as 'paint'\n const elementSpec = elementSpecs[elementSpecKey] || elementSpecs['*'];\n\n let validateElement;\n if (elementValidators[elementSpecKey]) {\n validateElement = elementValidators[elementSpecKey];\n } else if (elementSpecs[elementSpecKey]) {\n validateElement = validateSpec;\n } else if (elementValidators['*']) {\n validateElement = elementValidators['*'];\n } else if (elementSpecs['*']) {\n validateElement = validateSpec;\n }\n\n if (!validateElement) {\n errors.push(new ValidationError(key, object[objectKey], `unknown property \"${objectKey}\"`));\n continue;\n }\n\n errors = errors.concat(validateElement({\n key: (key ? `${key}.` : key) + objectKey,\n value: object[objectKey],\n valueSpec: elementSpec,\n style,\n styleSpec,\n object,\n objectKey\n // $FlowFixMe[extra-arg]\n }, object));\n }\n\n for (const elementSpecKey in elementSpecs) {\n // Don't check `required` when there's a custom validator for that property.\n if (elementValidators[elementSpecKey]) {\n continue;\n }\n\n if (elementSpecs[elementSpecKey].required && elementSpecs[elementSpecKey]['default'] === undefined && object[elementSpecKey] === undefined) {\n errors.push(new ValidationError(key, object, `missing required property \"${elementSpecKey}\"`));\n }\n }\n\n return errors;\n}\n","// @flow\n\nimport getType from '../util/get_type.js';\nimport validate from './validate.js';\nimport ValidationError from '../error/validation_error.js';\n\nimport type {ValidationOptions} from './validate.js';\n\ntype Options = ValidationOptions & {\n arrayElementValidator: Function;\n};\n\nexport default function validateArray(options: Options): Array<ValidationError> {\n const array = options.value;\n const arraySpec = options.valueSpec;\n const style = options.style;\n const styleSpec = options.styleSpec;\n const key = options.key;\n const validateArrayElement = options.arrayElementValidator || validate;\n\n if (getType(array) !== 'array') {\n return [new ValidationError(key, array, `array expected, ${getType(array)} found`)];\n }\n\n if (arraySpec.length && array.length !== arraySpec.length) {\n return [new ValidationError(key, array, `array length ${arraySpec.length} expected, length ${array.length} found`)];\n }\n\n if (arraySpec['min-length'] && array.length < arraySpec['min-length']) {\n return [new ValidationError(key, array, `array length at least ${arraySpec['min-length']} expected, length ${array.length} found`)];\n }\n\n let arrayElementSpec = {\n \"type\": arraySpec.value,\n \"values\": arraySpec.values,\n \"minimum\": arraySpec.minimum,\n \"maximum\": arraySpec.maximum,\n function: undefined\n };\n\n if (styleSpec.$version < 7) {\n arrayElementSpec.function = arraySpec.function;\n }\n\n if (getType(arraySpec.value) === 'object') {\n arrayElementSpec = arraySpec.value;\n }\n\n let errors = [];\n for (let i = 0; i < array.length; i++) {\n errors = errors.concat(validateArrayElement({\n array,\n arrayIndex: i,\n value: array[i],\n valueSpec: arrayElementSpec,\n style,\n styleSpec,\n key: `${key}[${i}]`\n }));\n }\n return errors;\n}\n","// @flow\n\nimport getType from '../util/get_type.js';\nimport ValidationError from '../error/validation_error.js';\n\nimport type {ValidationOptions} from './validate.js';\n\ntype Options = ValidationOptions & {\n arrayIndex: number;\n}\n\nexport default function validateNumber(options: Options): Array<ValidationError> {\n const key = options.key;\n const value = options.value;\n const valueSpec = options.valueSpec;\n let type = getType(value);\n\n // eslint-disable-next-line no-self-compare\n if (type === 'number' && value !== value) {\n type = 'NaN';\n }\n\n if (type !== 'number') {\n return [new ValidationError(key, value, `number expected, ${type} found`)];\n }\n\n if ('minimum' in valueSpec) {\n let specMin = valueSpec.minimum;\n if (getType(valueSpec.minimum) === 'array') {\n const i = options.arrayIndex;\n specMin = valueSpec.minimum[i];\n }\n if (value < specMin) {\n return [new ValidationError(key, value, `${value} is less than the minimum value ${specMin}`)];\n }\n }\n\n if ('maximum' in valueSpec) {\n let specMax = valueSpec.maximum;\n if (getType(valueSpec.maximum) === 'array') {\n const i = options.arrayIndex;\n specMax = valueSpec.maximum[i];\n }\n if (value > specMax) {\n return [new ValidationError(key, value, `${value} is greater than the maximum value ${specMax}`)];\n }\n }\n\n return [];\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error.js';\nimport getType from '../util/get_type.js';\nimport validate from './validate.js';\nimport validateObject from './validate_object.js';\nimport validateArray from './validate_array.js';\nimport validateNumber from './validate_number.js';\nimport {isExpression} from '../expression/index.js';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint.js';\nimport {\n supportsPropertyExpression,\n supportsZoomExpression,\n supportsInterpolation\n} from '../util/properties.js';\n\nimport type {ValidationOptions} from './validate.js';\n\nexport default function validateFunction(options: ValidationOptions): any {\n const functionValueSpec = options.valueSpec;\n const functionType = unbundle(options.value.type);\n let stopKeyType;\n let stopDomainValues: {[string | number]: boolean} = {};\n let previousStopDomainValue: ?mixed;\n let previousStopDomainZoom;\n\n const isZoomFunction = functionType !== 'categorical' && options.value.property === undefined;\n const isPropertyFunction = !isZoomFunction;\n const isZoomAndPropertyFunction =\n getType(options.value.stops) === 'array' &&\n getType(options.value.stops[0]) === 'array' &&\n getType(options.value.stops[0][0]) === 'object';\n\n const errors = validateObject({\n key: options.key,\n value: options.value,\n valueSpec: options.styleSpec.function,\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {\n stops: validateFunctionStops,\n default: validateFunctionDefault\n }\n });\n\n if (functionType === 'identity' && isZoomFunction) {\n errors.push(new ValidationError(options.key, options.value, 'missing required property \"property\"'));\n }\n\n if (functionType !== 'identity' && !options.value.stops) {\n errors.push(new ValidationError(options.key, options.value, 'missing required property \"stops\"'));\n }\n\n if (functionType === 'exponential' && options.valueSpec.expression && !supportsInterpolation(options.valueSpec)) {\n errors.push(new ValidationError(options.key, options.value, 'exponential functions not supported'));\n }\n\n if (options.styleSpec.$version >= 8) {\n if (isPropertyFunction && !supportsPropertyExpression(options.valueSpec)) {\n errors.push(new ValidationError(options.key, options.value, 'property functions not supported'));\n } else if (isZoomFunction && !supportsZoomExpression(options.valueSpec)) {\n errors.push(new ValidationError(options.key, options.value, 'zoom functions not supported'));\n }\n }\n\n if ((functionType === 'categorical' || isZoomAndPropertyFunction) && options.value.property === undefined) {\n errors.push(new ValidationError(options.key, options.value, '\"property\" property is required'));\n }\n\n return errors;\n\n function validateFunctionStops(options: ValidationOptions) {\n if (functionType === 'identity') {\n return [new ValidationError(options.key, options.value, 'identity function may not have a \"stops\" property')];\n }\n\n let errors = [];\n const value = options.value;\n\n errors = errors.concat(validateArray({\n key: options.key,\n value,\n valueSpec: options.valueSpec,\n style: options.style,\n styleSpec: options.styleSpec,\n arrayElementValidator: validateFunctionStop\n }));\n\n if (getType(value) === 'array' && value.length === 0) {\n errors.push(new ValidationError(options.key, value, 'array must have at least one stop'));\n }\n\n return errors;\n }\n\n function validateFunctionStop(options: ValidationOptions) {\n let errors = [];\n const value = options.value;\n const key = options.key;\n\n if (getType(value) !== 'array') {\n return [new ValidationError(key, value, `array expected, ${getType(value)} found`)];\n }\n\n if (value.length !== 2) {\n return [new ValidationError(key, value, `array length 2 expected, length ${value.length} found`)];\n }\n\n if (isZoomAndPropertyFunction) {\n if (getType(value[0]) !== 'object') {\n return [new ValidationError(key, value, `object expected, ${getType(value[0])} found`)];\n }\n if (value[0].zoom === undefined) {\n return [new ValidationError(key, value, 'object stop key must have zoom')];\n }\n if (value[0].value === undefined) {\n return [new ValidationError(key, value, 'object stop key must have value')];\n }\n\n const nextStopDomainZoom = unbundle(value[0].zoom);\n if (typeof nextStopDomainZoom !== 'number') {\n return [new ValidationError(key, value[0].zoom, 'stop zoom values must be numbers')];\n }\n\n if (previousStopDomainZoom && previousStopDomainZoom > nextStopDomainZoom) {\n return [new ValidationError(key, value[0].zoom, 'stop zoom values must appear in ascending order')];\n }\n if (nextStopDomainZoom !== previousStopDomainZoom) {\n previousStopDomainZoom = nextStopDomainZoom;\n previousStopDomainValue = undefined;\n stopDomainValues = {};\n }\n errors = errors.concat(validateObject({\n key: `${key}[0]`,\n value: value[0],\n valueSpec: {zoom: {}},\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {zoom: validateNumber, value: validateStopDomainValue}\n }));\n } else {\n errors = errors.concat(validateStopDomainValue({\n key: `${key}[0]`,\n value: value[0],\n valueSpec: {},\n style: options.style,\n styleSpec: options.styleSpec\n }, value));\n }\n\n if (isExpression(deepUnbundle(value[1]))) {\n return errors.concat([new ValidationError(`${key}[1]`, value[1], 'expressions are not allowed in function stops.')]);\n }\n\n return errors.concat(validate({\n key: `${key}[1]`,\n value: value[1],\n valueSpec: functionValueSpec,\n style: options.style,\n styleSpec: options.styleSpec\n }));\n }\n\n function validateStopDomainValue(options: ValidationOptions, stop: any) {\n const type = getType(options.value);\n const value = unbundle(options.value);\n\n const reportValue = options.value !== null ? options.value : stop;\n\n if (!stopKeyType) {\n stopKeyType = type;\n } else if (type !== stopKeyType) {\n return [new ValidationError(options.key, reportValue, `${type} stop domain type must match previous stop domain type ${stopKeyType}`)];\n }\n\n if (type !== 'number' && type !== 'string' && type !== 'boolean' && typeof value !== 'number' && typeof value !== 'string' && typeof value !== 'boolean') {\n return [new ValidationError(options.key, reportValue, 'stop domain value must be a number, string, or boolean')];\n }\n\n if (type !== 'number' && functionType !== 'categorical') {\n let message = `number expected, ${type} found`;\n if (supportsPropertyExpression(functionValueSpec) && functionType === undefined) {\n message += '\\nIf you intended to use a categorical function, specify `\"type\": \"categorical\"`.';\n }\n return [new ValidationError(options.key, reportValue, message)];\n }\n\n if (functionType === 'categorical' && type === 'number' && (typeof value !== 'number' || !isFinite(value) || Math.floor(value) !== value)) {\n return [new ValidationError(options.key, reportValue, `integer expected, found ${String(value)}`)];\n }\n\n if (functionType !== 'categorical' && type === 'number' && typeof value === 'number' && typeof previousStopDomainValue === 'number' && previousStopDomainValue !== undefined && value < previousStopDomainValue) {\n return [new ValidationError(options.key, reportValue, 'stop domain values must appear in ascending order')];\n } else {\n previousStopDomainValue = value;\n }\n\n if (functionType === 'categorical' && (value: any) in stopDomainValues) {\n return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')];\n } else {\n stopDomainValues[(value: any)] = true;\n }\n\n return [];\n }\n\n function validateFunctionDefault(options: ValidationOptions) {\n return validate({\n key: options.key,\n value: options.value,\n valueSpec: functionValueSpec,\n style: options.style,\n styleSpec: options.styleSpec\n });\n }\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error.js';\n\nimport {createExpression, createPropertyExpression} from '../expression/index.js';\nimport {deepUnbundle} from '../util/unbundle_jsonlint.js';\nimport {isStateConstant, isGlobalPropertyConstant, isFeatureConstant} from '../expression/is_constant.js';\nimport CompoundExpression from '../expression/compound_expression.js';\n\nimport type {Expression} from '../expression/expression.js';\n\nexport default function validateExpression(options: any): Array<ValidationError> {\n const expression = (options.expressionContext === 'property' ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec);\n if (expression.result === 'error') {\n return expression.value.map((error) => {\n return new ValidationError(`${options.key}${error.key}`, options.value, error.message);\n });\n }\n\n const expressionObj = (expression.value: any).expression || (expression.value: any)._styleExpression.expression;\n\n if (options.expressionContext === 'property' && (options.propertyKey === 'text-font') &&\n !expressionObj.outputDefined()) {\n return [new ValidationError(options.key, options.value, `Invalid data expression for \"${options.propertyKey}\". Output values must be contained as literals within the expression.`)];\n }\n\n if (options.expressionContext === 'property' && options.propertyType === 'layout' &&\n (!isStateConstant(expressionObj))) {\n return [new ValidationError(options.key, options.value, '\"feature-state\" data expressions are not supported with layout properties.')];\n }\n\n if (options.expressionContext === 'filter') {\n return disallowedFilterParameters(expressionObj, options);\n }\n\n if (options.expressionContext && options.expressionContext.indexOf('cluster') === 0) {\n if (!isGlobalPropertyConstant(expressionObj, ['zoom', 'feature-state'])) {\n return [new ValidationError(options.key, options.value, '\"zoom\" and \"feature-state\" expressions are not supported with cluster properties.')];\n }\n if (options.expressionContext === 'cluster-initial' && !isFeatureConstant(expressionObj)) {\n return [new ValidationError(options.key, options.value, 'Feature data expressions are not supported with initial expression part of cluster properties.')];\n }\n }\n\n return [];\n}\n\nexport function disallowedFilterParameters(e: Expression, options: any): Array<ValidationError> {\n const disallowedParameters = new Set([\n 'zoom',\n 'feature-state',\n 'pitch',\n 'distance-from-center'\n ]);\n\n if (options.valueSpec && options.valueSpec.expression) {\n for (const param of options.valueSpec.expression.parameters) {\n disallowedParameters.delete(param);\n }\n }\n\n if (disallowedParameters.size === 0) {\n return [];\n }\n const errors = [];\n\n if (e instanceof CompoundExpression) {\n if (disallowedParameters.has(e.name)) {\n return [new ValidationError(options.key, options.value, `[\"${e.name}\"] expression is not supported in a filter for a ${options.object.type} layer with id: ${options.object.id}`)];\n }\n }\n e.eachChild((arg) => {\n errors.push(...disallowedFilterParameters(arg, options));\n });\n\n return errors;\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error.js';\nimport {unbundle} from '../util/unbundle_jsonlint.js';\n\nimport type {ValidationOptions} from './validate.js';\n\nexport default function validateEnum(options: ValidationOptions): Array<ValidationError> {\n const key = options.key;\n const value = options.value;\n const valueSpec = options.valueSpec;\n const errors = [];\n\n if (Array.isArray(valueSpec.values)) { // <=v7\n if (valueSpec.values.indexOf(unbundle(value)) === -1) {\n errors.push(new ValidationError(key, value, `expected one of [${valueSpec.values.join(', ')}], ${JSON.stringify(value)} found`));\n }\n } else { // >=v8\n if (Object.keys(valueSpec.values).indexOf(unbundle(value)) === -1) {\n errors.push(new ValidationError(key, value, `expected one of [${Object.keys(valueSpec.values).join(', ')}], ${JSON.stringify(value)} found`));\n }\n }\n return errors;\n}\n","// @flow\n\nimport {createExpression} from '../expression/index.js';\nimport {isFeatureConstant} from '../expression/is_constant.js';\nimport {deepUnbundle} from '../util/unbundle_jsonlint.js';\nimport latest from '../reference/latest.js';\nimport type {GlobalProperties, Feature} from '../expression/index.js';\nimport type {CanonicalTileID} from '../../source/tile_id.js';\nimport type Point from '@mapbox/point-geometry';\n\nexport type FeatureDistanceData = {bearing: [number, number], center: [number, number], scale: number};\nexport type FilterExpression = (globalProperties: GlobalProperties, feature: Feature, canonical?: CanonicalTileID, featureTileCoord?: Point, featureDistanceData?: FeatureDistanceData) => boolean;\nexport type FeatureFilter = {filter: FilterExpression, dynamicFilter?: FilterExpression, needGeometry: boolean, needFeature: boolean};\n\nexport default createFilter;\nexport {isExpressionFilter, isDynamicFilter, extractStaticFilter};\n\nfunction isExpressionFilter(filter: any): boolean {\n if (filter === true || filter === false) {\n return true;\n }\n\n if (!Array.isArray(filter) || filter.length === 0) {\n return false;\n }\n switch (filter[0]) {\n case 'has':\n return filter.length >= 2 && filter[1] !== '$id' && filter[1] !== '$type';\n\n case 'in':\n return filter.length >= 3 && (typeof filter[1] !== 'string' || Array.isArray(filter[2]));\n\n case '!in':\n case '!has':\n case 'none':\n return false;\n\n case '==':\n case '!=':\n case '>':\n case '>=':\n case '<':\n case '<=':\n return filter.length !== 3 || (Array.isArray(filter[1]) || Array.isArray(filter[2]));\n\n case 'any':\n case 'all':\n for (const f of filter.slice(1)) {\n if (!isExpressionFilter(f) && typeof f !== 'boolean') {\n return false;\n }\n }\n return true;\n\n default:\n return true;\n }\n}\n\n/**\n * Given a filter expressed as nested arrays, return a new function\n * that evaluates whether a given feature (with a .properties or .tags property)\n * passes its test.\n *\n * @private\n * @param {Array} filter mapbox gl filter\n * @param {string} layerType the type of the layer this filter will be applied to.\n * @returns {Function} filter-evaluating function\n */\nfunction createFilter(filter: any, layerType?: string = 'fill'): FeatureFilter {\n if (filter === null || filter === undefined) {\n return {filter: () => true, needGeometry: false, needFeature: false};\n }\n\n if (!isExpressionFilter(filter)) {\n // $FlowFixMe[incompatible-call]\n filter = convertFilter(filter);\n }\n const filterExp = ((filter: any): string[] | string | boolean);\n\n let staticFilter = true;\n try {\n staticFilter = extractStaticFilter(filterExp);\n } catch (e) {\n console.warn(\n`Failed to extract static filter. Filter will continue working, but at higher memory usage and slower framerate.\nThis is most likely a bug, please report this via https://github.com/mapbox/mapbox-gl-js/issues/new?assignees=&labels=&template=Bug_report.md\nand paste the contents of this message in the report.\nThank you!\nFilter Expression:\n${JSON.stringify(filterExp, null, 2)}\n `);\n }\n\n // Compile the static component of the filter\n const filterSpec = latest[`filter_${layerType}`];\n const compiledStaticFilter = createExpression(staticFilter, filterSpec);\n\n let filterFunc = null;\n if (compiledStaticFilter.result === 'error') {\n throw new Error(compiledStaticFilter.value.map(err => `${err.key}: ${err.message}`).join(', '));\n } else {\n filterFunc = (globalProperties: GlobalProperties, feature: Feature, canonical?: CanonicalTileID) => compiledStaticFilter.value.evaluate(globalProperties, feature, {}, canonical);\n }\n\n // If the static component is not equal to the entire filter then we have a dynamic component\n // Compile the dynamic component separately\n let dynamicFilterFunc = null;\n let needFeature = null;\n if (staticFilter !== filterExp) {\n const compiledDynamicFilter = createExpression(filterExp, filterSpec);\n\n if (compiledDynamicFilter.result === 'error') {\n throw new Error(compiledDynamicFilter.value.map(err => `${err.key}: ${err.message}`).join(', '));\n } else {\n dynamicFilterFunc = (globalProperties: GlobalProperties, feature: Feature, canonical?: CanonicalTileID, featureTileCoord?: Point, featureDistanceData?: FeatureDistanceData) => compiledDynamicFilter.value.evaluate(globalProperties, feature, {}, canonical, undefined, undefined, featureTileCoord, featureDistanceData);\n needFeature = !isFeatureConstant(compiledDynamicFilter.value.expression);\n }\n }\n\n filterFunc = ((filterFunc: any): FilterExpression);\n const needGeometry = geometryNeeded(staticFilter);\n\n return {\n filter: filterFunc,\n dynamicFilter: dynamicFilterFunc ? dynamicFilterFunc : undefined,\n needGeometry,\n needFeature: !!needFeature\n };\n}\n\nfunction extractStaticFilter(filter: any): any {\n if (!isDynamicFilter(filter)) {\n return filter;\n }\n\n // Shallow copy so we can replace expressions in-place\n let result = deepUnbundle(filter);\n\n // 1. Union branches\n unionDynamicBranches(result);\n\n // 2. Collapse dynamic conditions to `true`\n result = collapseDynamicBooleanExpressions(result);\n\n return result;\n}\n\nfunction collapseDynamicBooleanExpressions(expression: any): any {\n if (!Array.isArray(expression)) {\n return expression;\n }\n\n const collapsed = collapsedExpression(expression);\n if (collapsed === true) {\n return collapsed;\n } else {\n return collapsed.map((subExpression) => collapseDynamicBooleanExpressions(subExpression));\n }\n}\n\n/**\n * Traverses the expression and replaces all instances of branching on a\n * `dynamic` conditional (such as `['pitch']` or `['distance-from-center']`)\n * into an `any` expression.\n * This ensures that all possible outcomes of a `dynamic` branch are considered\n * when evaluating the expression upfront during filtering.\n *\n * @param {Array<any>} filter the filter expression mutated in-place.\n */\nfunction unionDynamicBranches(filter: any) {\n let isBranchingDynamically = false;\n const branches = [];\n\n if (filter[0] === 'case') {\n for (let i = 1; i < filter.length - 1; i += 2) {\n isBranchingDynamically = isBranchingDynamically || isDynamicFilter(filter[i]);\n branches.push(filter[i + 1]);\n }\n\n branches.push(filter[filter.length - 1]);\n } else if (filter[0] === 'match') {\n isBranchingDynamically = isBranchingDynamically || isDynamicFilter(filter[1]);\n\n for (let i = 2; i < filter.length - 1; i += 2) {\n branches.push(filter[i + 1]);\n }\n branches.push(filter[filter.length - 1]);\n } else if (filter[0] === 'step') {\n isBranchingDynamically = isBranchingDynamically || isDynamicFilter(filter[1]);\n\n for (let i = 1; i < filter.length - 1; i += 2) {\n branches.push(filter[i + 1]);\n }\n }\n\n if (isBranchingDynamically) {\n filter.length = 0;\n filter.push('any', ...branches);\n }\n\n // traverse and recurse into children\n for (let i = 1; i < filter.length; i++) {\n unionDynamicBranches(filter[i]);\n }\n}\n\nfunction isDynamicFilter(filter: any): boolean {\n // Base Cases\n if (!Array.isArray(filter)) {\n return false;\n }\n if (isRootExpressionDynamic(filter[0])) {\n return true;\n }\n\n for (let i = 1; i < filter.length; i++) {\n const child = filter[i];\n if (isDynamicFilter(child)) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction isRootExpressionDynamic(expression: string): boolean {\n return expression === 'pitch' ||\n expression === 'distance-from-center';\n}\n\nconst dynamicConditionExpressions = new Set([\n 'in',\n '==',\n '!=',\n '>',\n '>=',\n '<',\n '<=',\n 'to-boolean'\n]);\n\nfunction collapsedExpression(expression: any): any {\n if (dynamicConditionExpressions.has(expression[0])) {\n\n for (let i = 1; i < expression.length; i++) {\n const param = expression[i];\n if (isDynamicFilter(param)) {\n return true;\n }\n }\n }\n return expression;\n}\n\n// Comparison function to sort numbers and strings\nfunction compare(a: number, b: number) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction geometryNeeded(filter: Array<any> | boolean) {\n if (!Array.isArray(filter)) return false;\n if (filter[0] === 'within') return true;\n for (let index = 1; index < filter.length; index++) {\n if (geometryNeeded(filter[index])) return true;\n }\n return false;\n}\n\nfunction convertFilter(filter: ?Array<any>): mixed {\n if (!filter) return true;\n const op = filter[0];\n if (filter.length <= 1) return (op !== 'any');\n const converted =\n op === '==' ? convertComparisonOp(filter[1], filter[2], '==') :\n op === '!=' ? convertNegation(convertComparisonOp(filter[1], filter[2], '==')) :\n op === '<' ||\n op === '>' ||\n op === '<=' ||\n op === '>=' ? convertComparisonOp(filter[1], filter[2], op) :\n op === 'any' ? convertDisjunctionOp(filter.slice(1)) :\n op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter)) :\n op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter).map(convertNegation)) :\n op === 'in' ? convertInOp(filter[1], filter.slice(2)) :\n op === '!in' ? convertNegation(convertInOp(filter[1], filter.slice(2))) :\n op === 'has' ? convertHasOp(filter[1]) :\n op === '!has' ? convertNegation(convertHasOp(filter[1])) :\n op === 'within' ? filter :\n true;\n return converted;\n}\n\nfunction convertComparisonOp(property: string, value: any, op: string) {\n switch (property) {\n case '$type':\n return [`filter-type-${op}`, value];\n case '$id':\n return [`filter-id-${op}`, value];\n default:\n return [`filter-${op}`, property, value];\n }\n}\n\nfunction convertDisjunctionOp(filters: Array<Array<any>>) {\n return ['any'].concat(filters.map(convertFilter));\n}\n\nfunction convertInOp(property: string, values: Array<any>) {\n if (values.length === 0) { return false; }\n switch (property) {\n case '$type':\n return [`filter-type-in`, ['literal', values]];\n case '$id':\n return [`filter-id-in`, ['literal', values]];\n default:\n if (values.length > 200 && !values.some(v => typeof v !== typeof values[0])) {\n return ['filter-in-large', property, ['literal', values.sort(compare)]];\n } else {\n return ['filter-in-small', property, ['literal', values]];\n }\n }\n}\n\nfunction convertHasOp(property: string) {\n switch (property) {\n case '$type':\n return true;\n case '$id':\n return [`filter-has-id`];\n default:\n return [`filter-has`, property];\n }\n}\n\nfunction convertNegation(filter: mixed) {\n return ['!', filter];\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error.js';\nimport validateExpression from './validate_expression.js';\nimport validateEnum from './validate_enum.js';\nimport getType from '../util/get_type.js';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint.js';\nimport extend from '../util/extend.js';\nimport {isExpressionFilter} from '../feature_filter/index.js';\n\nimport type {ValidationOptions} from './validate.js';\n\ntype Options = ValidationOptions & {\n layerType?: string;\n}\n\nexport default function validateFilter(options: Options): Array<ValidationError> {\n if (isExpressionFilter(deepUnbundle(options.value))) {\n // We default to a layerType of `fill` because that points to a non-dynamic filter definition within the style-spec.\n const layerType = options.layerType || 'fill';\n\n return validateExpression(extend({}, options, {\n expressionContext: 'filter',\n valueSpec: options.styleSpec[`filter_${layerType}`]\n }));\n } else {\n return validateNonExpressionFilter(options);\n }\n}\n\nfunction validateNonExpressionFilter(options: Options) {\n const value = options.value;\n const key = options.key;\n\n if (getType(value) !== 'array') {\n return [new ValidationError(key, value, `array expected, ${getType(value)} found`)];\n }\n\n const styleSpec = options.styleSpec;\n let type;\n\n let errors = [];\n\n if (value.length < 1) {\n return [new ValidationError(key, value, 'filter array must have at least 1 element')];\n }\n\n errors = errors.concat(validateEnum({\n key: `${key}[0]`,\n value: value[0],\n valueSpec: styleSpec.filter_operator,\n style: options.style,\n styleSpec: options.styleSpec\n }));\n\n switch (unbundle(value[0])) {\n case '<':\n case '<=':\n case '>':\n case '>=':\n if (value.length >= 2 && unbundle(value[1]) === '$type') {\n errors.push(new ValidationError(key, value, `\"$type\" cannot be use with operator \"${value[0]}\"`));\n }\n /* falls through */\n case '==':\n case '!=':\n if (value.length !== 3) {\n errors.push(new ValidationError(key, value, `filter array for operator \"${value[0]}\" must have 3 elements`));\n }\n /* falls through */\n case 'in':\n case '!in':\n if (value.length >= 2) {\n type = getType(value[1]);\n if (type !== 'string') {\n errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`));\n }\n }\n for (let i = 2; i < value.length; i++) {\n type = getType(value[i]);\n if (unbundle(value[1]) === '$type') {\n errors = errors.concat(validateEnum({\n key: `${key}[${i}]`,\n value: value[i],\n valueSpec: styleSpec.geometry_type,\n style: options.style,\n styleSpec: options.styleSpec\n }));\n } else if (type !== 'string' && type !== 'number' && type !== 'boolean') {\n errors.push(new ValidationError(`${key}[${i}]`, value[i], `string, number, or boolean expected, ${type} found`));\n }\n }\n break;\n\n case 'any':\n case 'all':\n case 'none':\n for (let i = 1; i < value.length; i++) {\n errors = errors.concat(validateNonExpressionFilter(({\n key: `${key}[${i}]`,\n value: value[i],\n style: options.style,\n styleSpec: options.styleSpec\n }: any)));\n }\n break;\n\n case 'has':\n case '!has':\n type = getType(value[1]);\n if (value.length !== 2) {\n errors.push(new ValidationError(key, value, `filter array for \"${value[0]}\" operator must have 2 elements`));\n } else if (type !== 'string') {\n errors.push(new ValidationError(`${key}[1]`, value[1], `string expected, ${type} found`));\n }\n break;\n case 'within':\n type = getType(value[1]);\n if (value.length !== 2) {\n errors.push(new ValidationError(key, value, `filter array for \"${value[0]}\" operator must have 2 elements`));\n } else if (type !== 'object') {\n errors.push(new ValidationError(`${key}[1]`, value[1], `object expected, ${type} found`));\n }\n break;\n }\n return errors;\n}\n","// @flow\n\nimport validate from './validate.js';\nimport ValidationError from '../error/validation_error.js';\nimport getType from '../util/get_type.js';\nimport {isFunction} from '../function/index.js';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint.js';\nimport {supportsPropertyExpression} from '../util/properties.js';\n\nimport type {ValidationOptions} from './validate.js';\n\nexport type PropertyValidationOptions = ValidationOptions & {\n objectKey: string;\n layerType: string;\n}\n\nexport default function validateProperty(options: PropertyValidationOptions, propertyType: string): Array<ValidationError> {\n const key = options.key;\n const style = options.style;\n const styleSpec = options.styleSpec;\n const value = options.value;\n const propertyKey = options.objectKey;\n const layerSpec = styleSpec[`${propertyType}_${options.layerType}`];\n\n if (!layerSpec) return [];\n\n const transitionMatch = propertyKey.match(/^(.*)-transition$/);\n if (propertyType === 'paint' && transitionMatch && layerSpec[transitionMatch[1]] && layerSpec[transitionMatch[1]].transition) {\n return validate({\n key,\n value,\n valueSpec: styleSpec.transition,\n style,\n styleSpec\n });\n }\n\n const valueSpec = options.valueSpec || layerSpec[propertyKey];\n if (!valueSpec) {\n return [new ValidationError(key, value, `unknown property \"${propertyKey}\"`)];\n }\n\n let tokenMatch: ?RegExp$matchResult;\n if (getType(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) {\n const example = `\\`{ \"type\": \"identity\", \"property\": ${tokenMatch ? JSON.stringify(tokenMatch[1]) : '\"_\"'} }\\``;\n return [new ValidationError(\n key, value,\n `\"${propertyKey}\" does not support interpolation syntax\\n` +\n `Use an identity property function instead: ${example}.`)];\n }\n\n const errors = [];\n\n if (options.layerType === 'symbol') {\n if (propertyKey === 'text-field' && style && !style.glyphs) {\n errors.push(new ValidationError(key, value, 'use of \"text-field\" requires a style \"glyphs\" property'));\n }\n if (propertyKey === 'text-font' && isFunction(deepUnbundle(value)) && unbundle(value.type) === 'identity') {\n errors.push(new ValidationError(key, value, '\"text-font\" does not support identity functions'));\n }\n }\n\n return errors.concat(validate({\n key: options.key,\n value,\n valueSpec,\n style,\n styleSpec,\n expressionContext: 'property',\n propertyType,\n propertyKey\n }));\n}\n","// @flow\n\nimport validateProperty from './validate_property.js';\n\nimport type ValidationError from '../error/validation_error.js';\nimport type {PropertyValidationOptions} from './validate_property.js';\n\nexport default function validatePaintProperty(options: PropertyValidationOptions): Array<ValidationError> {\n return validateProperty(options, 'paint');\n}\n","// @flow\n\nimport validateProperty from './validate_property.js';\n\nimport type ValidationError from '../error/validation_error.js';\nimport type {PropertyValidationOptions} from './validate_property.js';\n\nexport default function validateLayoutProperty(options: PropertyValidationOptions): Array<ValidationError> {\n return validateProperty(options, 'layout');\n}\n","// @flow\n\nimport getType from '../util/get_type.js';\nimport ValidationError from '../error/validation_error.js';\n\nimport type {ValidationOptions} from './validate.js';\n\nexport default function validateString(options: $Shape<ValidationOptions>): Array<ValidationError> {\n const value = options.value;\n const key = options.key;\n const type = getType(value);\n\n if (type !== 'string') {\n return [new ValidationError(key, value, `string expected, ${type} found`)];\n }\n\n return [];\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error.js';\nimport {unbundle} from '../util/unbundle_jsonlint.js';\nimport validateObject from './validate_object.js';\nimport validateEnum from './validate_enum.js';\nimport validateExpression from './validate_expression.js';\nimport validateString from './validate_string.js';\nimport getType from '../util/get_type.js';\n\nimport type {StyleReference} from '../reference/latest.js';\nimport type {ValidationOptions} from './validate.js';\n\nconst objectElementValidators = {\n promoteId: validatePromoteId\n};\n\nexport default function validateSource(options: ValidationOptions): Array<ValidationError> {\n const value = options.value;\n const key = options.key;\n const styleSpec = options.styleSpec;\n const style = options.style;\n\n if (!value.type) {\n return [new ValidationError(key, value, '\"type\" is required')];\n }\n\n const type = unbundle(value.type);\n let errors;\n\n switch (type) {\n case 'vector':\n case 'raster':\n case 'raster-dem':\n errors = validateObject({\n key,\n value,\n valueSpec: styleSpec[`source_${type.replace('-', '_')}`],\n style: options.style,\n styleSpec,\n objectElementValidators\n });\n return errors;\n\n case 'geojson':\n errors = validateObject({\n key,\n value,\n valueSpec: styleSpec.source_geojson,\n style,\n styleSpec,\n objectElementValidators\n });\n if (value.cluster) {\n for (const prop in value.clusterProperties) {\n const [operator, mapExpr] = value.clusterProperties[prop];\n const reduceExpr = typeof operator === 'string' ? [operator, ['accumulated'], ['get', prop]] : operator;\n\n errors.push(...validateExpression({\n key: `${key}.${prop}.map`,\n value: mapExpr,\n expressionContext: 'cluster-map'\n }));\n errors.push(...validateExpression({\n key: `${key}.${prop}.reduce`,\n value: reduceExpr,\n expressionContext: 'cluster-reduce'\n }));\n }\n }\n return errors;\n\n case 'video':\n return validateObject({\n key,\n value,\n valueSpec: styleSpec.source_video,\n style,\n styleSpec\n });\n\n case 'image':\n return validateObject({\n key,\n value,\n valueSpec: styleSpec.source_image,\n style,\n styleSpec\n });\n\n case 'canvas':\n return [new ValidationError(key, null, `Please use runtime APIs to add canvas sources, rather than including them in stylesheets.`, 'source.canvas')];\n\n default:\n return validateEnum({\n key: `${key}.type`,\n value: value.type,\n valueSpec: {values: getSourceTypeValues(styleSpec)},\n style,\n styleSpec\n });\n }\n}\n\nfunction getSourceTypeValues(styleSpec: StyleReference) {\n return styleSpec.source.reduce((memo, source) => {\n const sourceType = styleSpec[source];\n if (sourceType.type.type === 'enum') {\n memo = memo.concat(Object.keys(sourceType.type.values));\n }\n return memo;\n }, []);\n}\n\nfunction validatePromoteId({key, value}: $Shape<ValidationOptions>) {\n if (getType(value) === 'string') {\n return validateString({key, value});\n } else {\n const errors = [];\n for (const prop in value) {\n errors.push(...validateString({key: `${key}.${prop}`, value: value[prop]}));\n }\n return errors;\n }\n}\n","// @flow\n\nimport extend from '../util/extend.js';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint.js';\nimport {isExpression} from '../expression/index.js';\nimport {isFunction} from '../function/index.js';\n\nimport validateFunction from './validate_function.js';\nimport validateExpression from './validate_expression.js';\nimport validateObject from './validate_object.js';\nimport validateArray from './validate_array.js';\nimport validateBoolean from './validate_boolean.js';\nimport validateNumber from './validate_number.js';\nimport validateColor from './validate_color.js';\nimport validateEnum from './validate_enum.js';\nimport validateFilter from './validate_filter.js';\nimport validateLayer from './validate_layer.js';\nimport validateSource from './validate_source.js';\nimport validateLight from './validate_light.js';\nimport validateTerrain from './validate_terrain.js';\nimport validateFog from './validate_fog.js';\nimport validateString from './validate_string.js';\nimport validateFormatted from './validate_formatted.js';\nimport validateImage from './validate_image.js';\nimport validateProjection from './validate_projection.js';\n\nimport type {StyleReference} from '../reference/latest.js';\nimport type {StyleSpecification} from '../types.js';\nimport type ValidationError from '../error/validation_error.js';\n\nconst VALIDATORS = {\n '*'() {\n return [];\n },\n 'array': validateArray,\n 'boolean': validateBoolean,\n 'number': validateNumber,\n 'color': validateColor,\n 'enum': validateEnum,\n 'filter': validateFilter,\n 'function': validateFunction,\n 'layer': validateLayer,\n 'object': validateObject,\n 'source': validateSource,\n 'light': validateLight,\n 'terrain': validateTerrain,\n 'fog': validateFog,\n 'string': validateString,\n 'formatted': validateFormatted,\n 'resolvedImage': validateImage,\n 'projection': validateProjection\n};\n\n// Main recursive validation function. Tracks:\n//\n// - key: string representing location of validation in style tree. Used only\n// for more informative error reporting.\n// - value: current value from style being evaluated. May be anything from a\n// high level object that needs to be descended into deeper or a simple\n// scalar value.\n// - valueSpec: current spec being evaluated. Tracks value.\n// - styleSpec: current full spec being evaluated.\nexport type ValidationOptions = {\n key: string;\n value: Object;\n valueSpec: Object;\n style: $Shape<StyleSpecification>;\n styleSpec: StyleReference;\n}\n\nexport default function validate(options: ValidationOptions): Array<ValidationError> {\n const value = options.value;\n const valueSpec = options.valueSpec;\n const styleSpec = options.styleSpec;\n\n if (valueSpec.expression && isFunction(unbundle(value))) {\n return validateFunction(options);\n\n } else if (valueSpec.expression && isExpression(deepUnbundle(value))) {\n return validateExpression(options);\n\n } else if (valueSpec.type && VALIDATORS[valueSpec.type]) {\n return VALIDATORS[valueSpec.type](options);\n\n } else {\n const valid = validateObject(extend({}, options, {\n valueSpec: valueSpec.type ? styleSpec[valueSpec.type] : valueSpec\n }));\n return valid;\n }\n}\n","// @flow\n\nimport getType from '../util/get_type.js';\nimport ValidationError from '../error/validation_error.js';\n\nimport type {ValidationOptions} from './validate.js';\n\nexport default function validateBoolean(options: ValidationOptions): Array<ValidationError> {\n const value = options.value;\n const key = options.key;\n const type = getType(value);\n\n if (type !== 'boolean') {\n return [new ValidationError(key, value, `boolean expected, ${type} found`)];\n }\n\n return [];\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error.js';\nimport getType from '../util/get_type.js';\nimport {parseCSSColor} from 'csscolorparser';\n\nimport type {ValidationOptions} from './validate.js';\n\nexport default function validateColor(options: ValidationOptions): Array<ValidationError> {\n const key = options.key;\n const value = options.value;\n const type = getType(value);\n\n if (type !== 'string') {\n return [new ValidationError(key, value, `color expected, ${type} found`)];\n }\n\n if (parseCSSColor(value) === null) {\n return [new ValidationError(key, value, `color expected, \"${value}\" found`)];\n }\n\n return [];\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error.js';\nimport {unbundle} from '../util/unbundle_jsonlint.js';\nimport validateObject from './validate_object.js';\nimport validateFilter from './validate_filter.js';\nimport validatePaintProperty from './validate_paint_property.js';\nimport validateLayoutProperty from './validate_layout_property.js';\nimport validateSpec from './validate.js';\nimport extend from '../util/extend.js';\n\nimport type {ValidationOptions} from './validate.js';\nimport type {LayerSpecification} from '../types.js';\n\ntype Options = ValidationOptions & {\n value: LayerSpecification;\n arrayIndex: number;\n}\n\nexport default function validateLayer(options: Options): Array<ValidationError> {\n let errors = [];\n\n const layer = options.value;\n const key = options.key;\n const style = options.style;\n const styleSpec = options.styleSpec;\n\n if (!layer.type && !layer.ref) {\n errors.push(new ValidationError(key, layer, 'either \"type\" or \"ref\" is required'));\n }\n let type = unbundle(layer.type);\n const ref = unbundle(layer.ref);\n\n if (layer.id) {\n const layerId = unbundle(layer.id);\n for (let i = 0; i < options.arrayIndex; i++) {\n const otherLayer = style.layers[i];\n if (unbundle(otherLayer.id) === layerId) {\n // $FlowFixMe[prop-missing] - id.__line__ is added dynamically during the readStyle step\n errors.push(new ValidationError(key, layer.id, `duplicate layer id \"${layer.id}\", previously used at line ${otherLayer.id.__line__}`));\n }\n }\n }\n\n if ('ref' in layer) {\n ['type', 'source', 'source-layer', 'filter', 'layout'].forEach((p) => {\n if (p in layer) {\n errors.push(new ValidationError(key, layer[p], `\"${p}\" is prohibited for ref layers`));\n }\n });\n\n let parent;\n\n style.layers.forEach((layer) => {\n if (unbundle(layer.id) === ref) parent = layer;\n });\n\n if (!parent) {\n if (typeof ref === 'string')\n errors.push(new ValidationError(key, layer.ref, `ref layer \"${ref}\" not found`));\n // $FlowFixMe[prop-missing] - ref is not defined on the LayerSpecification subtypes\n } else if (parent.ref) {\n errors.push(new ValidationError(key, layer.ref, 'ref cannot reference another ref layer'));\n } else {\n type = unbundle(parent.type);\n }\n } else if (!(type === 'background' || type === 'sky')) {\n if (!layer.source) {\n errors.push(new ValidationError(key, layer, 'missing required property \"source\"'));\n } else {\n const source = style.sources && style.sources[layer.source];\n const sourceType = source && unbundle(source.type);\n if (!source) {\n errors.push(new ValidationError(key, layer.source, `source \"${layer.source}\" not found`));\n } else if (sourceType === 'vector' && type === 'raster') {\n errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a raster source`));\n } else if (sourceType === 'raster' && type !== 'raster') {\n errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a vector source`));\n } else if (sourceType === 'vector' && !layer['source-layer']) {\n errors.push(new ValidationError(key, layer, `layer \"${layer.id}\" must specify a \"source-layer\"`));\n } else if (sourceType === 'raster-dem' && type !== 'hillshade') {\n errors.push(new ValidationError(key, layer.source, 'raster-dem source can only be used with layer type \\'hillshade\\'.'));\n } else if (type === 'line' && layer.paint && (layer.paint['line-gradient'] || layer.paint['line-trim-offset']) &&\n (sourceType !== 'geojson' || !source.lineMetrics)) {\n errors.push(new ValidationError(key, layer, `layer \"${layer.id}\" specifies a line-gradient, which requires a GeoJSON source with \\`lineMetrics\\` enabled.`));\n }\n }\n }\n\n errors = errors.concat(validateObject({\n key,\n value: layer,\n valueSpec: styleSpec.layer,\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {\n '*'() {\n return [];\n },\n // We don't want to enforce the spec's `\"requires\": true` for backward compatibility with refs;\n // the actual requirement is validated above. See https://github.com/mapbox/mapbox-gl-js/issues/5772.\n type() {\n return validateSpec({\n key: `${key}.type`,\n value: layer.type,\n valueSpec: styleSpec.layer.type,\n style: options.style,\n styleSpec: options.styleSpec,\n object: layer,\n objectKey: 'type'\n });\n },\n filter(options) {\n return validateFilter(extend({layerType: type}, options));\n },\n layout(options) {\n return validateObject({\n layer,\n key: options.key,\n value: options.value,\n valueSpec: {},\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {\n '*'(options) {\n return validateLayoutProperty(extend({layerType: type}, options));\n }\n }\n });\n },\n paint(options) {\n return validateObject({\n layer,\n key: options.key,\n value: options.value,\n valueSpec: {},\n style: options.style,\n styleSpec: options.styleSpec,\n objectElementValidators: {\n '*'(options) {\n return validatePaintProperty(extend({layerType: type}, options));\n }\n }\n });\n }\n }\n }));\n\n return errors;\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error.js';\nimport getType from '../util/get_type.js';\nimport validate from './validate.js';\n\nimport type {ValidationOptions} from './validate.js';\n\nexport default function validateLight(options: ValidationOptions): Array<ValidationError> {\n const light = options.value;\n const styleSpec = options.styleSpec;\n const lightSpec = styleSpec.light;\n const style = options.style;\n\n let errors = [];\n\n const rootType = getType(light);\n if (light === undefined) {\n return errors;\n } else if (rootType !== 'object') {\n errors = errors.concat([new ValidationError('light', light, `object expected, ${rootType} found`)]);\n return errors;\n }\n\n for (const key in light) {\n const transitionMatch = key.match(/^(.*)-transition$/);\n\n if (transitionMatch && lightSpec[transitionMatch[1]] && lightSpec[transitionMatch[1]].transition) {\n errors = errors.concat(validate({\n key,\n value: light[key],\n valueSpec: styleSpec.transition,\n style,\n styleSpec\n }));\n } else if (lightSpec[key]) {\n errors = errors.concat(validate({\n key,\n value: light[key],\n valueSpec: lightSpec[key],\n style,\n styleSpec\n }));\n } else {\n errors = errors.concat([new ValidationError(key, light[key], `unknown property \"${key}\"`)]);\n }\n }\n\n return errors;\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error.js';\nimport validate from './validate.js';\nimport getType from '../util/get_type.js';\nimport {unbundle} from '../util/unbundle_jsonlint.js';\n\nimport type {ValidationOptions} from './validate.js';\n\nexport default function validateTerrain(options: ValidationOptions): Array<ValidationError> {\n const terrain = options.value;\n const key = options.key;\n const style = options.style;\n const styleSpec = options.styleSpec;\n const terrainSpec = styleSpec.terrain;\n let errors = [];\n\n const rootType = getType(terrain);\n if (terrain === undefined) {\n return errors;\n } else if (rootType !== 'object') {\n errors = errors.concat([new ValidationError('terrain', terrain, `object expected, ${rootType} found`)]);\n return errors;\n }\n\n for (const key in terrain) {\n const transitionMatch = key.match(/^(.*)-transition$/);\n\n if (transitionMatch && terrainSpec[transitionMatch[1]] && terrainSpec[transitionMatch[1]].transition) {\n errors = errors.concat(validate({\n key,\n value: terrain[key],\n valueSpec: styleSpec.transition,\n style,\n styleSpec\n }));\n } else if (terrainSpec[key]) {\n errors = errors.concat(validate({\n key,\n value: terrain[key],\n valueSpec: terrainSpec[key],\n style,\n styleSpec\n }));\n } else {\n errors = errors.concat([new ValidationError(key, terrain[key], `unknown property \"${key}\"`)]);\n }\n }\n\n if (!terrain.source) {\n errors.push(new ValidationError(key, terrain, `terrain is missing required property \"source\"`));\n } else {\n const source = style.sources && style.sources[terrain.source];\n const sourceType = source && unbundle(source.type);\n if (!source) {\n errors.push(new ValidationError(key, terrain.source, `source \"${terrain.source}\" not found`));\n } else if (sourceType !== 'raster-dem') {\n errors.push(new ValidationError(key, terrain.source, `terrain cannot be used with a source of type ${String(sourceType)}, it only be used with a \"raster-dem\" source type`));\n }\n }\n\n return errors;\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error.js';\nimport validate from './validate.js';\nimport getType from '../util/get_type.js';\n\nimport type {ValidationOptions} from './validate.js';\n\nexport default function validateFog(options: ValidationOptions): Array<ValidationError> {\n const fog = options.value;\n const style = options.style;\n const styleSpec = options.styleSpec;\n const fogSpec = styleSpec.fog;\n let errors = [];\n\n const rootType = getType(fog);\n if (fog === undefined) {\n return errors;\n } else if (rootType !== 'object') {\n errors = errors.concat([new ValidationError('fog', fog, `object expected, ${rootType} found`)]);\n return errors;\n }\n\n for (const key in fog) {\n const transitionMatch = key.match(/^(.*)-transition$/);\n\n if (transitionMatch && fogSpec[transitionMatch[1]] && fogSpec[transitionMatch[1]].transition) {\n errors = errors.concat(validate({\n key,\n value: fog[key],\n valueSpec: styleSpec.transition,\n style,\n styleSpec\n }));\n } else if (fogSpec[key]) {\n errors = errors.concat(validate({\n key,\n value: fog[key],\n valueSpec: fogSpec[key],\n style,\n styleSpec\n }));\n } else {\n errors = errors.concat([new ValidationError(key, fog[key], `unknown property \"${key}\"`)]);\n }\n }\n\n return errors;\n}\n","// @flow\n\nimport validateExpression from './validate_expression.js';\nimport validateString from './validate_string.js';\n\nimport type {ValidationOptions} from './validate.js';\nimport type ValidationError from '../error/validation_error.js';\n\nexport default function validateFormatted(options: ValidationOptions): Array<ValidationError> {\n if (validateString(options).length === 0) {\n return [];\n }\n\n return validateExpression(options);\n}\n","// @flow\n\nimport validateExpression from './validate_expression.js';\nimport validateString from './validate_string.js';\n\nimport type {ValidationOptions} from './validate.js';\nimport type ValidationError from '../error/validation_error.js';\n\nexport default function validateImage(options: ValidationOptions): Array<ValidationError> {\n if (validateString(options).length === 0) {\n return [];\n }\n\n return validateExpression(options);\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error.js';\nimport getType from '../util/get_type.js';\nimport validate from './validate.js';\n\nimport type {ValidationOptions} from './validate.js';\n\nexport default function validateProjection(options: ValidationOptions): Array<ValidationError> {\n const projection = options.value;\n const styleSpec = options.styleSpec;\n const projectionSpec = styleSpec.projection;\n const style = options.style;\n\n let errors = [];\n\n const rootType = getType(projection);\n\n if (rootType === 'object') {\n for (const key in projection) {\n errors = errors.concat(validate({\n key,\n value: projection[key],\n valueSpec: projectionSpec[key],\n style,\n styleSpec\n }));\n }\n } else if (rootType !== 'string') {\n errors = errors.concat([new ValidationError('projection', projection, `object or string expected, ${rootType} found`)]);\n }\n\n return errors;\n}\n","// @flow\n\nimport ValidationError from '../error/validation_error.js';\nimport validateString from './validate_string.js';\n\nimport type {ValidationOptions} from './validate.js';\n\nexport default function(options: ValidationOptions): Array<ValidationError> {\n const value = options.value;\n const key = options.key;\n\n const errors = validateString(options);\n if (errors.length) return errors;\n\n if (value.indexOf('{fontstack}') === -1) {\n errors.push(new ValidationError(key, value, '\"glyphs\" url must include a \"{fontstack}\" token'));\n }\n\n if (value.indexOf('{range}') === -1) {\n errors.push(new ValidationError(key, value, '\"glyphs\" url must include a \"{range}\" token'));\n }\n\n return errors;\n}\n","// @flow\nimport validate from './validate/validate.js';\nimport latestStyleSpec from './reference/latest.js';\nimport validateGlyphsURL from './validate/validate_glyphs_url.js';\n\nimport _validateSource from './validate/validate_source.js';\nimport _validateLight from './validate/validate_light.js';\nimport _validateTerrain from './validate/validate_terrain.js';\nimport _validateFog from './validate/validate_fog.js';\nimport _validateLayer from './validate/validate_layer.js';\nimport _validateFilter from './validate/validate_filter.js';\nimport _validatePaintProperty from './validate/validate_paint_property.js';\nimport _validateLayoutProperty from './validate/validate_layout_property.js';\n\nimport type {StyleSpecification} from './types.js';\n\nexport type ValidationError = interface {\n message: string,\n identifier?: ?string,\n line?: ?number,\n};\nexport type ValidationErrors = $ReadOnlyArray<ValidationError>;\nexport type Validator = (Object) => ValidationErrors;\n\n/**\n * Validate a Mapbox GL style against the style specification. This entrypoint,\n * `mapbox-gl-style-spec/lib/validate_style.min`, is designed to produce as\n * small a browserify bundle as possible by omitting unnecessary functionality\n * and legacy style specifications.\n *\n * @private\n * @param {Object} style The style to be validated.\n * @param {Object} [styleSpec] The style specification to validate against.\n * If omitted, the latest style spec is used.\n * @returns {Array<ValidationError>}\n * @example\n * var validate = require('mapbox-gl-style-spec/lib/validate_style.min');\n * var errors = validate(style);\n */\nexport function validateStyle(style: StyleSpecification, styleSpec: Object = latestStyleSpec): ValidationErrors {\n\n const errors = validate({\n key: '',\n value: style,\n valueSpec: styleSpec.$root,\n styleSpec,\n style,\n objectElementValidators: {\n glyphs: validateGlyphsURL,\n '*': () => []\n }\n });\n return sortErrors(errors);\n}\n\nexport const validateSource: Validator = opts => sortErrors(_validateSource(opts));\nexport const validateLight: Validator = opts => sortErrors(_validateLight(opts));\nexport const validateTerrain: Validator = opts => sortErrors(_validateTerrain(opts));\nexport const validateFog: Validator = opts => sortErrors(_validateFog(opts));\nexport const validateLayer: Validator = opts => sortErrors(_validateLayer(opts));\nexport const validateFilter: Validator = opts => sortErrors(_validateFilter(opts));\nexport const validatePaintProperty: Validator = opts => sortErrors(_validatePaintProperty(opts));\nexport const validateLayoutProperty: Validator = opts => sortErrors(_validateLayoutProperty(opts));\n\nfunction sortErrors(errors: ValidationErrors) {\n return errors.slice().sort((a, b) => a.line && b.line ? a.line - b.line : 0);\n}\n","// @flow\n\n// The following table comes from <http://www.unicode.org/Public/12.0.0/ucd/Blocks.txt>.\n// Keep it synchronized with <http://www.unicode.org/Public/UCD/latest/ucd/Blocks.txt>.\n\ntype UnicodeBlockLookup = {[key: string]: (char: number) => boolean};\n\nconst unicodeBlockLookup: UnicodeBlockLookup = {\n // 'Basic Latin': (char) => char >= 0x0000 && char <= 0x007F,\n 'Latin-1 Supplement': (char) => char >= 0x0080 && char <= 0x00FF,\n // 'Latin Extended-A': (char) => char >= 0x0100 && char <= 0x017F,\n // 'Latin Extended-B': (char) => char >= 0x0180 && char <= 0x024F,\n // 'IPA Extensions': (char) => char >= 0x0250 && char <= 0x02AF,\n // 'Spacing Modifier Letters': (char) => char >= 0x02B0 && char <= 0x02FF,\n // 'Combining Diacritical Marks': (char) => char >= 0x0300 && char <= 0x036F,\n // 'Greek and Coptic': (char) => char >= 0x0370 && char <= 0x03FF,\n // 'Cyrillic': (char) => char >= 0x0400 && char <= 0x04FF,\n // 'Cyrillic Supplement': (char) => char >= 0x0500 && char <= 0x052F,\n // 'Armenian': (char) => char >= 0x0530 && char <= 0x058F,\n //'Hebrew': (char) => char >= 0x0590 && char <= 0x05FF,\n 'Arabic': (char) => char >= 0x0600 && char <= 0x06FF,\n //'Syriac': (char) => char >= 0x0700 && char <= 0x074F,\n 'Arabic Supplement': (char) => char >= 0x0750 && char <= 0x077F,\n // 'Thaana': (char) => char >= 0x0780 && char <= 0x07BF,\n // 'NKo': (char) => char >= 0x07C0 && char <= 0x07FF,\n // 'Samaritan': (char) => char >= 0x0800 && char <= 0x083F,\n // 'Mandaic': (char) => char >= 0x0840 && char <= 0x085F,\n // 'Syriac Supplement': (char) => char >= 0x0860 && char <= 0x086F,\n 'Arabic Extended-A': (char) => char >= 0x08A0 && char <= 0x08FF,\n // 'Devanagari': (char) => char >= 0x0900 && char <= 0x097F,\n // 'Bengali': (char) => char >= 0x0980 && char <= 0x09FF,\n // 'Gurmukhi': (char) => char >= 0x0A00 && char <= 0x0A7F,\n // 'Gujarati': (char) => char >= 0x0A80 && char <= 0x0AFF,\n // 'Oriya': (char) => char >= 0x0B00 && char <= 0x0B7F,\n // 'Tamil': (char) => char >= 0x0B80 && char <= 0x0BFF,\n // 'Telugu': (char) => char >= 0x0C00 && char <= 0x0C7F,\n // 'Kannada': (char) => char >= 0x0C80 && char <= 0x0CFF,\n // 'Malayalam': (char) => char >= 0x0D00 && char <= 0x0D7F,\n // 'Sinhala': (char) => char >= 0x0D80 && char <= 0x0DFF,\n // 'Thai': (char) => char >= 0x0E00 && char <= 0x0E7F,\n // 'Lao': (char) => char >= 0x0E80 && char <= 0x0EFF,\n // 'Tibetan': (char) => char >= 0x0F00 && char <= 0x0FFF,\n // 'Myanmar': (char) => char >= 0x1000 && char <= 0x109F,\n // 'Georgian': (char) => char >= 0x10A0 && char <= 0x10FF,\n 'Hangul Jamo': (char) => char >= 0x1100 && char <= 0x11FF,\n // 'Ethiopic': (char) => char >= 0x1200 && char <= 0x137F,\n // 'Ethiopic Supplement': (char) => char >= 0x1380 && char <= 0x139F,\n // 'Cherokee': (char) => char >= 0x13A0 && char <= 0x13FF,\n 'Unified Canadian Aboriginal Syllabics': (char) => char >= 0x1400 && char <= 0x167F,\n // 'Ogham': (char) => char >= 0x1680 && char <= 0x169F,\n // 'Runic': (char) => char >= 0x16A0 && char <= 0x16FF,\n // 'Tagalog': (char) => char >= 0x1700 && char <= 0x171F,\n // 'Hanunoo': (char) => char >= 0x1720 && char <= 0x173F,\n // 'Buhid': (char) => char >= 0x1740 && char <= 0x175F,\n // 'Tagbanwa': (char) => char >= 0x1760 && char <= 0x177F,\n 'Khmer': (char) => char >= 0x1780 && char <= 0x17FF,\n // 'Mongolian': (char) => char >= 0x1800 && char <= 0x18AF,\n 'Unified Canadian Aboriginal Syllabics Extended': (char) => char >= 0x18B0 && char <= 0x18FF,\n // 'Limbu': (char) => char >= 0x1900 && char <= 0x194F,\n // 'Tai Le': (char) => char >= 0x1950 && char <= 0x197F,\n // 'New Tai Lue': (char) => char >= 0x1980 && char <= 0x19DF,\n // 'Khmer Symbols': (char) => char >= 0x19E0 && char <= 0x19FF,\n // 'Buginese': (char) => char >= 0x1A00 && char <= 0x1A1F,\n // 'Tai Tham': (char) => char >= 0x1A20 && char <= 0x1AAF,\n // 'Combining Diacritical Marks Extended': (char) => char >= 0x1AB0 && char <= 0x1AFF,\n // 'Balinese': (char) => char >= 0x1B00 && char <= 0x1B7F,\n // 'Sundanese': (char) => char >= 0x1B80 && char <= 0x1BBF,\n // 'Batak': (char) => char >= 0x1BC0 && char <= 0x1BFF,\n // 'Lepcha': (char) => char >= 0x1C00 && char <= 0x1C4F,\n // 'Ol Chiki': (char) => char >= 0x1C50 && char <= 0x1C7F,\n // 'Cyrillic Extended-C': (char) => char >= 0x1C80 && char <= 0x1C8F,\n // 'Georgian Extended': (char) => char >= 0x1C90 && char <= 0x1CBF,\n // 'Sundanese Supplement': (char) => char >= 0x1CC0 && char <= 0x1CCF,\n // 'Vedic Extensions': (char) => char >= 0x1CD0 && char <= 0x1CFF,\n // 'Phonetic Extensions': (char) => char >= 0x1D00 && char <= 0x1D7F,\n // 'Phonetic Extensions Supplement': (char) => char >= 0x1D80 && char <= 0x1DBF,\n // 'Combining Diacritical Marks Supplement': (char) => char >= 0x1DC0 && char <= 0x1DFF,\n // 'Latin Extended Additional': (char) => char >= 0x1E00 && char <= 0x1EFF,\n // 'Greek Extended': (char) => char >= 0x1F00 && char <= 0x1FFF,\n 'General Punctuation': (char) => char >= 0x2000 && char <= 0x206F,\n // 'Superscripts and Subscripts': (char) => char >= 0x2070 && char <= 0x209F,\n // 'Currency Symbols': (char) => char >= 0x20A0 && char <= 0x20CF,\n // 'Combining Diacritical Marks for Symbols': (char) => char >= 0x20D0 && char <= 0x20FF,\n 'Letterlike Symbols': (char) => char >= 0x2100 && char <= 0x214F,\n 'Number Forms': (char) => char >= 0x2150 && char <= 0x218F,\n // 'Arrows': (char) => char >= 0x2190 && char <= 0x21FF,\n // 'Mathematical Operators': (char) => char >= 0x2200 && char <= 0x22FF,\n 'Miscellaneous Technical': (char) => char >= 0x2300 && char <= 0x23FF,\n 'Control Pictures': (char) => char >= 0x2400 && char <= 0x243F,\n 'Optical Character Recognition': (char) => char >= 0x2440 && char <= 0x245F,\n 'Enclosed Alphanumerics': (char) => char >= 0x2460 && char <= 0x24FF,\n // 'Box Drawing': (char) => char >= 0x2500 && char <= 0x257F,\n // 'Block Elements': (char) => char >= 0x2580 && char <= 0x259F,\n 'Geometric Shapes': (char) => char >= 0x25A0 && char <= 0x25FF,\n 'Miscellaneous Symbols': (char) => char >= 0x2600 && char <= 0x26FF,\n // 'Dingbats': (char) => char >= 0x2700 && char <= 0x27BF,\n // 'Miscellaneous Mathematical Symbols-A': (char) => char >= 0x27C0 && char <= 0x27EF,\n // 'Supplemental Arrows-A': (char) => char >= 0x27F0 && char <= 0x27FF,\n // 'Braille Patterns': (char) => char >= 0x2800 && char <= 0x28FF,\n // 'Supplemental Arrows-B': (char) => char >= 0x2900 && char <= 0x297F,\n // 'Miscellaneous Mathematical Symbols-B': (char) => char >= 0x2980 && char <= 0x29FF,\n // 'Supplemental Mathematical Operators': (char) => char >= 0x2A00 && char <= 0x2AFF,\n 'Miscellaneous Symbols and Arrows': (char) => char >= 0x2B00 && char <= 0x2BFF,\n // 'Glagolitic': (char) => char >= 0x2C00 && char <= 0x2C5F,\n // 'Latin Extended-C': (char) => char >= 0x2C60 && char <= 0x2C7F,\n // 'Coptic': (char) => char >= 0x2C80 && char <= 0x2CFF,\n // 'Georgian Supplement': (char) => char >= 0x2D00 && char <= 0x2D2F,\n // 'Tifinagh': (char) => char >= 0x2D30 && char <= 0x2D7F,\n // 'Ethiopic Extended': (char) => char >= 0x2D80 && char <= 0x2DDF,\n // 'Cyrillic Extended-A': (char) => char >= 0x2DE0 && char <= 0x2DFF,\n // 'Supplemental Punctuation': (char) => char >= 0x2E00 && char <= 0x2E7F,\n 'CJK Radicals Supplement': (char) => char >= 0x2E80 && char <= 0x2EFF,\n 'Kangxi Radicals': (char) => char >= 0x2F00 && char <= 0x2FDF,\n 'Ideographic Description Characters': (char) => char >= 0x2FF0 && char <= 0x2FFF,\n 'CJK Symbols and Punctuation': (char) => char >= 0x3000 && char <= 0x303F,\n 'Hiragana': (char) => char >= 0x3040 && char <= 0x309F,\n 'Katakana': (char) => char >= 0x30A0 && char <= 0x30FF,\n 'Bopomofo': (char) => char >= 0x3100 && char <= 0x312F,\n 'Hangul Compatibility Jamo': (char) => char >= 0x3130 && char <= 0x318F,\n 'Kanbun': (char) => char >= 0x3190 && char <= 0x319F,\n 'Bopomofo Extended': (char) => char >= 0x31A0 && char <= 0x31BF,\n 'CJK Strokes': (char) => char >= 0x31C0 && char <= 0x31EF,\n 'Katakana Phonetic Extensions': (char) => char >= 0x31F0 && char <= 0x31FF,\n 'Enclosed CJK Letters and Months': (char) => char >= 0x3200 && char <= 0x32FF,\n 'CJK Compatibility': (char) => char >= 0x3300 && char <= 0x33FF,\n 'CJK Unified Ideographs Extension A': (char) => char >= 0x3400 && char <= 0x4DBF,\n 'Yijing Hexagram Symbols': (char) => char >= 0x4DC0 && char <= 0x4DFF,\n 'CJK Unified Ideographs': (char) => char >= 0x4E00 && char <= 0x9FFF,\n 'Yi Syllables': (char) => char >= 0xA000 && char <= 0xA48F,\n 'Yi Radicals': (char) => char >= 0xA490 && char <= 0xA4CF,\n // 'Lisu': (char) => char >= 0xA4D0 && char <= 0xA4FF,\n // 'Vai': (char) => char >= 0xA500 && char <= 0xA63F,\n // 'Cyrillic Extended-B': (char) => char >= 0xA640 && char <= 0xA69F,\n // 'Bamum': (char) => char >= 0xA6A0 && char <= 0xA6FF,\n // 'Modifier Tone Letters': (char) => char >= 0xA700 && char <= 0xA71F,\n // 'Latin Extended-D': (char) => char >= 0xA720 && char <= 0xA7FF,\n // 'Syloti Nagri': (char) => char >= 0xA800 && char <= 0xA82F,\n // 'Common Indic Number Forms': (char) => char >= 0xA830 && char <= 0xA83F,\n // 'Phags-pa': (char) => char >= 0xA840 && char <= 0xA87F,\n // 'Saurashtra': (char) => char >= 0xA880 && char <= 0xA8DF,\n // 'Devanagari Extended': (char) => char >= 0xA8E0 && char <= 0xA8FF,\n // 'Kayah Li': (char) => char >= 0xA900 && char <= 0xA92F,\n // 'Rejang': (char) => char >= 0xA930 && char <= 0xA95F,\n 'Hangul Jamo Extended-A': (char) => char >= 0xA960 && char <= 0xA97F,\n // 'Javanese': (char) => char >= 0xA980 && char <= 0xA9DF,\n // 'Myanmar Extended-B': (char) => char >= 0xA9E0 && char <= 0xA9FF,\n // 'Cham': (char) => char >= 0xAA00 && char <= 0xAA5F,\n // 'Myanmar Extended-A': (char) => char >= 0xAA60 && char <= 0xAA7F,\n // 'Tai Viet': (char) => char >= 0xAA80 && char <= 0xAADF,\n // 'Meetei Mayek Extensions': (char) => char >= 0xAAE0 && char <= 0xAAFF,\n // 'Ethiopic Extended-A': (char) => char >= 0xAB00 && char <= 0xAB2F,\n // 'Latin Extended-E': (char) => char >= 0xAB30 && char <= 0xAB6F,\n // 'Cherokee Supplement': (char) => char >= 0xAB70 && char <= 0xABBF,\n // 'Meetei Mayek': (char) => char >= 0xABC0 && char <= 0xABFF,\n 'Hangul Syllables': (char) => char >= 0xAC00 && char <= 0xD7AF,\n 'Hangul Jamo Extended-B': (char) => char >= 0xD7B0 && char <= 0xD7FF,\n // 'High Surrogates': (char) => char >= 0xD800 && char <= 0xDB7F,\n // 'High Private Use Surrogates': (char) => char >= 0xDB80 && char <= 0xDBFF,\n // 'Low Surrogates': (char) => char >= 0xDC00 && char <= 0xDFFF,\n 'Private Use Area': (char) => char >= 0xE000 && char <= 0xF8FF,\n 'CJK Compatibility Ideographs': (char) => char >= 0xF900 && char <= 0xFAFF,\n // 'Alphabetic Presentation Forms': (char) => char >= 0xFB00 && char <= 0xFB4F,\n 'Arabic Presentation Forms-A': (char) => char >= 0xFB50 && char <= 0xFDFF,\n // 'Variation Selectors': (char) => char >= 0xFE00 && char <= 0xFE0F,\n 'Vertical Forms': (char) => char >= 0xFE10 && char <= 0xFE1F,\n // 'Combining Half Marks': (char) => char >= 0xFE20 && char <= 0xFE2F,\n 'CJK Compatibility Forms': (char) => char >= 0xFE30 && char <= 0xFE4F,\n 'Small Form Variants': (char) => char >= 0xFE50 && char <= 0xFE6F,\n 'Arabic Presentation Forms-B': (char) => char >= 0xFE70 && char <= 0xFEFF,\n 'Halfwidth and Fullwidth Forms': (char) => char >= 0xFF00 && char <= 0xFFEF\n // 'Specials': (char) => char >= 0xFFF0 && char <= 0xFFFF,\n // 'Linear B Syllabary': (char) => char >= 0x10000 && char <= 0x1007F,\n // 'Linear B Ideograms': (char) => char >= 0x10080 && char <= 0x100FF,\n // 'Aegean Numbers': (char) => char >= 0x10100 && char <= 0x1013F,\n // 'Ancient Greek Numbers': (char) => char >= 0x10140 && char <= 0x1018F,\n // 'Ancient Symbols': (char) => char >= 0x10190 && char <= 0x101CF,\n // 'Phaistos Disc': (char) => char >= 0x101D0 && char <= 0x101FF,\n // 'Lycian': (char) => char >= 0x10280 && char <= 0x1029F,\n // 'Carian': (char) => char >= 0x102A0 && char <= 0x102DF,\n // 'Coptic Epact Numbers': (char) => char >= 0x102E0 && char <= 0x102FF,\n // 'Old Italic': (char) => char >= 0x10300 && char <= 0x1032F,\n // 'Gothic': (char) => char >= 0x10330 && char <= 0x1034F,\n // 'Old Permic': (char) => char >= 0x10350 && char <= 0x1037F,\n // 'Ugaritic': (char) => char >= 0x10380 && char <= 0x1039F,\n // 'Old Persian': (char) => char >= 0x103A0 && char <= 0x103DF,\n // 'Deseret': (char) => char >= 0x10400 && char <= 0x1044F,\n // 'Shavian': (char) => char >= 0x10450 && char <= 0x1047F,\n // 'Osmanya': (char) => char >= 0x10480 && char <= 0x104AF,\n // 'Osage': (char) => char >= 0x104B0 && char <= 0x104FF,\n // 'Elbasan': (char) => char >= 0x10500 && char <= 0x1052F,\n // 'Caucasian Albanian': (char) => char >= 0x10530 && char <= 0x1056F,\n // 'Linear A': (char) => char >= 0x10600 && char <= 0x1077F,\n // 'Cypriot Syllabary': (char) => char >= 0x10800 && char <= 0x1083F,\n // 'Imperial Aramaic': (char) => char >= 0x10840 && char <= 0x1085F,\n // 'Palmyrene': (char) => char >= 0x10860 && char <= 0x1087F,\n // 'Nabataean': (char) => char >= 0x10880 && char <= 0x108AF,\n // 'Hatran': (char) => char >= 0x108E0 && char <= 0x108FF,\n // 'Phoenician': (char) => char >= 0x10900 && char <= 0x1091F,\n // 'Lydian': (char) => char >= 0x10920 && char <= 0x1093F,\n // 'Meroitic Hieroglyphs': (char) => char >= 0x10980 && char <= 0x1099F,\n // 'Meroitic Cursive': (char) => char >= 0x109A0 && char <= 0x109FF,\n // 'Kharoshthi': (char) => char >= 0x10A00 && char <= 0x10A5F,\n // 'Old South Arabian': (char) => char >= 0x10A60 && char <= 0x10A7F,\n // 'Old North Arabian': (char) => char >= 0x10A80 && char <= 0x10A9F,\n // 'Manichaean': (char) => char >= 0x10AC0 && char <= 0x10AFF,\n // 'Avestan': (char) => char >= 0x10B00 && char <= 0x10B3F,\n // 'Inscriptional Parthian': (char) => char >= 0x10B40 && char <= 0x10B5F,\n // 'Inscriptional Pahlavi': (char) => char >= 0x10B60 && char <= 0x10B7F,\n // 'Psalter Pahlavi': (char) => char >= 0x10B80 && char <= 0x10BAF,\n // 'Old Turkic': (char) => char >= 0x10C00 && char <= 0x10C4F,\n // 'Old Hungarian': (char) => char >= 0x10C80 && char <= 0x10CFF,\n // 'Hanifi Rohingya': (char) => char >= 0x10D00 && char <= 0x10D3F,\n // 'Rumi Numeral Symbols': (char) => char >= 0x10E60 && char <= 0x10E7F,\n // 'Old Sogdian': (char) => char >= 0x10F00 && char <= 0x10F2F,\n // 'Sogdian': (char) => char >= 0x10F30 && char <= 0x10F6F,\n // 'Elymaic': (char) => char >= 0x10FE0 && char <= 0x10FFF,\n // 'Brahmi': (char) => char >= 0x11000 && char <= 0x1107F,\n // 'Kaithi': (char) => char >= 0x11080 && char <= 0x110CF,\n // 'Sora Sompeng': (char) => char >= 0x110D0 && char <= 0x110FF,\n // 'Chakma': (char) => char >= 0x11100 && char <= 0x1114F,\n // 'Mahajani': (char) => char >= 0x11150 && char <= 0x1117F,\n // 'Sharada': (char) => char >= 0x11180 && char <= 0x111DF,\n // 'Sinhala Archaic Numbers': (char) => char >= 0x111E0 && char <= 0x111FF,\n // 'Khojki': (char) => char >= 0x11200 && char <= 0x1124F,\n // 'Multani': (char) => char >= 0x11280 && char <= 0x112AF,\n // 'Khudawadi': (char) => char >= 0x112B0 && char <= 0x112FF,\n // 'Grantha': (char) => char >= 0x11300 && char <= 0x1137F,\n // 'Newa': (char) => char >= 0x11400 && char <= 0x1147F,\n // 'Tirhuta': (char) => char >= 0x11480 && char <= 0x114DF,\n // 'Siddham': (char) => char >= 0x11580 && char <= 0x115FF,\n // 'Modi': (char) => char >= 0x11600 && char <= 0x1165F,\n // 'Mongolian Supplement': (char) => char >= 0x11660 && char <= 0x1167F,\n // 'Takri': (char) => char >= 0x11680 && char <= 0x116CF,\n // 'Ahom': (char) => char >= 0x11700 && char <= 0x1173F,\n // 'Dogra': (char) => char >= 0x11800 && char <= 0x1184F,\n // 'Warang Citi': (char) => char >= 0x118A0 && char <= 0x118FF,\n // 'Nandinagari': (char) => char >= 0x119A0 && char <= 0x119FF,\n // 'Zanabazar Square': (char) => char >= 0x11A00 && char <= 0x11A4F,\n // 'Soyombo': (char) => char >= 0x11A50 && char <= 0x11AAF,\n // 'Pau Cin Hau': (char) => char >= 0x11AC0 && char <= 0x11AFF,\n // 'Bhaiksuki': (char) => char >= 0x11C00 && char <= 0x11C6F,\n // 'Marchen': (char) => char >= 0x11C70 && char <= 0x11CBF,\n // 'Masaram Gondi': (char) => char >= 0x11D00 && char <= 0x11D5F,\n // 'Gunjala Gondi': (char) => char >= 0x11D60 && char <= 0x11DAF,\n // 'Makasar': (char) => char >= 0x11EE0 && char <= 0x11EFF,\n // 'Tamil Supplement': (char) => char >= 0x11FC0 && char <= 0x11FFF,\n // 'Cuneiform': (char) => char >= 0x12000 && char <= 0x123FF,\n // 'Cuneiform Numbers and Punctuation': (char) => char >= 0x12400 && char <= 0x1247F,\n // 'Early Dynastic Cuneiform': (char) => char >= 0x12480 && char <= 0x1254F,\n // 'Egyptian Hieroglyphs': (char) => char >= 0x13000 && char <= 0x1342F,\n // 'Egyptian Hieroglyph Format Controls': (char) => char >= 0x13430 && char <= 0x1343F,\n // 'Anatolian Hieroglyphs': (char) => char >= 0x14400 && char <= 0x1467F,\n // 'Bamum Supplement': (char) => char >= 0x16800 && char <= 0x16A3F,\n // 'Mro': (char) => char >= 0x16A40 && char <= 0x16A6F,\n // 'Bassa Vah': (char) => char >= 0x16AD0 && char <= 0x16AFF,\n // 'Pahawh Hmong': (char) => char >= 0x16B00 && char <= 0x16B8F,\n // 'Medefaidrin': (char) => char >= 0x16E40 && char <= 0x16E9F,\n // 'Miao': (char) => char >= 0x16F00 && char <= 0x16F9F,\n // 'Ideographic Symbols and Punctuation': (char) => char >= 0x16FE0 && char <= 0x16FFF,\n // 'Tangut': (char) => char >= 0x17000 && char <= 0x187FF,\n // 'Tangut Components': (char) => char >= 0x18800 && char <= 0x18AFF,\n // 'Kana Supplement': (char) => char >= 0x1B000 && char <= 0x1B0FF,\n // 'Kana Extended-A': (char) => char >= 0x1B100 && char <= 0x1B12F,\n // 'Small Kana Extension': (char) => char >= 0x1B130 && char <= 0x1B16F,\n // 'Nushu': (char) => char >= 0x1B170 && char <= 0x1B2FF,\n // 'Duployan': (char) => char >= 0x1BC00 && char <= 0x1BC9F,\n // 'Shorthand Format Controls': (char) => char >= 0x1BCA0 && char <= 0x1BCAF,\n // 'Byzantine Musical Symbols': (char) => char >= 0x1D000 && char <= 0x1D0FF,\n // 'Musical Symbols': (char) => char >= 0x1D100 && char <= 0x1D1FF,\n // 'Ancient Greek Musical Notation': (char) => char >= 0x1D200 && char <= 0x1D24F,\n // 'Mayan Numerals': (char) => char >= 0x1D2E0 && char <= 0x1D2FF,\n // 'Tai Xuan Jing Symbols': (char) => char >= 0x1D300 && char <= 0x1D35F,\n // 'Counting Rod Numerals': (char) => char >= 0x1D360 && char <= 0x1D37F,\n // 'Mathematical Alphanumeric Symbols': (char) => char >= 0x1D400 && char <= 0x1D7FF,\n // 'Sutton SignWriting': (char) => char >= 0x1D800 && char <= 0x1DAAF,\n // 'Glagolitic Supplement': (char) => char >= 0x1E000 && char <= 0x1E02F,\n // 'Nyiakeng Puachue Hmong': (char) => char >= 0x1E100 && char <= 0x1E14F,\n // 'Wancho': (char) => char >= 0x1E2C0 && char <= 0x1E2FF,\n // 'Mende Kikakui': (char) => char >= 0x1E800 && char <= 0x1E8DF,\n // 'Adlam': (char) => char >= 0x1E900 && char <= 0x1E95F,\n // 'Indic Siyaq Numbers': (char) => char >= 0x1EC70 && char <= 0x1ECBF,\n // 'Ottoman Siyaq Numbers': (char) => char >= 0x1ED00 && char <= 0x1ED4F,\n // 'Arabic Mathematical Alphabetic Symbols': (char) => char >= 0x1EE00 && char <= 0x1EEFF,\n // 'Mahjong Tiles': (char) => char >= 0x1F000 && char <= 0x1F02F,\n // 'Domino Tiles': (char) => char >= 0x1F030 && char <= 0x1F09F,\n // 'Playing Cards': (char) => char >= 0x1F0A0 && char <= 0x1F0FF,\n // 'Enclosed Alphanumeric Supplement': (char) => char >= 0x1F100 && char <= 0x1F1FF,\n // 'Enclosed Ideographic Supplement': (char) => char >= 0x1F200 && char <= 0x1F2FF,\n // 'Miscellaneous Symbols and Pictographs': (char) => char >= 0x1F300 && char <= 0x1F5FF,\n // 'Emoticons': (char) => char >= 0x1F600 && char <= 0x1F64F,\n // 'Ornamental Dingbats': (char) => char >= 0x1F650 && char <= 0x1F67F,\n // 'Transport and Map Symbols': (char) => char >= 0x1F680 && char <= 0x1F6FF,\n // 'Alchemical Symbols': (char) => char >= 0x1F700 && char <= 0x1F77F,\n // 'Geometric Shapes Extended': (char) => char >= 0x1F780 && char <= 0x1F7FF,\n // 'Supplemental Arrows-C': (char) => char >= 0x1F800 && char <= 0x1F8FF,\n // 'Supplemental Symbols and Pictographs': (char) => char >= 0x1F900 && char <= 0x1F9FF,\n // 'Chess Symbols': (char) => char >= 0x1FA00 && char <= 0x1FA6F,\n // 'Symbols and Pictographs Extended-A': (char) => char >= 0x1FA70 && char <= 0x1FAFF,\n // 'CJK Unified Ideographs Extension B': (char) => char >= 0x20000 && char <= 0x2A6DF,\n // 'CJK Unified Ideographs Extension C': (char) => char >= 0x2A700 && char <= 0x2B73F,\n // 'CJK Unified Ideographs Extension D': (char) => char >= 0x2B740 && char <= 0x2B81F,\n // 'CJK Unified Ideographs Extension E': (char) => char >= 0x2B820 && char <= 0x2CEAF,\n // 'CJK Unified Ideographs Extension F': (char) => char >= 0x2CEB0 && char <= 0x2EBEF,\n // 'CJK Compatibility Ideographs Supplement': (char) => char >= 0x2F800 && char <= 0x2FA1F,\n // 'Tags': (char) => char >= 0xE0000 && char <= 0xE007F,\n // 'Variation Selectors Supplement': (char) => char >= 0xE0100 && char <= 0xE01EF,\n // 'Supplementary Private Use Area-A': (char) => char >= 0xF0000 && char <= 0xFFFFF,\n // 'Supplementary Private Use Area-B': (char) => char >= 0x100000 && char <= 0x10FFFF,\n};\n\nexport default unicodeBlockLookup;\n","// @flow\n\n/* eslint-disable new-cap */\n\nimport isChar from './is_char_in_unicode_block.js';\n\nexport function allowsIdeographicBreaking(chars: string): boolean {\n for (const char of chars) {\n if (!charAllowsIdeographicBreaking(char.charCodeAt(0))) return false;\n }\n return true;\n}\n\nexport function allowsVerticalWritingMode(chars: string): boolean {\n for (const char of chars) {\n if (charHasUprightVerticalOrientation(char.charCodeAt(0))) return true;\n }\n return false;\n}\n\nexport function allowsLetterSpacing(chars: string): boolean {\n for (const char of chars) {\n if (!charAllowsLetterSpacing(char.charCodeAt(0))) return false;\n }\n return true;\n}\n\nexport function charAllowsLetterSpacing(char: number): boolean {\n if (isChar['Arabic'](char)) return false;\n if (isChar['Arabic Supplement'](char)) return false;\n if (isChar['Arabic Extended-A'](char)) return false;\n if (isChar['Arabic Presentation Forms-A'](char)) return false;\n if (isChar['Arabic Presentation Forms-B'](char)) return false;\n\n return true;\n}\n\nexport function charAllowsIdeographicBreaking(char: number): boolean {\n // Return early for characters outside all ideographic ranges.\n if (char < 0x2E80) return false;\n\n if (isChar['Bopomofo Extended'](char)) return true;\n if (isChar['Bopomofo'](char)) return true;\n if (isChar['CJK Compatibility Forms'](char)) return true;\n if (isChar['CJK Compatibility Ideographs'](char)) return true;\n if (isChar['CJK Compatibility'](char)) return true;\n if (isChar['CJK Radicals Supplement'](char)) return true;\n if (isChar['CJK Strokes'](char)) return true;\n if (isChar['CJK Symbols and Punctuation'](char)) return true;\n if (isChar['CJK Unified Ideographs Extension A'](char)) return true;\n if (isChar['CJK Unified Ideographs'](char)) return true;\n if (isChar['Enclosed CJK Letters and Months'](char)) return true;\n if (isChar['Halfwidth and Fullwidth Forms'](char)) return true;\n if (isChar['Hiragana'](char)) return true;\n if (isChar['Ideographic Description Characters'](char)) return true;\n if (isChar['Kangxi Radicals'](char)) return true;\n if (isChar['Katakana Phonetic Extensions'](char)) return true;\n if (isChar['Katakana'](char)) return true;\n if (isChar['Vertical Forms'](char)) return true;\n if (isChar['Yi Radicals'](char)) return true;\n if (isChar['Yi Syllables'](char)) return true;\n\n return false;\n}\n\n// The following logic comes from\n// <http://www.unicode.org/Public/12.0.0/ucd/VerticalOrientation.txt>.\n// Keep it synchronized with\n// <http://www.unicode.org/Public/UCD/latest/ucd/VerticalOrientation.txt>.\n// The data file denotes with “U” or “Tu” any codepoint that may be drawn\n// upright in vertical text but does not distinguish between upright and\n// “neutral” characters.\n\n// Blocks in the Unicode supplementary planes are excluded from this module due\n// to <https://github.com/mapbox/mapbox-gl/issues/29>.\n\n/**\n * Returns true if the given Unicode codepoint identifies a character with\n * upright orientation.\n *\n * A character has upright orientation if it is drawn upright (unrotated)\n * whether the line is oriented horizontally or vertically, even if both\n * adjacent characters can be rotated. For example, a Chinese character is\n * always drawn upright. An uprightly oriented character causes an adjacent\n * “neutral” character to be drawn upright as well.\n * @private\n */\nexport function charHasUprightVerticalOrientation(char: number): boolean {\n if (char === 0x02EA /* modifier letter yin departing tone mark */ ||\n char === 0x02EB /* modifier letter yang departing tone mark */) {\n return true;\n }\n\n // Return early for characters outside all ranges whose characters remain\n // upright in vertical writing mode.\n if (char < 0x1100) return false;\n\n if (isChar['Bopomofo Extended'](char)) return true;\n if (isChar['Bopomofo'](char)) return true;\n if (isChar['CJK Compatibility Forms'](char)) {\n if (!((char >= 0xFE49 /* dashed overline */ && char <= 0xFE4F) /* wavy low line */)) {\n return true;\n }\n }\n if (isChar['CJK Compatibility Ideographs'](char)) return true;\n if (isChar['CJK Compatibility'](char)) return true;\n if (isChar['CJK Radicals Supplement'](char)) return true;\n if (isChar['CJK Strokes'](char)) return true;\n if (isChar['CJK Symbols and Punctuation'](char)) {\n if (!((char >= 0x3008 /* left angle bracket */ && char <= 0x3011) /* right black lenticular bracket */) &&\n !((char >= 0x3014 /* left tortoise shell bracket */ && char <= 0x301F) /* low double prime quotation mark */) &&\n char !== 0x3030 /* wavy dash */) {\n return true;\n }\n }\n if (isChar['CJK Unified Ideographs Extension A'](char)) return true;\n if (isChar['CJK Unified Ideographs'](char)) return true;\n if (isChar['Enclosed CJK Letters and Months'](char)) return true;\n if (isChar['Hangul Compatibility Jamo'](char)) return true;\n if (isChar['Hangul Jamo Extended-A'](char)) return true;\n if (isChar['Hangul Jamo Extended-B'](char)) return true;\n if (isChar['Hangul Jamo'](char)) return true;\n if (isChar['Hangul Syllables'](char)) return true;\n if (isChar['Hiragana'](char)) return true;\n if (isChar['Ideographic Description Characters'](char)) return true;\n if (isChar['Kanbun'](char)) return true;\n if (isChar['Kangxi Radicals'](char)) return true;\n if (isChar['Katakana Phonetic Extensions'](char)) return true;\n if (isChar['Katakana'](char)) {\n if (char !== 0x30FC /* katakana-hiragana prolonged sound mark */) {\n return true;\n }\n }\n if (isChar['Halfwidth and Fullwidth Forms'](char)) {\n if (char !== 0xFF08 /* fullwidth left parenthesis */ &&\n char !== 0xFF09 /* fullwidth right parenthesis */ &&\n char !== 0xFF0D /* fullwidth hyphen-minus */ &&\n !((char >= 0xFF1A /* fullwidth colon */ && char <= 0xFF1E) /* fullwidth greater-than sign */) &&\n char !== 0xFF3B /* fullwidth left square bracket */ &&\n char !== 0xFF3D /* fullwidth right square bracket */ &&\n char !== 0xFF3F /* fullwidth low line */ &&\n !(char >= 0xFF5B /* fullwidth left curly bracket */ && char <= 0xFFDF) &&\n char !== 0xFFE3 /* fullwidth macron */ &&\n !(char >= 0xFFE8 /* halfwidth forms light vertical */ && char <= 0xFFEF)) {\n return true;\n }\n }\n if (isChar['Small Form Variants'](char)) {\n if (!((char >= 0xFE58 /* small em dash */ && char <= 0xFE5E) /* small right tortoise shell bracket */) &&\n !((char >= 0xFE63 /* small hyphen-minus */ && char <= 0xFE66) /* small equals sign */)) {\n return true;\n }\n }\n if (isChar['Unified Canadian Aboriginal Syllabics'](char)) return true;\n if (isChar['Unified Canadian Aboriginal Syllabics Extended'](char)) return true;\n if (isChar['Vertical Forms'](char)) return true;\n if (isChar['Yijing Hexagram Symbols'](char)) return true;\n if (isChar['Yi Syllables'](char)) return true;\n if (isChar['Yi Radicals'](char)) return true;\n\n return false;\n}\n\n/**\n * Returns true if the given Unicode codepoint identifies a character with\n * neutral orientation.\n *\n * A character has neutral orientation if it may be drawn rotated or unrotated\n * when the line is oriented vertically, depending on the orientation of the\n * adjacent characters. For example, along a verticlly oriented line, the vulgar\n * fraction ½ is drawn upright among Chinese characters but rotated among Latin\n * letters. A neutrally oriented character does not influence whether an\n * adjacent character is drawn upright or rotated.\n * @private\n */\nexport function charHasNeutralVerticalOrientation(char: number): boolean {\n if (isChar['Latin-1 Supplement'](char)) {\n if (char === 0x00A7 /* section sign */ ||\n char === 0x00A9 /* copyright sign */ ||\n char === 0x00AE /* registered sign */ ||\n char === 0x00B1 /* plus-minus sign */ ||\n char === 0x00BC /* vulgar fraction one quarter */ ||\n char === 0x00BD /* vulgar fraction one half */ ||\n char === 0x00BE /* vulgar fraction three quarters */ ||\n char === 0x00D7 /* multiplication sign */ ||\n char === 0x00F7 /* division sign */) {\n return true;\n }\n }\n if (isChar['General Punctuation'](char)) {\n if (char === 0x2016 /* double vertical line */ ||\n char === 0x2020 /* dagger */ ||\n char === 0x2021 /* double dagger */ ||\n char === 0x2030 /* per mille sign */ ||\n char === 0x2031 /* per ten thousand sign */ ||\n char === 0x203B /* reference mark */ ||\n char === 0x203C /* double exclamation mark */ ||\n char === 0x2042 /* asterism */ ||\n char === 0x2047 /* double question mark */ ||\n char === 0x2048 /* question exclamation mark */ ||\n char === 0x2049 /* exclamation question mark */ ||\n char === 0x2051 /* two asterisks aligned vertically */) {\n return true;\n }\n }\n if (isChar['Letterlike Symbols'](char)) return true;\n if (isChar['Number Forms'](char)) return true;\n if (isChar['Miscellaneous Technical'](char)) {\n if ((char >= 0x2300 /* diameter sign */ && char <= 0x2307 /* wavy line */) ||\n (char >= 0x230C /* bottom right crop */ && char <= 0x231F /* bottom right corner */) ||\n (char >= 0x2324 /* up arrowhead between two horizontal bars */ && char <= 0x2328 /* keyboard */) ||\n char === 0x232B /* erase to the left */ ||\n (char >= 0x237D /* shouldered open box */ && char <= 0x239A /* clear screen symbol */) ||\n (char >= 0x23BE /* dentistry symbol light vertical and top right */ && char <= 0x23CD /* square foot */) ||\n char === 0x23CF /* eject symbol */ ||\n (char >= 0x23D1 /* metrical breve */ && char <= 0x23DB /* fuse */) ||\n (char >= 0x23E2 /* white trapezium */ && char <= 0x23FF)) {\n return true;\n }\n }\n if (isChar['Control Pictures'](char) && char !== 0x2423 /* open box */) return true;\n if (isChar['Optical Character Recognition'](char)) return true;\n if (isChar['Enclosed Alphanumerics'](char)) return true;\n if (isChar['Geometric Shapes'](char)) return true;\n if (isChar['Miscellaneous Symbols'](char)) {\n if (!((char >= 0x261A /* black left pointing index */ && char <= 0x261F) /* white down pointing index */)) {\n return true;\n }\n }\n if (isChar['Miscellaneous Symbols and Arrows'](char)) {\n if ((char >= 0x2B12 /* square with top half black */ && char <= 0x2B2F /* white vertical ellipse */) ||\n (char >= 0x2B50 /* white medium star */ && char <= 0x2B59 /* heavy circled saltire */) ||\n (char >= 0x2BB8 /* upwards white arrow from bar with horizontal bar */ && char <= 0x2BEB)) {\n return true;\n }\n }\n if (isChar['CJK Symbols and Punctuation'](char)) return true;\n if (isChar['Katakana'](char)) return true;\n if (isChar['Private Use Area'](char)) return true;\n if (isChar['CJK Compatibility Forms'](char)) return true;\n if (isChar['Small Form Variants'](char)) return true;\n if (isChar['Halfwidth and Fullwidth Forms'](char)) return true;\n\n if (char === 0x221E /* infinity */ ||\n char === 0x2234 /* therefore */ ||\n char === 0x2235 /* because */ ||\n (char >= 0x2700 /* black safety scissors */ && char <= 0x2767 /* rotated floral heart bullet */) ||\n (char >= 0x2776 /* dingbat negative circled digit one */ && char <= 0x2793 /* dingbat negative circled sans-serif number ten */) ||\n char === 0xFFFC /* object replacement character */ ||\n char === 0xFFFD /* replacement character */) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Returns true if the given Unicode codepoint identifies a character with\n * rotated orientation.\n *\n * A character has rotated orientation if it is drawn rotated when the line is\n * oriented vertically, even if both adjacent characters are upright. For\n * example, a Latin letter is drawn rotated along a vertical line. A rotated\n * character causes an adjacent “neutral” character to be drawn rotated as well.\n * @private\n */\nexport function charHasRotatedVerticalOrientation(char: number): boolean {\n return !(charHasUprightVerticalOrientation(char) ||\n charHasNeutralVerticalOrientation(char));\n}\n\nexport function charInComplexShapingScript(char: number): boolean {\n return isChar['Arabic'](char) ||\n isChar['Arabic Supplement'](char) ||\n isChar['Arabic Extended-A'](char) ||\n isChar['Arabic Presentation Forms-A'](char) ||\n isChar['Arabic Presentation Forms-B'](char);\n}\n\nexport function charInRTLScript(char: number): boolean {\n // Main blocks for Hebrew, Arabic, Thaana and other RTL scripts\n return (char >= 0x0590 && char <= 0x08FF) ||\n isChar['Arabic Presentation Forms-A'](char) ||\n isChar['Arabic Presentation Forms-B'](char);\n}\n\nexport function charInSupportedScript(char: number, canRenderRTL: boolean): boolean {\n // This is a rough heuristic: whether we \"can render\" a script\n // actually depends on the properties of the font being used\n // and whether differences from the ideal rendering are considered\n // semantically significant.\n\n // Even in Latin script, we \"can't render\" combinations such as the fi\n // ligature, but we don't consider that semantically significant.\n if (!canRenderRTL && charInRTLScript(char)) {\n return false;\n }\n if ((char >= 0x0900 && char <= 0x0DFF) ||\n // Main blocks for Indic scripts and Sinhala\n (char >= 0x0F00 && char <= 0x109F) ||\n // Main blocks for Tibetan and Myanmar\n isChar['Khmer'](char)) {\n // These blocks cover common scripts that require\n // complex text shaping, based on unicode script metadata:\n // http://www.unicode.org/repos/cldr/trunk/common/properties/scriptMetadata.txt\n // where \"Web Rank <= 32\" \"Shaping Required = YES\"\n return false;\n }\n return true;\n}\n\nexport function stringContainsRTLText(chars: string): boolean {\n for (const char of chars) {\n if (charInRTLScript(char.charCodeAt(0))) {\n return true;\n }\n }\n return false;\n}\n\nexport function isStringInSupportedScript(chars: string, canRenderRTL: boolean): boolean {\n for (const char of chars) {\n if (!charInSupportedScript(char.charCodeAt(0), canRenderRTL)) {\n return false;\n }\n }\n return true;\n}\n","// @flow strict\n\nimport window from './window.js';\nimport type {Cancelable} from '../types/cancelable.js';\n\nlet linkEl;\n\nlet reducedMotionQuery: MediaQueryList;\n\nlet stubTime: number | void;\n\nlet canvas;\n\n/**\n * @private\n */\nconst exported = {\n /**\n * Returns either performance.now() or a value set by setNow.\n * @returns {number} Time value in milliseconds.\n */\n now(): number {\n if (stubTime !== undefined) {\n return stubTime;\n }\n return window.performance.now();\n },\n setNow(time: number) {\n stubTime = time;\n },\n\n restoreNow() {\n stubTime = undefined;\n },\n\n frame(fn: (paintStartTimestamp: number) => void): Cancelable {\n const frame = window.requestAnimationFrame(fn);\n return {cancel: () => window.cancelAnimationFrame(frame)};\n },\n\n getImageData(img: CanvasImageSource, padding?: number = 0): ImageData {\n const {width, height} = img;\n\n if (!canvas) {\n canvas = window.document.createElement('canvas');\n }\n\n const context = canvas.getContext('2d', {willReadFrequently: true});\n if (!context) {\n throw new Error('failed to create canvas 2d context');\n }\n\n if (width > canvas.width || height > canvas.height) {\n canvas.width = width;\n canvas.height = height;\n }\n\n context.clearRect(-padding, -padding, width + 2 * padding, height + 2 * padding);\n context.drawImage(img, 0, 0, width, height);\n return context.getImageData(-padding, -padding, width + 2 * padding, height + 2 * padding);\n },\n\n resolveURL(path: string): string {\n if (!linkEl) linkEl = window.document.createElement('a');\n linkEl.href = path;\n return linkEl.href;\n },\n\n get devicePixelRatio(): number { return window.devicePixelRatio; },\n get prefersReducedMotion(): boolean {\n if (!window.matchMedia) return false;\n // Lazily initialize media query.\n if (reducedMotionQuery == null) {\n reducedMotionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');\n }\n return reducedMotionQuery.matches;\n },\n};\n\nexport default exported;\n","// @flow\n\nimport {Event, Evented} from '../util/evented.js';\nimport {getArrayBuffer} from '../util/ajax.js';\nimport browser from '../util/browser.js';\nimport assert from 'assert';\nimport {isWorker} from '../util/util.js';\nimport type {Callback} from '../types/callback.js';\n\nconst status = {\n unavailable: 'unavailable', // Not loaded\n deferred: 'deferred', // The plugin URL has been specified, but loading has been deferred\n loading: 'loading', // request in-flight\n loaded: 'loaded',\n error: 'error'\n};\n\nexport type PluginState = {\n pluginStatus: $Values<typeof status>;\n pluginURL: ?string\n};\n\ntype PluginStateSyncCallback = (state: PluginState) => void;\nlet _completionCallback = null;\n\n//Variables defining the current state of the plugin\nlet pluginStatus = status.unavailable;\nlet pluginURL: ?string = null;\n\nexport const triggerPluginCompletionEvent = function(error: ?Error) {\n // NetworkError's are not correctly reflected by the plugin status which prevents reloading plugin\n if (error && typeof error === 'string' && error.indexOf('NetworkError') > -1) {\n pluginStatus = status.error;\n }\n\n if (_completionCallback) {\n _completionCallback(error);\n }\n};\n\nfunction sendPluginStateToWorker() {\n evented.fire(new Event('pluginStateChange', {pluginStatus, pluginURL}));\n}\n\nexport const evented: Evented = new Evented();\n\nexport const getRTLTextPluginStatus = function (): string {\n return pluginStatus;\n};\n\nexport const registerForPluginStateChange = function(callback: PluginStateSyncCallback): PluginStateSyncCallback {\n // Do an initial sync of the state\n callback({pluginStatus, pluginURL});\n // Listen for all future state changes\n evented.on('pluginStateChange', callback);\n return callback;\n};\n\nexport const clearRTLTextPlugin = function() {\n pluginStatus = status.unavailable;\n pluginURL = null;\n};\n\nexport const setRTLTextPlugin = function(url: string, callback: ?Callback<{err: ?Error}>, deferred: boolean = false) {\n if (pluginStatus === status.deferred || pluginStatus === status.loading || pluginStatus === status.loaded) {\n throw new Error('setRTLTextPlugin cannot be called multiple times.');\n }\n pluginURL = browser.resolveURL(url);\n pluginStatus = status.deferred;\n _completionCallback = callback;\n sendPluginStateToWorker();\n\n //Start downloading the plugin immediately if not intending to lazy-load\n if (!deferred) {\n downloadRTLTextPlugin();\n }\n};\n\nexport const downloadRTLTextPlugin = function() {\n if (pluginStatus !== status.deferred || !pluginURL) {\n throw new Error('rtl-text-plugin cannot be downloaded unless a pluginURL is specified');\n }\n pluginStatus = status.loading;\n sendPluginStateToWorker();\n if (pluginURL) {\n getArrayBuffer({url: pluginURL}, (error) => {\n if (error) {\n triggerPluginCompletionEvent(error);\n } else {\n pluginStatus = status.loaded;\n sendPluginStateToWorker();\n }\n });\n }\n};\n\nexport const plugin: {\n applyArabicShaping: ?Function,\n processBidirectionalText: ?(string, Array<number>) => Array<string>,\n processStyledBidirectionalText: ?(string, Array<number>, Array<number>) => Array<[string, Array<number>]>,\n isLoaded: () => boolean,\n isLoading: () => boolean,\n setState: (state: PluginState) => void,\n isParsed: () => boolean,\n getPluginURL: () => ?string\n} = {\n applyArabicShaping: null,\n processBidirectionalText: null,\n processStyledBidirectionalText: null,\n isLoaded() {\n return pluginStatus === status.loaded || // Main Thread: loaded if the completion callback returned successfully\n plugin.applyArabicShaping != null; // Web-worker: loaded if the plugin functions have been compiled\n },\n isLoading() { // Main Thread Only: query the loading status, this function does not return the correct value in the worker context.\n return pluginStatus === status.loading;\n },\n setState(state: PluginState) { // Worker thread only: this tells the worker threads that the plugin is available on the Main thread\n assert(isWorker(), 'Cannot set the state of the rtl-text-plugin when not in the web-worker context');\n\n pluginStatus = state.pluginStatus;\n pluginURL = state.pluginURL;\n },\n isParsed(): boolean {\n assert(isWorker(), 'rtl-text-plugin is only parsed on the worker-threads');\n\n return plugin.applyArabicShaping != null &&\n plugin.processBidirectionalText != null &&\n plugin.processStyledBidirectionalText != null;\n },\n getPluginURL(): ?string {\n assert(isWorker(), 'rtl-text-plugin url can only be queried from the worker threads');\n return pluginURL;\n }\n};\n\nexport const lazyLoadRTLTextPlugin = function() {\n if (!plugin.isLoading() &&\n !plugin.isLoaded() &&\n getRTLTextPluginStatus() === 'deferred'\n ) {\n downloadRTLTextPlugin();\n }\n};\n","// @flow\n\nimport {isStringInSupportedScript} from '../util/script_detection.js';\nimport {plugin as rtlTextPlugin} from '../source/rtl_text_plugin.js';\n\nimport type {TransitionSpecification} from '../style-spec/types.js';\n\nclass EvaluationParameters {\n zoom: number;\n pitch: number;\n now: number;\n fadeDuration: number;\n transition: TransitionSpecification;\n\n // \"options\" may also be another EvaluationParameters to copy\n constructor(zoom: number, options?: any) {\n this.zoom = zoom;\n\n if (options) {\n this.now = options.now;\n this.fadeDuration = options.fadeDuration;\n this.transition = options.transition;\n this.pitch = options.pitch;\n } else {\n this.now = 0;\n this.fadeDuration = 0;\n this.transition = {};\n this.pitch = 0;\n }\n }\n\n isSupportedScript(str: string): boolean {\n return isStringInSupportedScript(str, rtlTextPlugin.isLoaded());\n }\n}\n\nexport default EvaluationParameters;\n","// @flow\n\nimport assert from 'assert';\nimport {clone, extend, easeCubicInOut} from '../util/util.js';\nimport * as interpolate from '../style-spec/util/interpolate.js';\nimport {normalizePropertyExpression} from '../style-spec/expression/index.js';\nimport Color from '../style-spec/util/color.js';\nimport {register} from '../util/web_worker_transfer.js';\nimport EvaluationParameters from './evaluation_parameters.js';\n\nimport type {CanonicalTileID} from '../source/tile_id.js';\nimport type {StylePropertySpecification} from '../style-spec/style-spec.js';\nimport type {\n TransitionSpecification,\n PropertyValueSpecification\n} from '../style-spec/types.js';\n\nimport type {\n Feature,\n FeatureState,\n StylePropertyExpression,\n SourceExpression,\n CompositeExpression\n} from '../style-spec/expression/index.js';\n\ntype TimePoint = number;\n\n/**\n * Implements a number of classes that define state and behavior for paint and layout properties, most\n * importantly their respective evaluation chains:\n *\n * Transitionable paint property value\n * → Transitioning paint property value\n * → Possibly evaluated paint property value\n * → Fully evaluated paint property value\n *\n * Layout property value\n * → Possibly evaluated layout property value\n * → Fully evaluated layout property value\n *\n * @module\n * @private\n */\n\n/**\n * Implementations of the `Property` interface:\n *\n * * Hold metadata about a property that's independent of any specific value: stuff like the type of the value,\n * the default value, etc. This comes from the style specification JSON.\n * * Define behavior that needs to be polymorphic across different properties: \"possibly evaluating\"\n * an input value (see below), and interpolating between two possibly-evaluted values.\n *\n * The type `T` is the fully-evaluated value type (e.g. `number`, `string`, `Color`).\n * The type `R` is the intermediate \"possibly evaluated\" value type. See below.\n *\n * There are two main implementations of the interface -- one for properties that allow data-driven values,\n * and one for properties that don't. There are a few \"special case\" implementations as well:\n * one for `heatmap-color` and `line-gradient`, and one for `light-position`.\n *\n * @private\n */\nexport interface Property<T, R> {\n specification: StylePropertySpecification;\n possiblyEvaluate(value: PropertyValue<T, R>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array<string>): R;\n interpolate(a: R, b: R, t: number): R;\n}\n\n/**\n * `PropertyValue` represents the value part of a property key-value unit. It's used to represent both\n * paint and layout property values, and regardless of whether or not their property supports data-driven\n * expressions.\n *\n * `PropertyValue` stores the raw input value as seen in a style or a runtime styling API call, i.e. one of the\n * following:\n *\n * * A constant value of the type appropriate for the property\n * * A function which produces a value of that type (but functions are quasi-deprecated in favor of expressions)\n * * An expression which produces a value of that type\n * * \"undefined\"/\"not present\", in which case the property is assumed to take on its default value.\n *\n * In addition to storing the original input value, `PropertyValue` also stores a normalized representation,\n * effectively treating functions as if they are expressions, and constant or default values as if they are\n * (constant) expressions.\n *\n * @private\n */\nexport class PropertyValue<T, R> {\n property: Property<T, R>;\n value: PropertyValueSpecification<T> | void;\n expression: StylePropertyExpression;\n\n constructor(property: Property<T, R>, value: PropertyValueSpecification<T> | void) {\n this.property = property;\n this.value = value;\n this.expression = normalizePropertyExpression(value === undefined ? property.specification.default : value, property.specification);\n }\n\n isDataDriven(): boolean {\n return this.expression.kind === 'source' || this.expression.kind === 'composite';\n }\n\n possiblyEvaluate(parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array<string>): R {\n return this.property.possiblyEvaluate(this, parameters, canonical, availableImages);\n }\n}\n\n// ------- Transitionable -------\n\nexport type TransitionParameters = interface {\n now: TimePoint,\n transition: TransitionSpecification,\n};\n\n/**\n * Paint properties are _transitionable_: they can change in a fluid manner, interpolating or cross-fading between\n * old and new value. The duration of the transition, and the delay before it begins, is configurable.\n *\n * `TransitionablePropertyValue` is a compositional class that stores both the property value and that transition\n * configuration.\n *\n * A `TransitionablePropertyValue` can calculate the next step in the evaluation chain for paint property values:\n * `TransitioningPropertyValue`.\n *\n * @private\n */\nclass TransitionablePropertyValue<T, R> {\n property: Property<T, R>;\n value: PropertyValue<T, R>;\n transition: TransitionSpecification | void;\n\n constructor(property: Property<T, R>) {\n this.property = property;\n this.value = new PropertyValue(property, undefined);\n }\n\n transitioned(parameters: TransitionParameters,\n prior: TransitioningPropertyValue<T, R>): TransitioningPropertyValue<T, R> {\n return new TransitioningPropertyValue(this.property, this.value, prior, // eslint-disable-line no-use-before-define\n extend({}, parameters.transition, this.transition), parameters.now);\n }\n\n untransitioned(): TransitioningPropertyValue<T, R> {\n return new TransitioningPropertyValue(this.property, this.value, null, {}, 0); // eslint-disable-line no-use-before-define\n }\n}\n\n/**\n * A helper type: given an object type `Properties` whose values are each of type `Property<T, R>`, it calculates\n * an object type with the same keys and values of type `TransitionablePropertyValue<T, R>`.\n *\n * @private\n */\ntype TransitionablePropertyValues<Props: Object>\n = $Exact<$ObjMap<Props, <T, R>(p: Property<T, R>) => TransitionablePropertyValue<T, R>>>\n\n/**\n * `Transitionable` stores a map of all (property name, `TransitionablePropertyValue`) pairs for paint properties of a\n * given layer type. It can calculate the `TransitioningPropertyValue`s for all of them at once, producing a\n * `Transitioning` instance for the same set of properties.\n *\n * @private\n */\nexport class Transitionable<Props: Object> {\n _properties: Properties<Props>;\n _values: TransitionablePropertyValues<Props>;\n\n constructor(properties: Properties<Props>) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultTransitionablePropertyValues): any);\n }\n\n getValue<S: string, T>(name: S): PropertyValueSpecification<T> | void {\n return clone(this._values[name].value.value);\n }\n\n setValue<S: string, T>(name: S, value: PropertyValueSpecification<T> | void) {\n if (!this._values.hasOwnProperty(name)) {\n this._values[name] = new TransitionablePropertyValue(this._values[name].property);\n }\n // Note that we do not _remove_ an own property in the case where a value is being reset\n // to the default: the transition might still be non-default.\n this._values[name].value = new PropertyValue(this._values[name].property, value === null ? undefined : clone(value));\n }\n\n getTransition<S: string>(name: S): TransitionSpecification | void {\n return clone(this._values[name].transition);\n }\n\n setTransition<S: string>(name: S, value: TransitionSpecification | void) {\n if (!this._values.hasOwnProperty(name)) {\n this._values[name] = new TransitionablePropertyValue(this._values[name].property);\n }\n this._values[name].transition = clone(value) || undefined;\n }\n\n serialize(): PropertyValueSpecifications<Props> {\n const result: Object = {};\n for (const property of Object.keys(this._values)) {\n const value = this.getValue(property);\n if (value !== undefined) {\n result[property] = value;\n }\n\n const transition = this.getTransition(property);\n if (transition !== undefined) {\n result[`${property}-transition`] = transition;\n }\n }\n return result;\n }\n\n transitioned(parameters: TransitionParameters, prior: Transitioning<Props>): Transitioning<Props> {\n const result = new Transitioning(this._properties); // eslint-disable-line no-use-before-define\n for (const property of Object.keys(this._values)) {\n result._values[property] = this._values[property].transitioned(parameters, prior._values[property]);\n }\n return result;\n }\n\n untransitioned(): Transitioning<Props> {\n const result = new Transitioning(this._properties); // eslint-disable-line no-use-before-define\n for (const property of Object.keys(this._values)) {\n result._values[property] = this._values[property].untransitioned();\n }\n return result;\n }\n}\n\n// ------- Transitioning -------\n\n/**\n * `TransitioningPropertyValue` implements the first of two intermediate steps in the evaluation chain of a paint\n * property value. In this step, transitions between old and new values are handled: as long as the transition is in\n * progress, `TransitioningPropertyValue` maintains a reference to the prior value, and interpolates between it and\n * the new value based on the current time and the configured transition duration and delay. The product is the next\n * step in the evaluation chain: the \"possibly evaluated\" result type `R`. See below for more on this concept.\n *\n * @private\n */\nclass TransitioningPropertyValue<T, R> {\n property: Property<T, R>;\n value: PropertyValue<T, R>;\n prior: ?TransitioningPropertyValue<T, R>;\n begin: TimePoint;\n end: TimePoint;\n\n constructor(property: Property<T, R>,\n value: PropertyValue<T, R>,\n prior: ?TransitioningPropertyValue<T, R>,\n transition: TransitionSpecification,\n now: TimePoint) {\n const delay = transition.delay || 0;\n const duration = transition.duration || 0;\n now = now || 0;\n this.property = property;\n this.value = value;\n this.begin = now + delay;\n this.end = this.begin + duration;\n if (property.specification.transition && (transition.delay || transition.duration)) {\n this.prior = prior;\n }\n }\n\n possiblyEvaluate(parameters: EvaluationParameters, canonical: CanonicalTileID, availableImages: Array<string>): R {\n const now = parameters.now || 0;\n const finalValue = this.value.possiblyEvaluate(parameters, canonical, availableImages);\n const prior = this.prior;\n if (!prior) {\n // No prior value.\n return finalValue;\n } else if (now > this.end) {\n // Transition from prior value is now complete.\n this.prior = null;\n return finalValue;\n } else if (this.value.isDataDriven()) {\n // Transitions to data-driven properties are not supported.\n // We snap immediately to the data-driven value so that, when we perform layout,\n // we see the data-driven function and can use it to populate vertex buffers.\n this.prior = null;\n return finalValue;\n } else if (now < this.begin) {\n // Transition hasn't started yet.\n return prior.possiblyEvaluate(parameters, canonical, availableImages);\n } else {\n // Interpolate between recursively-calculated prior value and final.\n const t = (now - this.begin) / (this.end - this.begin);\n return this.property.interpolate(prior.possiblyEvaluate(parameters, canonical, availableImages), finalValue, easeCubicInOut(t));\n }\n }\n}\n\n/**\n * A helper type: given an object type `Properties` whose values are each of type `Property<T, R>`, it calculates\n * an object type with the same keys and values of type `TransitioningPropertyValue<T, R>`.\n *\n * @private\n */\ntype TransitioningPropertyValues<Props: Object>\n = $Exact<$ObjMap<Props, <T, R>(p: Property<T, R>) => TransitioningPropertyValue<T, R>>>\n\n/**\n * `Transitioning` stores a map of all (property name, `TransitioningPropertyValue`) pairs for paint properties of a\n * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a\n * `PossiblyEvaluated` instance for the same set of properties.\n *\n * @private\n */\nexport class Transitioning<Props: Object> {\n _properties: Properties<Props>;\n _values: TransitioningPropertyValues<Props>;\n\n constructor(properties: Properties<Props>) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultTransitioningPropertyValues): any);\n }\n\n possiblyEvaluate(parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array<string>): PossiblyEvaluated<Props> {\n const result = new PossiblyEvaluated(this._properties); // eslint-disable-line no-use-before-define\n for (const property of Object.keys(this._values)) {\n result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages);\n }\n return result;\n }\n\n hasTransition(): boolean {\n for (const property of Object.keys(this._values)) {\n if (this._values[property].prior) {\n return true;\n }\n }\n return false;\n }\n}\n\n// ------- Layout -------\n\n/**\n * A helper type: given an object type `Properties` whose values are each of type `Property<T, R>`, it calculates\n * an object type with the same keys and values of type `PropertyValue<T, R>`.\n *\n * @private\n */\ntype PropertyValues<Props: Object>\n = $Exact<$ObjMap<Props, <T, R>(p: Property<T, R>) => PropertyValue<T, R>>>\n\n/**\n * A helper type: given an object type `Properties` whose values are each of type `Property<T, R>`, it calculates\n * an object type with the same keys and values of type `PropertyValueSpecification<T>`.\n *\n * @private\n */\ntype PropertyValueSpecifications<Props: Object>\n = $Exact<$ObjMap<Props, <T, R>(p: Property<T, R>) => PropertyValueSpecification<T>>>\n\n/**\n * Because layout properties are not transitionable, they have a simpler representation and evaluation chain than\n * paint properties: `PropertyValue`s are possibly evaluated, producing possibly evaluated values, which are then\n * fully evaluated.\n *\n * `Layout` stores a map of all (property name, `PropertyValue`) pairs for layout properties of a\n * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a\n * `PossiblyEvaluated` instance for the same set of properties.\n *\n * @private\n */\nexport class Layout<Props: Object> {\n _properties: Properties<Props>;\n _values: PropertyValues<Props>;\n\n constructor(properties: Properties<Props>) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultPropertyValues): any);\n }\n\n getValue<S: string, T>(name: S): PropertyValueSpecification<T> | void {\n return clone(this._values[name].value);\n }\n\n setValue<S: string>(name: S, value: any) {\n this._values[name] = new PropertyValue(this._values[name].property, value === null ? undefined : clone(value));\n }\n\n serialize(): PropertyValueSpecifications<Props> {\n const result: Object = {};\n for (const property of Object.keys(this._values)) {\n const value = this.getValue(property);\n if (value !== undefined) {\n result[property] = value;\n }\n }\n return result;\n }\n\n possiblyEvaluate(parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array<string>): PossiblyEvaluated<Props> {\n const result = new PossiblyEvaluated(this._properties); // eslint-disable-line no-use-before-define\n for (const property of Object.keys(this._values)) {\n result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages);\n }\n return result;\n }\n}\n\n// ------- PossiblyEvaluated -------\n\n/**\n * \"Possibly evaluated value\" is an intermediate stage in the evaluation chain for both paint and layout property\n * values. The purpose of this stage is to optimize away unnecessary recalculations for data-driven properties. Code\n * which uses data-driven property values must assume that the value is dependent on feature data, and request that it\n * be evaluated for each feature. But when that property value is in fact a constant or camera function, the calculation\n * will not actually depend on the feature, and we can benefit from returning the prior result of having done the\n * evaluation once, ahead of time, in an intermediate step whose inputs are just the value and \"global\" parameters\n * such as current zoom level.\n *\n * `PossiblyEvaluatedValue` represents the three possible outcomes of this step: if the input value was a constant or\n * camera expression, then the \"possibly evaluated\" result is a constant value. Otherwise, the input value was either\n * a source or composite expression, and we must defer final evaluation until supplied a feature. We separate\n * the source and composite cases because they are handled differently when generating GL attributes, buffers, and\n * uniforms.\n *\n * Note that `PossiblyEvaluatedValue` (and `PossiblyEvaluatedPropertyValue`, below) are _not_ used for properties that\n * do not allow data-driven values. For such properties, we know that the \"possibly evaluated\" result is always a constant\n * scalar value. See below.\n *\n * @private\n */\nexport type PossiblyEvaluatedValue<T> =\n | {kind: 'constant', value: T}\n | SourceExpression\n | CompositeExpression;\n\n/**\n * `PossiblyEvaluatedPropertyValue` is used for data-driven paint and layout property values. It holds a\n * `PossiblyEvaluatedValue` and the `GlobalProperties` that were used to generate it. You're not allowed to supply\n * a different set of `GlobalProperties` when performing the final evaluation because they would be ignored in the\n * case where the input value was a constant or camera function.\n *\n * @private\n */\nexport class PossiblyEvaluatedPropertyValue<T> {\n property: DataDrivenProperty<T>;\n value: PossiblyEvaluatedValue<T>;\n parameters: EvaluationParameters;\n\n constructor(property: DataDrivenProperty<T>, value: PossiblyEvaluatedValue<T>, parameters: EvaluationParameters) {\n this.property = property;\n this.value = value;\n this.parameters = parameters;\n }\n\n isConstant(): boolean {\n return this.value.kind === 'constant';\n }\n\n constantOr(value: T): T {\n if (this.value.kind === 'constant') {\n return this.value.value;\n } else {\n return value;\n }\n }\n\n evaluate(feature: Feature, featureState: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>): T {\n return this.property.evaluate(this.value, this.parameters, feature, featureState, canonical, availableImages);\n }\n}\n\n/**\n * A helper type: given an object type `Properties` whose values are each of type `Property<T, R>`, it calculates\n * an object type with the same keys, and values of type `R`.\n *\n * For properties that don't allow data-driven values, `R` is a scalar type such as `number`, `string`, or `Color`.\n * For data-driven properties, it is `PossiblyEvaluatedPropertyValue`. Critically, the type definitions are set up\n * in a way that allows flow to know which of these two cases applies for any given property name, and if you attempt\n * to use a `PossiblyEvaluatedPropertyValue` as if it was a scalar, or vice versa, you will get a type error. (However,\n * there's at least one case in which flow fails to produce a type error that you should be aware of: in a context such\n * as `layer.paint.get('foo-opacity') === 0`, if `foo-opacity` is data-driven, than the left-hand side is of type\n * `PossiblyEvaluatedPropertyValue<number>`, but flow will not complain about comparing this to a number using `===`.\n * See https://github.com/facebook/flow/issues/2359.)\n *\n * @private\n */\ntype PossiblyEvaluatedPropertyValues<Props: Object>\n = $Exact<$ObjMap<Props, <T, R>(p: Property<T, R>) => R>>\n\n/**\n * `PossiblyEvaluated` stores a map of all (property name, `R`) pairs for paint or layout properties of a\n * given layer type.\n * @private\n */\nexport class PossiblyEvaluated<Props: Object> {\n _properties: Properties<Props>;\n _values: PossiblyEvaluatedPropertyValues<Props>;\n\n constructor(properties: Properties<Props>) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultPossiblyEvaluatedValues): any);\n }\n\n get<S: string>(name: S): $ElementType<PossiblyEvaluatedPropertyValues<Props>, S> {\n return this._values[name];\n }\n}\n\n/**\n * An implementation of `Property` for properties that do not permit data-driven (source or composite) expressions.\n * This restriction allows us to declare statically that the result of possibly evaluating this kind of property\n * is in fact always the scalar type `T`, and can be used without further evaluating the value on a per-feature basis.\n *\n * @private\n */\nexport class DataConstantProperty<T> implements Property<T, T> {\n specification: StylePropertySpecification;\n\n constructor(specification: StylePropertySpecification) {\n this.specification = specification;\n }\n\n possiblyEvaluate(value: PropertyValue<T, T>, parameters: EvaluationParameters): T {\n assert(!value.isDataDriven());\n // $FlowFixMe[method-unbinding]\n return value.expression.evaluate(parameters);\n }\n\n interpolate(a: T, b: T, t: number): T {\n const interp: ?(a: T, b: T, t: number) => T = (interpolate: any)[this.specification.type];\n if (interp) {\n return interp(a, b, t);\n } else {\n return a;\n }\n }\n}\n\n/**\n * An implementation of `Property` for properties that permit data-driven (source or composite) expressions.\n * The result of possibly evaluating this kind of property is `PossiblyEvaluatedPropertyValue<T>`; obtaining\n * a scalar value `T` requires further evaluation on a per-feature basis.\n *\n * @private\n */\nexport class DataDrivenProperty<T> implements Property<T, PossiblyEvaluatedPropertyValue<T>> {\n specification: StylePropertySpecification;\n overrides: ?Object;\n useIntegerZoom: ?boolean;\n\n constructor(specification: StylePropertySpecification, overrides?: Object) {\n this.specification = specification;\n this.overrides = overrides;\n }\n\n possiblyEvaluate(value: PropertyValue<T, PossiblyEvaluatedPropertyValue<T>>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array<string>): PossiblyEvaluatedPropertyValue<T> {\n if (value.expression.kind === 'constant' || value.expression.kind === 'camera') {\n // $FlowFixMe[method-unbinding]\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: value.expression.evaluate(parameters, (null: any), {}, canonical, availableImages)}, parameters);\n } else {\n return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters);\n }\n }\n\n interpolate(a: PossiblyEvaluatedPropertyValue<T>,\n b: PossiblyEvaluatedPropertyValue<T>,\n t: number): PossiblyEvaluatedPropertyValue<T> {\n // If either possibly-evaluated value is non-constant, give up: we aren't able to interpolate data-driven values.\n if (a.value.kind !== 'constant' || b.value.kind !== 'constant') {\n return a;\n }\n\n // Special case hack solely for fill-outline-color. The undefined value is subsequently handled in\n // FillStyleLayer#recalculate, which sets fill-outline-color to the fill-color value if the former\n // is a PossiblyEvaluatedPropertyValue containing a constant undefined value. In addition to the\n // return value here, the other source of a PossiblyEvaluatedPropertyValue containing a constant\n // undefined value is the \"default value\" for fill-outline-color held in\n // `Properties#defaultPossiblyEvaluatedValues`, which serves as the prototype of\n // `PossiblyEvaluated#_values`.\n if (a.value.value === undefined || b.value.value === undefined) {\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: (undefined: any)}, a.parameters);\n }\n\n const interp: ?(a: T, b: T, t: number) => T = (interpolate: any)[this.specification.type];\n if (interp) {\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: interp(a.value.value, b.value.value, t)}, a.parameters);\n } else {\n return a;\n }\n }\n\n evaluate(value: PossiblyEvaluatedValue<T>, parameters: EvaluationParameters, feature: Feature, featureState: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>): T {\n if (value.kind === 'constant') {\n return value.value;\n } else {\n // $FlowFixMe[method-unbinding]\n return value.evaluate(parameters, feature, featureState, canonical, availableImages);\n }\n }\n}\n\n/**\n * An implementation of `Property` for `heatmap-color` and `line-gradient`. Interpolation is a no-op, and\n * evaluation returns a boolean value in order to indicate its presence, but the real\n * evaluation happens in StyleLayer classes.\n *\n * @private\n */\nexport class ColorRampProperty implements Property<Color, boolean> {\n specification: StylePropertySpecification;\n\n constructor(specification: StylePropertySpecification) {\n this.specification = specification;\n }\n\n possiblyEvaluate(value: PropertyValue<Color, boolean>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array<string>): boolean {\n // $FlowFixMe[method-unbinding]\n return !!value.expression.evaluate(parameters, (null: any), {}, canonical, availableImages);\n }\n\n interpolate(): boolean { return false; }\n}\n\n/**\n * `Properties` holds objects containing default values for the layout or paint property set of a given\n * layer type. These objects are immutable, and they are used as the prototypes for the `_values` members of\n * `Transitionable`, `Transitioning`, `Layout`, and `PossiblyEvaluated`. This allows these classes to avoid\n * doing work in the common case where a property has no explicit value set and should be considered to take\n * on the default value: using `for (const property of Object.keys(this._values))`, they can iterate over\n * only the _own_ properties of `_values`, skipping repeated calculation of transitions and possible/final\n * evaluations for defaults, the result of which will always be the same.\n *\n * @private\n */\nexport class Properties<Props: Object> {\n properties: Props;\n defaultPropertyValues: PropertyValues<Props>;\n defaultTransitionablePropertyValues: TransitionablePropertyValues<Props>;\n defaultTransitioningPropertyValues: TransitioningPropertyValues<Props>;\n defaultPossiblyEvaluatedValues: PossiblyEvaluatedPropertyValues<Props>;\n overridableProperties: Array<string>;\n\n constructor(properties: Props) {\n this.properties = properties;\n this.defaultPropertyValues = ({}: any);\n this.defaultTransitionablePropertyValues = ({}: any);\n this.defaultTransitioningPropertyValues = ({}: any);\n this.defaultPossiblyEvaluatedValues = ({}: any);\n this.overridableProperties = ([]: any);\n\n const defaultParameters = new EvaluationParameters(0, {});\n for (const property in properties) {\n const prop = properties[property];\n if (prop.specification.overridable) {\n this.overridableProperties.push(property);\n }\n const defaultPropertyValue = this.defaultPropertyValues[property] =\n new PropertyValue(prop, undefined);\n const defaultTransitionablePropertyValue = this.defaultTransitionablePropertyValues[property] =\n new TransitionablePropertyValue(prop);\n this.defaultTransitioningPropertyValues[property] =\n defaultTransitionablePropertyValue.untransitioned();\n this.defaultPossiblyEvaluatedValues[property] =\n defaultPropertyValue.possiblyEvaluate(defaultParameters);\n }\n }\n}\n\nregister(DataDrivenProperty, 'DataDrivenProperty');\nregister(DataConstantProperty, 'DataConstantProperty');\nregister(ColorRampProperty, 'ColorRampProperty');\n","// @flow\n\nimport {clamp} from '../util/util.js';\n\n/**\n * Packs two numbers, interpreted as 8-bit unsigned integers, into a single\n * float. Unpack them in the shader using the `unpack_float()` function,\n * defined in _prelude.vertex.glsl\n *\n * @private\n */\nexport function packUint8ToFloat(a: number, b: number): number {\n // coerce a and b to 8-bit ints\n a = clamp(Math.floor(a), 0, 255);\n b = clamp(Math.floor(b), 0, 255);\n return 256 * a + b;\n}\n","// @flow\n\n// Note: all \"sizes\" are measured in bytes\n\nimport assert from 'assert';\n\nimport type {Transferable} from '../types/transferable.js';\n\nconst viewTypes = {\n 'Int8': Int8Array,\n 'Uint8': Uint8Array,\n 'Int16': Int16Array,\n 'Uint16': Uint16Array,\n 'Int32': Int32Array,\n 'Uint32': Uint32Array,\n 'Float32': Float32Array\n};\n\nexport type ViewType = $Keys<typeof viewTypes>;\n\n/**\n * @private\n */\nclass Struct {\n // When reading the ArrayBuffer as an array of different data types, arrays have different length\n // depending on data type size. So to acess the same position,\n // we need to read different indexes depending on array data size.\n // _pos1 is the index reading an array with 1 byte data,\n // _pos2 is reading 2 byte data, and so forth.\n _pos1: number;\n _pos2: number;\n _pos4: number;\n _pos8: number;\n +_structArray: StructArray;\n\n // The following properties are defined on the prototype of sub classes.\n size: number;\n\n /**\n * @param {StructArray} structArray The StructArray the struct is stored in\n * @param {number} index The index of the struct in the StructArray.\n * @private\n */\n constructor(structArray: StructArray, index: number) {\n (this: any)._structArray = structArray;\n this._pos1 = index * this.size;\n this._pos2 = this._pos1 / 2;\n this._pos4 = this._pos1 / 4;\n this._pos8 = this._pos1 / 8;\n }\n}\n\nconst DEFAULT_CAPACITY = 128;\nconst RESIZE_MULTIPLIER = 5;\n\nexport type StructArrayMember = {\n name: string,\n type: ViewType,\n components: number,\n offset: number\n};\n\nexport type StructArrayLayout = {\n members: Array<StructArrayMember>,\n size: number,\n alignment: ?number\n}\n\nexport type SerializedStructArray = {\n length: number,\n arrayBuffer: ArrayBuffer\n};\n\n/**\n * `StructArray` provides an abstraction over `ArrayBuffer` and `TypedArray`\n * making it behave like an array of typed structs.\n *\n * Conceptually, a StructArray is comprised of elements, i.e., instances of its\n * associated struct type. Each particular struct type, together with an\n * alignment size, determines the memory layout of a StructArray whose elements\n * are of that type. Thus, for each such layout that we need, we have\n * a corrseponding StructArrayLayout class, inheriting from StructArray and\n * implementing `emplaceBack()` and `_refreshViews()`.\n *\n * In some cases, where we need to access particular elements of a StructArray,\n * we implement a more specific subclass that inherits from one of the\n * StructArrayLayouts and adds a `get(i): T` accessor that returns a structured\n * object whose properties are proxies into the underlying memory space for the\n * i-th element. This affords the convience of working with (seemingly) plain\n * Javascript objects without the overhead of serializing/deserializing them\n * into ArrayBuffers for efficient web worker transfer.\n *\n * @private\n */\nclass StructArray {\n capacity: number;\n length: number;\n isTransferred: boolean;\n arrayBuffer: ArrayBuffer;\n uint8: Uint8Array;\n\n // The following properties are defined on the prototype.\n members: Array<StructArrayMember>;\n bytesPerElement: number;\n +emplaceBack: Function;\n +emplace: Function;\n\n constructor() {\n this.isTransferred = false;\n this.capacity = -1;\n this.resize(0);\n }\n\n /**\n * Serialize a StructArray instance. Serializes both the raw data and the\n * metadata needed to reconstruct the StructArray base class during\n * deserialization.\n * @private\n */\n static serialize(array: StructArray, transferables?: Array<Transferable>): SerializedStructArray {\n assert(!array.isTransferred);\n\n array._trim();\n\n if (transferables) {\n array.isTransferred = true;\n transferables.push(array.arrayBuffer);\n }\n\n return {\n length: array.length,\n arrayBuffer: array.arrayBuffer,\n };\n }\n\n static deserialize(input: SerializedStructArray): StructArray {\n // $FlowFixMe not-an-object - newer Flow doesn't understand this pattern, silence for now\n const structArray: {[_: string]: any} = Object.create(this.prototype);\n structArray.arrayBuffer = input.arrayBuffer;\n structArray.length = input.length;\n structArray.capacity = input.arrayBuffer.byteLength / structArray.bytesPerElement;\n structArray._refreshViews();\n return ((structArray: any): StructArray);\n }\n\n /**\n * Resize the array to discard unused capacity.\n */\n _trim() {\n if (this.length !== this.capacity) {\n this.capacity = this.length;\n this.arrayBuffer = this.arrayBuffer.slice(0, this.length * this.bytesPerElement);\n this._refreshViews();\n }\n }\n\n /**\n * Resets the the length of the array to 0 without de-allocating capcacity.\n */\n clear() {\n this.length = 0;\n }\n\n /**\n * Resize the array.\n * If `n` is greater than the current length then additional elements with undefined values are added.\n * If `n` is less than the current length then the array will be reduced to the first `n` elements.\n * @param {number} n The new size of the array.\n */\n resize(n: number) {\n assert(!this.isTransferred);\n this.reserve(n);\n this.length = n;\n }\n\n /**\n * Indicate a planned increase in size, so that any necessary allocation may\n * be done once, ahead of time.\n * @param {number} n The expected size of the array.\n */\n reserve(n: number) {\n if (n > this.capacity) {\n this.capacity = Math.max(n, Math.floor(this.capacity * RESIZE_MULTIPLIER), DEFAULT_CAPACITY);\n this.arrayBuffer = new ArrayBuffer(this.capacity * this.bytesPerElement);\n\n const oldUint8Array = this.uint8;\n this._refreshViews();\n if (oldUint8Array) this.uint8.set(oldUint8Array);\n }\n }\n\n /**\n * Create TypedArray views for the current ArrayBuffer.\n */\n _refreshViews(): void {\n throw new Error('_refreshViews() must be implemented by each concrete StructArray layout');\n }\n\n destroy() {\n // $FlowFixMe\n this.int8 = this.uint8 = this.int16 = this.uint16 = this.int32 = this.uint32 = this.float32 = null;\n this.arrayBuffer = (null: any);\n }\n}\n\n/**\n * Given a list of member fields, create a full StructArrayLayout, in\n * particular calculating the correct byte offset for each field. This data\n * is used at build time to generate StructArrayLayout_*#emplaceBack() and\n * other accessors, and at runtime for binding vertex buffer attributes.\n *\n * @private\n */\nfunction createLayout(\n members: Array<{ name: string, type: ViewType, +components?: number, }>,\n alignment: number = 1\n): StructArrayLayout {\n\n let offset = 0;\n let maxSize = 0;\n const layoutMembers = members.map((member) => {\n assert(member.name.length);\n const typeSize = sizeOf(member.type);\n const memberOffset = offset = align(offset, Math.max(alignment, typeSize));\n const components = member.components || 1;\n\n maxSize = Math.max(maxSize, typeSize);\n offset += typeSize * components;\n\n return {\n name: member.name,\n type: member.type,\n components,\n offset: memberOffset,\n };\n });\n\n const size = align(offset, Math.max(maxSize, alignment));\n\n return {\n members: layoutMembers,\n size,\n alignment\n };\n}\n\nfunction sizeOf(type: ViewType): number {\n return viewTypes[type].BYTES_PER_ELEMENT;\n}\n\nfunction align(offset: number, size: number): number {\n return Math.ceil(offset / size) * size;\n}\n\nexport {StructArray, Struct, viewTypes, createLayout};\n","// This file is generated. Edit build/generate-struct-arrays.js, then run `yarn run codegen`.\n/* eslint-disable camelcase */\n// @flow\n\nimport assert from 'assert';\nimport {Struct, StructArray} from '../util/struct_array.js';\nimport {register} from '../util/web_worker_transfer.js';\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[2]\n *\n * @private\n */\nclass StructArrayLayout2i4 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1);\n }\n\n emplace(i: number, v0: number, v1: number): number {\n const o2 = i * 2;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n return i;\n }\n}\n\nStructArrayLayout2i4.prototype.bytesPerElement = 4;\nregister(StructArrayLayout2i4, 'StructArrayLayout2i4');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[3]\n *\n * @private\n */\nclass StructArrayLayout3i6 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number): number {\n const o2 = i * 3;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n return i;\n }\n}\n\nStructArrayLayout3i6.prototype.bytesPerElement = 6;\nregister(StructArrayLayout3i6, 'StructArrayLayout3i6');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[4]\n *\n * @private\n */\nclass StructArrayLayout4i8 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number): number {\n const o2 = i * 4;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n this.int16[o2 + 3] = v3;\n return i;\n }\n}\n\nStructArrayLayout4i8.prototype.bytesPerElement = 8;\nregister(StructArrayLayout4i8, 'StructArrayLayout4i8');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[2]\n * [4]: Uint8[4]\n * [8]: Float32[1]\n *\n * @private\n */\nclass StructArrayLayout2i4ub1f12 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number): number {\n const o2 = i * 6;\n const o1 = i * 12;\n const o4 = i * 3;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.uint8[o1 + 4] = v2;\n this.uint8[o1 + 5] = v3;\n this.uint8[o1 + 6] = v4;\n this.uint8[o1 + 7] = v5;\n this.float32[o4 + 2] = v6;\n return i;\n }\n}\n\nStructArrayLayout2i4ub1f12.prototype.bytesPerElement = 12;\nregister(StructArrayLayout2i4ub1f12, 'StructArrayLayout2i4ub1f12');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Float32[4]\n *\n * @private\n */\nclass StructArrayLayout4f16 extends StructArray {\n uint8: Uint8Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number): number {\n const o4 = i * 4;\n this.float32[o4 + 0] = v0;\n this.float32[o4 + 1] = v1;\n this.float32[o4 + 2] = v2;\n this.float32[o4 + 3] = v3;\n return i;\n }\n}\n\nStructArrayLayout4f16.prototype.bytesPerElement = 16;\nregister(StructArrayLayout4f16, 'StructArrayLayout4f16');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Uint16[4]\n * [8]: Float32[1]\n *\n * @private\n */\nclass StructArrayLayout4ui1f12 extends StructArray {\n uint8: Uint8Array;\n uint16: Uint16Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number): number {\n const o2 = i * 6;\n const o4 = i * 3;\n this.uint16[o2 + 0] = v0;\n this.uint16[o2 + 1] = v1;\n this.uint16[o2 + 2] = v2;\n this.uint16[o2 + 3] = v3;\n this.float32[o4 + 2] = v4;\n return i;\n }\n}\n\nStructArrayLayout4ui1f12.prototype.bytesPerElement = 12;\nregister(StructArrayLayout4ui1f12, 'StructArrayLayout4ui1f12');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Uint16[4]\n *\n * @private\n */\nclass StructArrayLayout4ui8 extends StructArray {\n uint8: Uint8Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number): number {\n const o2 = i * 4;\n this.uint16[o2 + 0] = v0;\n this.uint16[o2 + 1] = v1;\n this.uint16[o2 + 2] = v2;\n this.uint16[o2 + 3] = v3;\n return i;\n }\n}\n\nStructArrayLayout4ui8.prototype.bytesPerElement = 8;\nregister(StructArrayLayout4ui8, 'StructArrayLayout4ui8');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[6]\n *\n * @private\n */\nclass StructArrayLayout6i12 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number {\n const o2 = i * 6;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n this.int16[o2 + 3] = v3;\n this.int16[o2 + 4] = v4;\n this.int16[o2 + 5] = v5;\n return i;\n }\n}\n\nStructArrayLayout6i12.prototype.bytesPerElement = 12;\nregister(StructArrayLayout6i12, 'StructArrayLayout6i12');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[4]\n * [8]: Uint16[4]\n * [16]: Int16[4]\n *\n * @private\n */\nclass StructArrayLayout4i4ui4i24 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number): number {\n const o2 = i * 12;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n this.int16[o2 + 3] = v3;\n this.uint16[o2 + 4] = v4;\n this.uint16[o2 + 5] = v5;\n this.uint16[o2 + 6] = v6;\n this.uint16[o2 + 7] = v7;\n this.int16[o2 + 8] = v8;\n this.int16[o2 + 9] = v9;\n this.int16[o2 + 10] = v10;\n this.int16[o2 + 11] = v11;\n return i;\n }\n}\n\nStructArrayLayout4i4ui4i24.prototype.bytesPerElement = 24;\nregister(StructArrayLayout4i4ui4i24, 'StructArrayLayout4i4ui4i24');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[3]\n * [8]: Float32[3]\n *\n * @private\n */\nclass StructArrayLayout3i3f20 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number): number {\n const o2 = i * 10;\n const o4 = i * 5;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n this.float32[o4 + 2] = v3;\n this.float32[o4 + 3] = v4;\n this.float32[o4 + 4] = v5;\n return i;\n }\n}\n\nStructArrayLayout3i3f20.prototype.bytesPerElement = 20;\nregister(StructArrayLayout3i3f20, 'StructArrayLayout3i3f20');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Uint32[1]\n *\n * @private\n */\nclass StructArrayLayout1ul4 extends StructArray {\n uint8: Uint8Array;\n uint32: Uint32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint32 = new Uint32Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0);\n }\n\n emplace(i: number, v0: number): number {\n const o4 = i * 1;\n this.uint32[o4 + 0] = v0;\n return i;\n }\n}\n\nStructArrayLayout1ul4.prototype.bytesPerElement = 4;\nregister(StructArrayLayout1ul4, 'StructArrayLayout1ul4');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[5]\n * [12]: Float32[4]\n * [28]: Int16[1]\n * [32]: Uint32[1]\n * [36]: Uint16[2]\n *\n * @private\n */\nclass StructArrayLayout5i4f1i1ul2ui40 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n float32: Float32Array;\n uint32: Uint32Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n this.uint32 = new Uint32Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number): number {\n const o2 = i * 20;\n const o4 = i * 10;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n this.int16[o2 + 3] = v3;\n this.int16[o2 + 4] = v4;\n this.float32[o4 + 3] = v5;\n this.float32[o4 + 4] = v6;\n this.float32[o4 + 5] = v7;\n this.float32[o4 + 6] = v8;\n this.int16[o2 + 14] = v9;\n this.uint32[o4 + 8] = v10;\n this.uint16[o2 + 18] = v11;\n this.uint16[o2 + 19] = v12;\n return i;\n }\n}\n\nStructArrayLayout5i4f1i1ul2ui40.prototype.bytesPerElement = 40;\nregister(StructArrayLayout5i4f1i1ul2ui40, 'StructArrayLayout5i4f1i1ul2ui40');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[3]\n * [8]: Int16[2]\n * [12]: Int16[2]\n *\n * @private\n */\nclass StructArrayLayout3i2i2i16 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number): number {\n const o2 = i * 8;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n this.int16[o2 + 4] = v3;\n this.int16[o2 + 5] = v4;\n this.int16[o2 + 6] = v5;\n this.int16[o2 + 7] = v6;\n return i;\n }\n}\n\nStructArrayLayout3i2i2i16.prototype.bytesPerElement = 16;\nregister(StructArrayLayout3i2i2i16, 'StructArrayLayout3i2i2i16');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Float32[2]\n * [8]: Float32[1]\n * [12]: Int16[2]\n *\n * @private\n */\nclass StructArrayLayout2f1f2i16 extends StructArray {\n uint8: Uint8Array;\n float32: Float32Array;\n int16: Int16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number): number {\n const o4 = i * 4;\n const o2 = i * 8;\n this.float32[o4 + 0] = v0;\n this.float32[o4 + 1] = v1;\n this.float32[o4 + 2] = v2;\n this.int16[o2 + 6] = v3;\n this.int16[o2 + 7] = v4;\n return i;\n }\n}\n\nStructArrayLayout2f1f2i16.prototype.bytesPerElement = 16;\nregister(StructArrayLayout2f1f2i16, 'StructArrayLayout2f1f2i16');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Uint8[2]\n * [4]: Float32[2]\n *\n * @private\n */\nclass StructArrayLayout2ub2f12 extends StructArray {\n uint8: Uint8Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number): number {\n const o1 = i * 12;\n const o4 = i * 3;\n this.uint8[o1 + 0] = v0;\n this.uint8[o1 + 1] = v1;\n this.float32[o4 + 1] = v2;\n this.float32[o4 + 2] = v3;\n return i;\n }\n}\n\nStructArrayLayout2ub2f12.prototype.bytesPerElement = 12;\nregister(StructArrayLayout2ub2f12, 'StructArrayLayout2ub2f12');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Float32[3]\n *\n * @private\n */\nclass StructArrayLayout3f12 extends StructArray {\n uint8: Uint8Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number): number {\n const o4 = i * 3;\n this.float32[o4 + 0] = v0;\n this.float32[o4 + 1] = v1;\n this.float32[o4 + 2] = v2;\n return i;\n }\n}\n\nStructArrayLayout3f12.prototype.bytesPerElement = 12;\nregister(StructArrayLayout3f12, 'StructArrayLayout3f12');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Uint16[3]\n *\n * @private\n */\nclass StructArrayLayout3ui6 extends StructArray {\n uint8: Uint8Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number): number {\n const o2 = i * 3;\n this.uint16[o2 + 0] = v0;\n this.uint16[o2 + 1] = v1;\n this.uint16[o2 + 2] = v2;\n return i;\n }\n}\n\nStructArrayLayout3ui6.prototype.bytesPerElement = 6;\nregister(StructArrayLayout3ui6, 'StructArrayLayout3ui6');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[3]\n * [8]: Float32[2]\n * [16]: Uint16[2]\n * [20]: Uint32[3]\n * [32]: Uint16[3]\n * [40]: Float32[2]\n * [48]: Uint8[3]\n * [52]: Uint32[1]\n * [56]: Int16[1]\n * [58]: Uint8[1]\n *\n * @private\n */\nclass StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n float32: Float32Array;\n uint16: Uint16Array;\n uint32: Uint32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n this.uint32 = new Uint32Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, v16: number, v17: number, v18: number, v19: number, v20: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, v16: number, v17: number, v18: number, v19: number, v20: number): number {\n const o2 = i * 30;\n const o4 = i * 15;\n const o1 = i * 60;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n this.float32[o4 + 2] = v3;\n this.float32[o4 + 3] = v4;\n this.uint16[o2 + 8] = v5;\n this.uint16[o2 + 9] = v6;\n this.uint32[o4 + 5] = v7;\n this.uint32[o4 + 6] = v8;\n this.uint32[o4 + 7] = v9;\n this.uint16[o2 + 16] = v10;\n this.uint16[o2 + 17] = v11;\n this.uint16[o2 + 18] = v12;\n this.float32[o4 + 10] = v13;\n this.float32[o4 + 11] = v14;\n this.uint8[o1 + 48] = v15;\n this.uint8[o1 + 49] = v16;\n this.uint8[o1 + 50] = v17;\n this.uint32[o4 + 13] = v18;\n this.int16[o2 + 28] = v19;\n this.uint8[o1 + 58] = v20;\n return i;\n }\n}\n\nStructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60.prototype.bytesPerElement = 60;\nregister(StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60, 'StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[3]\n * [8]: Float32[2]\n * [16]: Int16[6]\n * [28]: Uint16[15]\n * [60]: Uint32[1]\n * [64]: Float32[3]\n *\n * @private\n */\nclass StructArrayLayout3i2f6i15ui1ul3f76 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n float32: Float32Array;\n uint16: Uint16Array;\n uint32: Uint32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n this.uint32 = new Uint32Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, v16: number, v17: number, v18: number, v19: number, v20: number, v21: number, v22: number, v23: number, v24: number, v25: number, v26: number, v27: number, v28: number, v29: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, v16: number, v17: number, v18: number, v19: number, v20: number, v21: number, v22: number, v23: number, v24: number, v25: number, v26: number, v27: number, v28: number, v29: number): number {\n const o2 = i * 38;\n const o4 = i * 19;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.int16[o2 + 2] = v2;\n this.float32[o4 + 2] = v3;\n this.float32[o4 + 3] = v4;\n this.int16[o2 + 8] = v5;\n this.int16[o2 + 9] = v6;\n this.int16[o2 + 10] = v7;\n this.int16[o2 + 11] = v8;\n this.int16[o2 + 12] = v9;\n this.int16[o2 + 13] = v10;\n this.uint16[o2 + 14] = v11;\n this.uint16[o2 + 15] = v12;\n this.uint16[o2 + 16] = v13;\n this.uint16[o2 + 17] = v14;\n this.uint16[o2 + 18] = v15;\n this.uint16[o2 + 19] = v16;\n this.uint16[o2 + 20] = v17;\n this.uint16[o2 + 21] = v18;\n this.uint16[o2 + 22] = v19;\n this.uint16[o2 + 23] = v20;\n this.uint16[o2 + 24] = v21;\n this.uint16[o2 + 25] = v22;\n this.uint16[o2 + 26] = v23;\n this.uint16[o2 + 27] = v24;\n this.uint16[o2 + 28] = v25;\n this.uint32[o4 + 15] = v26;\n this.float32[o4 + 16] = v27;\n this.float32[o4 + 17] = v28;\n this.float32[o4 + 18] = v29;\n return i;\n }\n}\n\nStructArrayLayout3i2f6i15ui1ul3f76.prototype.bytesPerElement = 76;\nregister(StructArrayLayout3i2f6i15ui1ul3f76, 'StructArrayLayout3i2f6i15ui1ul3f76');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Float32[1]\n *\n * @private\n */\nclass StructArrayLayout1f4 extends StructArray {\n uint8: Uint8Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0);\n }\n\n emplace(i: number, v0: number): number {\n const o4 = i * 1;\n this.float32[o4 + 0] = v0;\n return i;\n }\n}\n\nStructArrayLayout1f4.prototype.bytesPerElement = 4;\nregister(StructArrayLayout1f4, 'StructArrayLayout1f4');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Float32[5]\n *\n * @private\n */\nclass StructArrayLayout5f20 extends StructArray {\n uint8: Uint8Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number): number {\n const o4 = i * 5;\n this.float32[o4 + 0] = v0;\n this.float32[o4 + 1] = v1;\n this.float32[o4 + 2] = v2;\n this.float32[o4 + 3] = v3;\n this.float32[o4 + 4] = v4;\n return i;\n }\n}\n\nStructArrayLayout5f20.prototype.bytesPerElement = 20;\nregister(StructArrayLayout5f20, 'StructArrayLayout5f20');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Uint32[1]\n * [4]: Uint16[3]\n *\n * @private\n */\nclass StructArrayLayout1ul3ui12 extends StructArray {\n uint8: Uint8Array;\n uint32: Uint32Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint32 = new Uint32Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number): number {\n const o4 = i * 3;\n const o2 = i * 6;\n this.uint32[o4 + 0] = v0;\n this.uint16[o2 + 2] = v1;\n this.uint16[o2 + 3] = v2;\n this.uint16[o2 + 4] = v3;\n return i;\n }\n}\n\nStructArrayLayout1ul3ui12.prototype.bytesPerElement = 12;\nregister(StructArrayLayout1ul3ui12, 'StructArrayLayout1ul3ui12');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Uint16[2]\n *\n * @private\n */\nclass StructArrayLayout2ui4 extends StructArray {\n uint8: Uint8Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1);\n }\n\n emplace(i: number, v0: number, v1: number): number {\n const o2 = i * 2;\n this.uint16[o2 + 0] = v0;\n this.uint16[o2 + 1] = v1;\n return i;\n }\n}\n\nStructArrayLayout2ui4.prototype.bytesPerElement = 4;\nregister(StructArrayLayout2ui4, 'StructArrayLayout2ui4');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Uint16[1]\n *\n * @private\n */\nclass StructArrayLayout1ui2 extends StructArray {\n uint8: Uint8Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0);\n }\n\n emplace(i: number, v0: number): number {\n const o2 = i * 1;\n this.uint16[o2 + 0] = v0;\n return i;\n }\n}\n\nStructArrayLayout1ui2.prototype.bytesPerElement = 2;\nregister(StructArrayLayout1ui2, 'StructArrayLayout1ui2');\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Float32[2]\n *\n * @private\n */\nclass StructArrayLayout2f8 extends StructArray {\n uint8: Uint8Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number): number {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1);\n }\n\n emplace(i: number, v0: number, v1: number): number {\n const o4 = i * 2;\n this.float32[o4 + 0] = v0;\n this.float32[o4 + 1] = v1;\n return i;\n }\n}\n\nStructArrayLayout2f8.prototype.bytesPerElement = 8;\nregister(StructArrayLayout2f8, 'StructArrayLayout2f8');\n\nclass CollisionBoxStruct extends Struct {\n _structArray: CollisionBoxArray;\n get projectedAnchorX(): number { return this._structArray.int16[this._pos2 + 0]; }\n get projectedAnchorY(): number { return this._structArray.int16[this._pos2 + 1]; }\n get projectedAnchorZ(): number { return this._structArray.int16[this._pos2 + 2]; }\n get tileAnchorX(): number { return this._structArray.int16[this._pos2 + 3]; }\n get tileAnchorY(): number { return this._structArray.int16[this._pos2 + 4]; }\n get x1(): number { return this._structArray.float32[this._pos4 + 3]; }\n get y1(): number { return this._structArray.float32[this._pos4 + 4]; }\n get x2(): number { return this._structArray.float32[this._pos4 + 5]; }\n get y2(): number { return this._structArray.float32[this._pos4 + 6]; }\n get padding(): number { return this._structArray.int16[this._pos2 + 14]; }\n get featureIndex(): number { return this._structArray.uint32[this._pos4 + 8]; }\n get sourceLayerIndex(): number { return this._structArray.uint16[this._pos2 + 18]; }\n get bucketIndex(): number { return this._structArray.uint16[this._pos2 + 19]; }\n}\n\nCollisionBoxStruct.prototype.size = 40;\n\nexport type CollisionBox = CollisionBoxStruct;\n\n/**\n * @private\n */\nexport class CollisionBoxArray extends StructArrayLayout5i4f1i1ul2ui40 {\n /**\n * Return the CollisionBoxStruct at the given location in the array.\n * @param {number} index The index of the element.\n * @private\n */\n get(index: number): CollisionBoxStruct {\n assert(!this.isTransferred);\n assert(index >= 0);\n assert(index < this.length);\n return new CollisionBoxStruct(this, index);\n }\n}\n\nregister(CollisionBoxArray, 'CollisionBoxArray');\n\nclass PlacedSymbolStruct extends Struct {\n _structArray: PlacedSymbolArray;\n get projectedAnchorX(): number { return this._structArray.int16[this._pos2 + 0]; }\n get projectedAnchorY(): number { return this._structArray.int16[this._pos2 + 1]; }\n get projectedAnchorZ(): number { return this._structArray.int16[this._pos2 + 2]; }\n get tileAnchorX(): number { return this._structArray.float32[this._pos4 + 2]; }\n get tileAnchorY(): number { return this._structArray.float32[this._pos4 + 3]; }\n get glyphStartIndex(): number { return this._structArray.uint16[this._pos2 + 8]; }\n get numGlyphs(): number { return this._structArray.uint16[this._pos2 + 9]; }\n get vertexStartIndex(): number { return this._structArray.uint32[this._pos4 + 5]; }\n get lineStartIndex(): number { return this._structArray.uint32[this._pos4 + 6]; }\n get lineLength(): number { return this._structArray.uint32[this._pos4 + 7]; }\n get segment(): number { return this._structArray.uint16[this._pos2 + 16]; }\n get lowerSize(): number { return this._structArray.uint16[this._pos2 + 17]; }\n get upperSize(): number { return this._structArray.uint16[this._pos2 + 18]; }\n get lineOffsetX(): number { return this._structArray.float32[this._pos4 + 10]; }\n get lineOffsetY(): number { return this._structArray.float32[this._pos4 + 11]; }\n get writingMode(): number { return this._structArray.uint8[this._pos1 + 48]; }\n get placedOrientation(): number { return this._structArray.uint8[this._pos1 + 49]; }\n set placedOrientation(x: number) { this._structArray.uint8[this._pos1 + 49] = x; }\n get hidden(): number { return this._structArray.uint8[this._pos1 + 50]; }\n set hidden(x: number) { this._structArray.uint8[this._pos1 + 50] = x; }\n get crossTileID(): number { return this._structArray.uint32[this._pos4 + 13]; }\n set crossTileID(x: number) { this._structArray.uint32[this._pos4 + 13] = x; }\n get associatedIconIndex(): number { return this._structArray.int16[this._pos2 + 28]; }\n get flipState(): number { return this._structArray.uint8[this._pos1 + 58]; }\n set flipState(x: number) { this._structArray.uint8[this._pos1 + 58] = x; }\n}\n\nPlacedSymbolStruct.prototype.size = 60;\n\nexport type PlacedSymbol = PlacedSymbolStruct;\n\n/**\n * @private\n */\nexport class PlacedSymbolArray extends StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60 {\n /**\n * Return the PlacedSymbolStruct at the given location in the array.\n * @param {number} index The index of the element.\n * @private\n */\n get(index: number): PlacedSymbolStruct {\n assert(!this.isTransferred);\n assert(index >= 0);\n assert(index < this.length);\n return new PlacedSymbolStruct(this, index);\n }\n}\n\nregister(PlacedSymbolArray, 'PlacedSymbolArray');\n\nclass SymbolInstanceStruct extends Struct {\n _structArray: SymbolInstanceArray;\n get projectedAnchorX(): number { return this._structArray.int16[this._pos2 + 0]; }\n get projectedAnchorY(): number { return this._structArray.int16[this._pos2 + 1]; }\n get projectedAnchorZ(): number { return this._structArray.int16[this._pos2 + 2]; }\n get tileAnchorX(): number { return this._structArray.float32[this._pos4 + 2]; }\n get tileAnchorY(): number { return this._structArray.float32[this._pos4 + 3]; }\n get rightJustifiedTextSymbolIndex(): number { return this._structArray.int16[this._pos2 + 8]; }\n get centerJustifiedTextSymbolIndex(): number { return this._structArray.int16[this._pos2 + 9]; }\n get leftJustifiedTextSymbolIndex(): number { return this._structArray.int16[this._pos2 + 10]; }\n get verticalPlacedTextSymbolIndex(): number { return this._structArray.int16[this._pos2 + 11]; }\n get placedIconSymbolIndex(): number { return this._structArray.int16[this._pos2 + 12]; }\n get verticalPlacedIconSymbolIndex(): number { return this._structArray.int16[this._pos2 + 13]; }\n get key(): number { return this._structArray.uint16[this._pos2 + 14]; }\n get textBoxStartIndex(): number { return this._structArray.uint16[this._pos2 + 15]; }\n get textBoxEndIndex(): number { return this._structArray.uint16[this._pos2 + 16]; }\n get verticalTextBoxStartIndex(): number { return this._structArray.uint16[this._pos2 + 17]; }\n get verticalTextBoxEndIndex(): number { return this._structArray.uint16[this._pos2 + 18]; }\n get iconBoxStartIndex(): number { return this._structArray.uint16[this._pos2 + 19]; }\n get iconBoxEndIndex(): number { return this._structArray.uint16[this._pos2 + 20]; }\n get verticalIconBoxStartIndex(): number { return this._structArray.uint16[this._pos2 + 21]; }\n get verticalIconBoxEndIndex(): number { return this._structArray.uint16[this._pos2 + 22]; }\n get featureIndex(): number { return this._structArray.uint16[this._pos2 + 23]; }\n get numHorizontalGlyphVertices(): number { return this._structArray.uint16[this._pos2 + 24]; }\n get numVerticalGlyphVertices(): number { return this._structArray.uint16[this._pos2 + 25]; }\n get numIconVertices(): number { return this._structArray.uint16[this._pos2 + 26]; }\n get numVerticalIconVertices(): number { return this._structArray.uint16[this._pos2 + 27]; }\n get useRuntimeCollisionCircles(): number { return this._structArray.uint16[this._pos2 + 28]; }\n get crossTileID(): number { return this._structArray.uint32[this._pos4 + 15]; }\n set crossTileID(x: number) { this._structArray.uint32[this._pos4 + 15] = x; }\n get textOffset0(): number { return this._structArray.float32[this._pos4 + 16]; }\n get textOffset1(): number { return this._structArray.float32[this._pos4 + 17]; }\n get collisionCircleDiameter(): number { return this._structArray.float32[this._pos4 + 18]; }\n}\n\nSymbolInstanceStruct.prototype.size = 76;\n\nexport type SymbolInstance = SymbolInstanceStruct;\n\n/**\n * @private\n */\nexport class SymbolInstanceArray extends StructArrayLayout3i2f6i15ui1ul3f76 {\n /**\n * Return the SymbolInstanceStruct at the given location in the array.\n * @param {number} index The index of the element.\n * @private\n */\n get(index: number): SymbolInstanceStruct {\n assert(!this.isTransferred);\n assert(index >= 0);\n assert(index < this.length);\n return new SymbolInstanceStruct(this, index);\n }\n}\n\nregister(SymbolInstanceArray, 'SymbolInstanceArray');\n\n/**\n * @private\n */\nexport class GlyphOffsetArray extends StructArrayLayout1f4 {\n getoffsetX(index: number): number { return this.float32[index * 1 + 0]; }\n}\n\nregister(GlyphOffsetArray, 'GlyphOffsetArray');\n\n/**\n * @private\n */\nexport class SymbolLineVertexArray extends StructArrayLayout2i4 {\n getx(index: number): number { return this.int16[index * 2 + 0]; }\n gety(index: number): number { return this.int16[index * 2 + 1]; }\n}\n\nregister(SymbolLineVertexArray, 'SymbolLineVertexArray');\n\nclass FeatureIndexStruct extends Struct {\n _structArray: FeatureIndexArray;\n get featureIndex(): number { return this._structArray.uint32[this._pos4 + 0]; }\n get sourceLayerIndex(): number { return this._structArray.uint16[this._pos2 + 2]; }\n get bucketIndex(): number { return this._structArray.uint16[this._pos2 + 3]; }\n get layoutVertexArrayOffset(): number { return this._structArray.uint16[this._pos2 + 4]; }\n}\n\nFeatureIndexStruct.prototype.size = 12;\n\nexport type FeatureIndex = FeatureIndexStruct;\n\n/**\n * @private\n */\nexport class FeatureIndexArray extends StructArrayLayout1ul3ui12 {\n /**\n * Return the FeatureIndexStruct at the given location in the array.\n * @param {number} index The index of the element.\n * @private\n */\n get(index: number): FeatureIndexStruct {\n assert(!this.isTransferred);\n assert(index >= 0);\n assert(index < this.length);\n return new FeatureIndexStruct(this, index);\n }\n}\n\nregister(FeatureIndexArray, 'FeatureIndexArray');\n\n/**\n * @private\n */\nexport class FillExtrusionCentroidArray extends StructArrayLayout2ui4 {\n geta_centroid_pos0(index: number): number { return this.uint16[index * 2 + 0]; }\n geta_centroid_pos1(index: number): number { return this.uint16[index * 2 + 1]; }\n}\n\nregister(FillExtrusionCentroidArray, 'FillExtrusionCentroidArray');\n\nexport {\n StructArrayLayout2i4,\n StructArrayLayout3i6,\n StructArrayLayout4i8,\n StructArrayLayout2i4ub1f12,\n StructArrayLayout4f16,\n StructArrayLayout4ui1f12,\n StructArrayLayout4ui8,\n StructArrayLayout6i12,\n StructArrayLayout4i4ui4i24,\n StructArrayLayout3i3f20,\n StructArrayLayout1ul4,\n StructArrayLayout5i4f1i1ul2ui40,\n StructArrayLayout3i2i2i16,\n StructArrayLayout2f1f2i16,\n StructArrayLayout2ub2f12,\n StructArrayLayout3f12,\n StructArrayLayout3ui6,\n StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60,\n StructArrayLayout3i2f6i15ui1ul3f76,\n StructArrayLayout1f4,\n StructArrayLayout5f20,\n StructArrayLayout1ul3ui12,\n StructArrayLayout2ui4,\n StructArrayLayout1ui2,\n StructArrayLayout2f8,\n StructArrayLayout2i4 as PosArray,\n StructArrayLayout3i6 as PosGlobeExtArray,\n StructArrayLayout4i8 as RasterBoundsArray,\n StructArrayLayout2i4 as CircleLayoutArray,\n StructArrayLayout2i4 as FillLayoutArray,\n StructArrayLayout4i8 as FillExtrusionLayoutArray,\n StructArrayLayout2i4 as HeatmapLayoutArray,\n StructArrayLayout2i4ub1f12 as LineLayoutArray,\n StructArrayLayout4f16 as LineExtLayoutArray,\n StructArrayLayout4ui1f12 as PatternLayoutArray,\n StructArrayLayout4ui8 as DashLayoutArray,\n StructArrayLayout6i12 as FillExtrusionExtArray,\n StructArrayLayout4i4ui4i24 as SymbolLayoutArray,\n StructArrayLayout3i3f20 as SymbolGlobeExtArray,\n StructArrayLayout4f16 as SymbolDynamicLayoutArray,\n StructArrayLayout1ul4 as SymbolOpacityArray,\n StructArrayLayout3i2i2i16 as CollisionBoxLayoutArray,\n StructArrayLayout2f1f2i16 as CollisionCircleLayoutArray,\n StructArrayLayout2ub2f12 as CollisionVertexArray,\n StructArrayLayout3f12 as CollisionVertexExtArray,\n StructArrayLayout3ui6 as QuadTriangleArray,\n StructArrayLayout5f20 as GlobeVertexArray,\n StructArrayLayout5f20 as AtmosphereVertexArray,\n StructArrayLayout3ui6 as TriangleIndexArray,\n StructArrayLayout2ui4 as LineIndexArray,\n StructArrayLayout1ui2 as LineStripIndexArray,\n StructArrayLayout3f12 as SkyboxVertexArray,\n StructArrayLayout4i8 as TileBoundsArray,\n StructArrayLayout6i12 as CircleGlobeExtArray\n};\n","// @flow\nimport {createLayout} from '../../util/struct_array.js';\n\nimport type {StructArrayLayout} from '../../util/struct_array.js';\n\nconst patternAttributes: StructArrayLayout = createLayout([\n // [tl.x, tl.y, br.x, br.y]\n {name: 'a_pattern', components: 4, type: 'Uint16'},\n {name: 'a_pixel_ratio', components: 1, type: 'Float32'}\n]);\n\nexport default patternAttributes;\n","// @flow\nimport {createLayout} from '../../util/struct_array.js';\n\nimport type {StructArrayLayout} from '../../util/struct_array.js';\n\nconst dashAttributes: StructArrayLayout = createLayout([\n {name: 'a_dash', components: 4, type: 'Uint16'} // [x, y, width, unused]\n]);\n\nexport default dashAttributes;\n","/**\n * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)\n * \n * @author <a href=\"mailto:gary.court@gmail.com\">Gary Court</a>\n * @see http://github.com/garycourt/murmurhash-js\n * @author <a href=\"mailto:aappleby@gmail.com\">Austin Appleby</a>\n * @see http://sites.google.com/site/murmurhash/\n * \n * @param {string} key ASCII only\n * @param {number} seed Positive integer only\n * @return {number} 32-bit positive integer hash \n */\n\nfunction murmurhash3_32_gc(key, seed) {\n\tvar remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i;\n\t\n\tremainder = key.length & 3; // key.length % 4\n\tbytes = key.length - remainder;\n\th1 = seed;\n\tc1 = 0xcc9e2d51;\n\tc2 = 0x1b873593;\n\ti = 0;\n\t\n\twhile (i < bytes) {\n\t \tk1 = \n\t \t ((key.charCodeAt(i) & 0xff)) |\n\t \t ((key.charCodeAt(++i) & 0xff) << 8) |\n\t \t ((key.charCodeAt(++i) & 0xff) << 16) |\n\t \t ((key.charCodeAt(++i) & 0xff) << 24);\n\t\t++i;\n\t\t\n\t\tk1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;\n\t\tk1 = (k1 << 15) | (k1 >>> 17);\n\t\tk1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;\n\n\t\th1 ^= k1;\n h1 = (h1 << 13) | (h1 >>> 19);\n\t\th1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;\n\t\th1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));\n\t}\n\t\n\tk1 = 0;\n\t\n\tswitch (remainder) {\n\t\tcase 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;\n\t\tcase 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;\n\t\tcase 1: k1 ^= (key.charCodeAt(i) & 0xff);\n\t\t\n\t\tk1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;\n\t\tk1 = (k1 << 15) | (k1 >>> 17);\n\t\tk1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;\n\t\th1 ^= k1;\n\t}\n\t\n\th1 ^= key.length;\n\n\th1 ^= h1 >>> 16;\n\th1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;\n\th1 ^= h1 >>> 13;\n\th1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;\n\th1 ^= h1 >>> 16;\n\n\treturn h1 >>> 0;\n}\n\nif(typeof module !== \"undefined\") {\n module.exports = murmurhash3_32_gc\n}","/**\n * JS Implementation of MurmurHash2\n * \n * @author <a href=\"mailto:gary.court@gmail.com\">Gary Court</a>\n * @see http://github.com/garycourt/murmurhash-js\n * @author <a href=\"mailto:aappleby@gmail.com\">Austin Appleby</a>\n * @see http://sites.google.com/site/murmurhash/\n * \n * @param {string} str ASCII only\n * @param {number} seed Positive integer only\n * @return {number} 32-bit positive integer hash\n */\n\nfunction murmurhash2_32_gc(str, seed) {\n var\n l = str.length,\n h = seed ^ l,\n i = 0,\n k;\n \n while (l >= 4) {\n \tk = \n \t ((str.charCodeAt(i) & 0xff)) |\n \t ((str.charCodeAt(++i) & 0xff) << 8) |\n \t ((str.charCodeAt(++i) & 0xff) << 16) |\n \t ((str.charCodeAt(++i) & 0xff) << 24);\n \n k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n k ^= k >>> 24;\n k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n\n\th = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k;\n\n l -= 4;\n ++i;\n }\n \n switch (l) {\n case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16;\n case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8;\n case 1: h ^= (str.charCodeAt(i) & 0xff);\n h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n }\n\n h ^= h >>> 13;\n h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n h ^= h >>> 15;\n\n return h >>> 0;\n}\n\nif(typeof module !== undefined) {\n module.exports = murmurhash2_32_gc\n}\n","var murmur3 = require(\"./murmurhash3_gc.js\")\nvar murmur2 = require(\"./murmurhash2_gc.js\")\n\nmodule.exports = murmur3\nmodule.exports.murmur3 = murmur3\nmodule.exports.murmur2 = murmur2\n","// @flow\n\nimport murmur3 from 'murmurhash-js';\nimport {register} from '../util/web_worker_transfer.js';\nimport assert from 'assert';\n\ntype SerializedFeaturePositionMap = {\n ids: Float64Array;\n positions: Uint32Array;\n};\n\ntype FeaturePosition = {\n index: number;\n start: number;\n end: number;\n};\n\n// A transferable data structure that maps feature ids to their indices and buffer offsets\nexport default class FeaturePositionMap {\n ids: Array<number>;\n positions: Array<number>;\n indexed: boolean;\n\n constructor() {\n this.ids = [];\n this.positions = [];\n this.indexed = false;\n }\n\n add(id: mixed, index: number, start: number, end: number) {\n this.ids.push(getNumericId(id));\n this.positions.push(index, start, end);\n }\n\n getPositions(id: mixed): Array<FeaturePosition> {\n assert(this.indexed);\n\n const intId = getNumericId(id);\n\n // binary search for the first occurrence of id in this.ids;\n // relies on ids/positions being sorted by id, which happens in serialization\n let i = 0;\n let j = this.ids.length - 1;\n while (i < j) {\n const m = (i + j) >> 1;\n if (this.ids[m] >= intId) {\n j = m;\n } else {\n i = m + 1;\n }\n }\n const positions = [];\n while (this.ids[i] === intId) {\n const index = this.positions[3 * i];\n const start = this.positions[3 * i + 1];\n const end = this.positions[3 * i + 2];\n positions.push({index, start, end});\n i++;\n }\n return positions;\n }\n\n static serialize(map: FeaturePositionMap, transferables: Array<ArrayBuffer>): SerializedFeaturePositionMap {\n const ids = new Float64Array(map.ids);\n const positions = new Uint32Array(map.positions);\n\n sort(ids, positions, 0, ids.length - 1);\n\n if (transferables) {\n transferables.push(ids.buffer, positions.buffer);\n }\n\n return {ids, positions};\n }\n\n static deserialize(obj: SerializedFeaturePositionMap): FeaturePositionMap {\n const map = new FeaturePositionMap();\n // after transferring, we only use these arrays statically (no pushes),\n // so TypedArray vs Array distinction that flow points out doesn't matter\n map.ids = (obj.ids: any);\n map.positions = (obj.positions: any);\n map.indexed = true;\n return map;\n }\n}\n\nfunction getNumericId(value: mixed) {\n const numValue = +value;\n if (!isNaN(numValue) && Number.MIN_SAFE_INTEGER <= numValue && numValue <= Number.MAX_SAFE_INTEGER) {\n return numValue;\n }\n return murmur3(String(value));\n}\n\n// custom quicksort that sorts ids, indices and offsets together (by ids)\n// uses Hoare partitioning & manual tail call optimization to avoid worst case scenarios\nfunction sort(ids: Float64Array, positions: Uint32Array, left: number, right: number) {\n while (left < right) {\n const pivot = ids[(left + right) >> 1];\n let i = left - 1;\n let j = right + 1;\n\n while (true) {\n do i++; while (ids[i] < pivot);\n do j--; while (ids[j] > pivot);\n if (i >= j) break;\n swap(ids, i, j);\n swap(positions, 3 * i, 3 * j);\n swap(positions, 3 * i + 1, 3 * j + 1);\n swap(positions, 3 * i + 2, 3 * j + 2);\n }\n\n if (j - left < right - j) {\n sort(ids, positions, left, j);\n left = j + 1;\n } else {\n sort(ids, positions, j + 1, right);\n right = j;\n }\n }\n}\n\nfunction swap(arr: Uint32Array | Float64Array, i: number, j: number) {\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n\nregister(FeaturePositionMap, 'FeaturePositionMap');\n","// @flow\n\nimport Color from '../style-spec/util/color.js';\nimport type Context from '../gl/context.js';\n\nexport type UniformValues<Us: Object>\n = $Exact<$ObjMap<Us, <V>(u: Uniform<V>) => V>>;\n\nclass Uniform<T> {\n gl: WebGLRenderingContext;\n location: ?WebGLUniformLocation;\n current: T;\n initialized: boolean;\n\n constructor(context: Context) {\n this.gl = context.gl;\n this.initialized = false;\n }\n\n fetchUniformLocation(program: WebGLProgram, name: string): boolean {\n if (!this.location && !this.initialized) {\n this.location = this.gl.getUniformLocation(program, name);\n this.initialized = true;\n }\n return !!this.location;\n }\n\n +set: (program: WebGLProgram, name: string, v: T) => void;\n}\n\nclass Uniform1i extends Uniform<number> {\n constructor(context: Context) {\n super(context);\n this.current = 0;\n }\n\n // $FlowFixMe[method-unbinding]\n set(program: WebGLProgram, name: string, v: number): void {\n if (!this.fetchUniformLocation(program, name)) return;\n if (this.current !== v) {\n this.current = v;\n this.gl.uniform1i(this.location, v);\n }\n }\n}\n\nclass Uniform1f extends Uniform<number> {\n constructor(context: Context) {\n super(context);\n this.current = 0;\n }\n\n // $FlowFixMe[method-unbinding]\n set(program: WebGLProgram, name: string, v: number): void {\n if (!this.fetchUniformLocation(program, name)) return;\n if (this.current !== v) {\n this.current = v;\n this.gl.uniform1f(this.location, v);\n }\n }\n}\n\nclass Uniform2f extends Uniform<[number, number]> {\n constructor(context: Context) {\n super(context);\n this.current = [0, 0];\n }\n\n // $FlowFixMe[method-unbinding]\n set(program: WebGLProgram, name: string, v: [number, number]): void {\n if (!this.fetchUniformLocation(program, name)) return;\n if (v[0] !== this.current[0] || v[1] !== this.current[1]) {\n this.current = v;\n this.gl.uniform2f(this.location, v[0], v[1]);\n }\n }\n}\n\nclass Uniform3f extends Uniform<[number, number, number]> {\n constructor(context: Context) {\n super(context);\n this.current = [0, 0, 0];\n }\n\n // $FlowFixMe[method-unbinding]\n set(program: WebGLProgram, name: string, v: [number, number, number]): void {\n if (!this.fetchUniformLocation(program, name)) return;\n if (v[0] !== this.current[0] || v[1] !== this.current[1] || v[2] !== this.current[2]) {\n this.current = v;\n this.gl.uniform3f(this.location, v[0], v[1], v[2]);\n }\n }\n}\n\nclass Uniform4f extends Uniform<[number, number, number, number]> {\n constructor(context: Context) {\n super(context);\n this.current = [0, 0, 0, 0];\n }\n\n // $FlowFixMe[method-unbinding]\n set(program: WebGLProgram, name: string, v: [number, number, number, number]): void {\n if (!this.fetchUniformLocation(program, name)) return;\n if (v[0] !== this.current[0] || v[1] !== this.current[1] ||\n v[2] !== this.current[2] || v[3] !== this.current[3]) {\n this.current = v;\n this.gl.uniform4f(this.location, v[0], v[1], v[2], v[3]);\n }\n }\n}\n\nclass UniformColor extends Uniform<Color> {\n constructor(context: Context) {\n super(context);\n this.current = Color.transparent;\n }\n\n // $FlowFixMe[method-unbinding]\n set(program: WebGLProgram, name: string, v: Color): void {\n if (!this.fetchUniformLocation(program, name)) return;\n if (v.r !== this.current.r || v.g !== this.current.g ||\n v.b !== this.current.b || v.a !== this.current.a) {\n this.current = v;\n this.gl.uniform4f(this.location, v.r, v.g, v.b, v.a);\n }\n }\n}\n\nconst emptyMat4 = new Float32Array(16);\nclass UniformMatrix4f extends Uniform<Float32Array> {\n constructor(context: Context) {\n super(context);\n this.current = emptyMat4;\n }\n\n // $FlowFixMe[method-unbinding]\n set(program: WebGLProgram, name: string, v: Float32Array): void {\n if (!this.fetchUniformLocation(program, name)) return;\n // The vast majority of matrix comparisons that will trip this set\n // happen at i=12 or i=0, so we check those first to avoid lots of\n // unnecessary iteration:\n if (v[12] !== this.current[12] || v[0] !== this.current[0]) {\n this.current = v;\n this.gl.uniformMatrix4fv(this.location, false, v);\n return;\n }\n for (let i = 1; i < 16; i++) {\n if (v[i] !== this.current[i]) {\n this.current = v;\n this.gl.uniformMatrix4fv(this.location, false, v);\n break;\n }\n }\n }\n}\n\nconst emptyMat3 = new Float32Array(9);\nclass UniformMatrix3f extends Uniform<Float32Array> {\n constructor(context: Context) {\n super(context);\n this.current = emptyMat3;\n }\n\n // $FlowFixMe[method-unbinding]\n set(program: WebGLProgram, name: string, v: Float32Array): void {\n if (!this.fetchUniformLocation(program, name)) return;\n for (let i = 0; i < 9; i++) {\n if (v[i] !== this.current[i]) {\n this.current = v;\n this.gl.uniformMatrix3fv(this.location, false, v);\n break;\n }\n }\n }\n}\n\nconst emptyMat2 = new Float32Array(4);\nclass UniformMatrix2f extends Uniform<Float32Array> {\n constructor(context: Context) {\n super(context);\n this.current = emptyMat2;\n }\n\n // $FlowFixMe[method-unbinding]\n set(program: WebGLProgram, name: string, v: Float32Array): void {\n if (!this.fetchUniformLocation(program, name)) return;\n for (let i = 0; i < 4; i++) {\n if (v[i] !== this.current[i]) {\n this.current = v;\n this.gl.uniformMatrix2fv(this.location, false, v);\n break;\n }\n }\n }\n}\n\nexport {\n Uniform,\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform3f,\n Uniform4f,\n UniformColor,\n UniformMatrix2f,\n UniformMatrix3f,\n UniformMatrix4f\n};\n\nexport type UniformBindings = {[_: string]: Uniform<any>};\n","// @flow\n\nimport {packUint8ToFloat} from '../shaders/encode_attribute.js';\nimport Color from '../style-spec/util/color.js';\nimport {supportsPropertyExpression} from '../style-spec/util/properties.js';\nimport {register} from '../util/web_worker_transfer.js';\nimport {PossiblyEvaluatedPropertyValue} from '../style/properties.js';\nimport {StructArrayLayout1f4, StructArrayLayout2f8, StructArrayLayout4f16, PatternLayoutArray, DashLayoutArray} from './array_types.js';\nimport {clamp} from '../util/util.js';\nimport patternAttributes from './bucket/pattern_attributes.js';\nimport dashAttributes from './bucket/dash_attributes.js';\nimport EvaluationParameters from '../style/evaluation_parameters.js';\nimport FeaturePositionMap from './feature_position_map.js';\nimport {\n Uniform,\n Uniform1f,\n UniformColor,\n Uniform4f\n} from '../render/uniform_binding.js';\nimport assert from 'assert';\n\nimport type {CanonicalTileID} from '../source/tile_id.js';\nimport type Context from '../gl/context.js';\nimport type {TypedStyleLayer} from '../style/style_layer/typed_style_layer.js';\nimport type {StructArray, StructArrayMember} from '../util/struct_array.js';\nimport type VertexBuffer from '../gl/vertex_buffer.js';\nimport type {SpritePosition, SpritePositions} from '../util/image.js';\nimport type {\n Feature,\n FeatureState,\n GlobalProperties,\n SourceExpression,\n CompositeExpression\n} from '../style-spec/expression/index.js';\nimport type {PossiblyEvaluated} from '../style/properties.js';\nimport type {FeatureStates} from '../source/source_state.js';\nimport type {FormattedSection} from '../style-spec/expression/types/formatted.js';\nimport type {IVectorTileLayer} from '@mapbox/vector-tile';\n\nexport type BinderUniform = {\n name: string,\n property: string,\n binding: Uniform<any>\n};\n\nfunction packColor(color: Color): [number, number] {\n return [\n packUint8ToFloat(255 * color.r, 255 * color.g),\n packUint8ToFloat(255 * color.b, 255 * color.a)\n ];\n}\n\n/**\n * `Binder` is the interface definition for the strategies for constructing,\n * uploading, and binding paint property data as GLSL attributes. Most style-\n * spec properties have a 1:1 relationship to shader attribute/uniforms, but\n * some require multiple values per feature to be passed to the GPU, and in\n * those cases we bind multiple attributes/uniforms.\n *\n * It has three implementations, one for each of the three strategies we use:\n *\n * * For _constant_ properties -- those whose value is a constant, or the constant\n * result of evaluating a camera expression at a particular camera position -- we\n * don't need a vertex attribute buffer, and instead use a uniform.\n * * For data expressions, we use a vertex buffer with a single attribute value,\n * the evaluated result of the source function for the given feature.\n * * For composite expressions, we use a vertex buffer with two attributes: min and\n * max values covering the range of zooms at which we expect the tile to be\n * displayed. These values are calculated by evaluating the composite expression for\n * the given feature at strategically chosen zoom levels. In addition to this\n * attribute data, we also use a uniform value which the shader uses to interpolate\n * between the min and max value at the final displayed zoom level. The use of a\n * uniform allows us to cheaply update the value on every frame.\n *\n * Note that the shader source varies depending on whether we're using a uniform or\n * attribute. We dynamically compile shaders at runtime to accommodate this.\n *\n * @private\n */\n\ninterface AttributeBinder {\n populatePaintArray(length: number, feature: Feature, imagePositions: SpritePositions, availableImages: Array<string>, canonical?: CanonicalTileID, formattedSection?: FormattedSection): void;\n updatePaintArray(start: number, length: number, feature: Feature, featureState: FeatureState, availableImages: Array<string>, imagePositions: SpritePositions): void;\n upload(Context): void;\n destroy(): void;\n}\n\ninterface UniformBinder {\n uniformNames: Array<string>;\n setUniform(program: WebGLProgram, uniform: Uniform<*>, globals: GlobalProperties, currentValue: PossiblyEvaluatedPropertyValue<*>, uniformName: string): void;\n getBinding(context: Context, name: string): $Shape<Uniform<*>>;\n}\n\nclass ConstantBinder implements UniformBinder {\n value: mixed;\n type: string;\n uniformNames: Array<string>;\n\n constructor(value: mixed, names: Array<string>, type: string) {\n this.value = value;\n this.uniformNames = names.map(name => `u_${name}`);\n this.type = type;\n }\n\n setUniform(program: WebGLProgram, uniform: Uniform<*>, globals: GlobalProperties, currentValue: PossiblyEvaluatedPropertyValue<mixed>, uniformName: string): void {\n uniform.set(program, uniformName, currentValue.constantOr(this.value));\n }\n\n // $FlowFixMe[method-unbinding]\n getBinding(context: Context, _: string): $Shape<Uniform<any>> {\n // $FlowFixMe[method-unbinding]\n return (this.type === 'color') ?\n new UniformColor(context) :\n new Uniform1f(context);\n }\n}\n\nclass PatternConstantBinder implements UniformBinder {\n uniformNames: Array<string>;\n pattern: ?Array<number>;\n pixelRatio: number;\n\n constructor(value: mixed, names: Array<string>) {\n this.uniformNames = names.map(name => `u_${name}`);\n this.pattern = null;\n this.pixelRatio = 1;\n }\n\n setConstantPatternPositions(posTo: SpritePosition) {\n this.pixelRatio = posTo.pixelRatio || 1;\n this.pattern = posTo.tl.concat(posTo.br);\n }\n\n setUniform(program: WebGLProgram, uniform: Uniform<*>, globals: GlobalProperties, currentValue: PossiblyEvaluatedPropertyValue<mixed>, uniformName: string) {\n const pos =\n uniformName === 'u_pattern' || uniformName === 'u_dash' ? this.pattern :\n uniformName === 'u_pixel_ratio' ? this.pixelRatio : null;\n if (pos) uniform.set(program, uniformName, pos);\n }\n\n // $FlowFixMe[method-unbinding]\n getBinding(context: Context, name: string): $Shape<Uniform<any>> {\n // $FlowFixMe[method-unbinding]\n return name === 'u_pattern' || name === 'u_dash' ?\n new Uniform4f(context) :\n new Uniform1f(context);\n }\n}\n\nclass SourceExpressionBinder implements AttributeBinder {\n expression: SourceExpression;\n type: string;\n maxValue: number;\n\n paintVertexArray: StructArray;\n paintVertexAttributes: Array<StructArrayMember>;\n paintVertexBuffer: ?VertexBuffer;\n\n constructor(expression: SourceExpression, names: Array<string>, type: string, PaintVertexArray: Class<StructArray>) {\n this.expression = expression;\n this.type = type;\n this.maxValue = 0;\n this.paintVertexAttributes = names.map((name) => ({\n name: `a_${name}`,\n type: 'Float32',\n components: type === 'color' ? 2 : 1,\n offset: 0\n }));\n this.paintVertexArray = new PaintVertexArray();\n }\n\n populatePaintArray(newLength: number, feature: Feature, imagePositions: SpritePositions, availableImages: Array<string>, canonical?: CanonicalTileID, formattedSection?: FormattedSection) {\n const start = this.paintVertexArray.length;\n assert(Array.isArray(availableImages));\n // $FlowFixMe[method-unbinding]\n const value = this.expression.evaluate(new EvaluationParameters(0), feature, {}, canonical, availableImages, formattedSection);\n this.paintVertexArray.resize(newLength);\n this._setPaintValue(start, newLength, value);\n }\n\n updatePaintArray(start: number, end: number, feature: Feature, featureState: FeatureState, availableImages: Array<string>) {\n const value = this.expression.evaluate({zoom: 0}, feature, featureState, undefined, availableImages);\n this._setPaintValue(start, end, value);\n }\n\n _setPaintValue(start: number, end: number, value: any) {\n if (this.type === 'color') {\n const color = packColor(value);\n for (let i = start; i < end; i++) {\n this.paintVertexArray.emplace(i, color[0], color[1]);\n }\n } else {\n for (let i = start; i < end; i++) {\n this.paintVertexArray.emplace(i, value);\n }\n this.maxValue = Math.max(this.maxValue, Math.abs(value));\n }\n }\n\n upload(context: Context) {\n if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) {\n if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) {\n this.paintVertexBuffer.updateData(this.paintVertexArray);\n } else {\n this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent);\n }\n }\n }\n\n destroy() {\n if (this.paintVertexBuffer) {\n this.paintVertexBuffer.destroy();\n }\n }\n}\n\nclass CompositeExpressionBinder implements AttributeBinder, UniformBinder {\n expression: CompositeExpression;\n uniformNames: Array<string>;\n type: string;\n useIntegerZoom: boolean;\n zoom: number;\n maxValue: number;\n\n paintVertexArray: StructArray;\n paintVertexAttributes: Array<StructArrayMember>;\n paintVertexBuffer: ?VertexBuffer;\n\n constructor(expression: CompositeExpression, names: Array<string>, type: string, useIntegerZoom: boolean, zoom: number, PaintVertexArray: Class<StructArray>) {\n this.expression = expression;\n this.uniformNames = names.map(name => `u_${name}_t`);\n this.type = type;\n this.useIntegerZoom = useIntegerZoom;\n this.zoom = zoom;\n this.maxValue = 0;\n this.paintVertexAttributes = names.map((name) => ({\n name: `a_${name}`,\n type: 'Float32',\n components: type === 'color' ? 4 : 2,\n offset: 0\n }));\n this.paintVertexArray = new PaintVertexArray();\n }\n\n populatePaintArray(newLength: number, feature: Feature, imagePositions: SpritePositions, availableImages: Array<string>, canonical?: CanonicalTileID, formattedSection?: FormattedSection) {\n // $FlowFixMe[method-unbinding]\n const min = this.expression.evaluate(new EvaluationParameters(this.zoom), feature, {}, canonical, availableImages, formattedSection);\n // $FlowFixMe[method-unbinding]\n const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1), feature, {}, canonical, availableImages, formattedSection);\n const start = this.paintVertexArray.length;\n this.paintVertexArray.resize(newLength);\n this._setPaintValue(start, newLength, min, max);\n }\n\n updatePaintArray(start: number, end: number, feature: Feature, featureState: FeatureState, availableImages: Array<string>) {\n const min = this.expression.evaluate({zoom: this.zoom}, feature, featureState, undefined, availableImages);\n const max = this.expression.evaluate({zoom: this.zoom + 1}, feature, featureState, undefined, availableImages);\n this._setPaintValue(start, end, min, max);\n }\n\n _setPaintValue(start: number, end: number, min: any, max: any) {\n if (this.type === 'color') {\n const minColor = packColor(min);\n const maxColor = packColor(max);\n for (let i = start; i < end; i++) {\n this.paintVertexArray.emplace(i, minColor[0], minColor[1], maxColor[0], maxColor[1]);\n }\n } else {\n for (let i = start; i < end; i++) {\n this.paintVertexArray.emplace(i, min, max);\n }\n this.maxValue = Math.max(this.maxValue, Math.abs(min), Math.abs(max));\n }\n }\n\n upload(context: Context) {\n if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) {\n if (this.paintVertexBuffer && this.paintVertexBuffer.buffer) {\n this.paintVertexBuffer.updateData(this.paintVertexArray);\n } else {\n this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent);\n }\n }\n }\n\n destroy() {\n if (this.paintVertexBuffer) {\n this.paintVertexBuffer.destroy();\n }\n }\n\n setUniform(program: WebGLProgram, uniform: Uniform<*>, globals: GlobalProperties, _: PossiblyEvaluatedPropertyValue<*>, uniformName: string): void {\n const currentZoom = this.useIntegerZoom ? Math.floor(globals.zoom) : globals.zoom;\n const factor = clamp(this.expression.interpolationFactor(currentZoom, this.zoom, this.zoom + 1), 0, 1);\n uniform.set(program, uniformName, factor);\n }\n\n // $FlowFixMe[method-unbinding]\n getBinding(context: Context, _: string): Uniform1f {\n return new Uniform1f(context);\n }\n}\n\nclass PatternCompositeBinder implements AttributeBinder {\n expression: CompositeExpression;\n layerId: string;\n\n paintVertexArray: StructArray;\n paintVertexBuffer: ?VertexBuffer;\n paintVertexAttributes: Array<StructArrayMember>;\n\n constructor(expression: CompositeExpression, names: Array<string>, type: string, PaintVertexArray: Class<StructArray>, layerId: string) {\n this.expression = expression;\n this.layerId = layerId;\n\n this.paintVertexAttributes = (type === 'array' ? dashAttributes : patternAttributes).members;\n for (let i = 0; i < names.length; ++i) {\n assert(`a_${names[i]}` === this.paintVertexAttributes[i].name);\n }\n\n this.paintVertexArray = new PaintVertexArray();\n }\n\n populatePaintArray(length: number, feature: Feature, imagePositions: SpritePositions) {\n const start = this.paintVertexArray.length;\n this.paintVertexArray.resize(length);\n this._setPaintValues(start, length, feature.patterns && feature.patterns[this.layerId], imagePositions);\n }\n\n updatePaintArray(start: number, end: number, feature: Feature, featureState: FeatureState, availableImages: Array<string>, imagePositions: SpritePositions) {\n this._setPaintValues(start, end, feature.patterns && feature.patterns[this.layerId], imagePositions);\n }\n\n _setPaintValues(start: number, end: number, patterns: ?string, positions: SpritePositions) {\n if (!positions || !patterns) return;\n\n const pos = positions[patterns];\n if (!pos) return;\n\n const {tl, br, pixelRatio} = pos;\n for (let i = start; i < end; i++) {\n this.paintVertexArray.emplace(i, tl[0], tl[1], br[0], br[1], pixelRatio);\n }\n }\n\n upload(context: Context) {\n if (this.paintVertexArray && this.paintVertexArray.arrayBuffer) {\n this.paintVertexBuffer = context.createVertexBuffer(this.paintVertexArray, this.paintVertexAttributes, this.expression.isStateDependent);\n }\n }\n\n destroy() {\n if (this.paintVertexBuffer) this.paintVertexBuffer.destroy();\n }\n}\n\n/**\n * ProgramConfiguration contains the logic for binding style layer properties and tile\n * layer feature data into GL program uniforms and vertex attributes.\n *\n * Non-data-driven property values are bound to shader uniforms. Data-driven property\n * values are bound to vertex attributes. In order to support a uniform GLSL syntax over\n * both, [Mapbox GL Shaders](https://github.com/mapbox/mapbox-gl-shaders) defines a `#pragma`\n * abstraction, which ProgramConfiguration is responsible for implementing. At runtime,\n * it examines the attributes of a particular layer, combines this with fixed knowledge\n * about how layers of the particular type are implemented, and determines which uniforms\n * and vertex attributes will be required. It can then substitute the appropriate text\n * into the shader source code, create and link a program, and bind the uniforms and\n * vertex attributes in preparation for drawing.\n *\n * When a vector tile is parsed, this same configuration information is used to\n * populate the attribute buffers needed for data-driven styling using the zoom\n * level and feature property data.\n *\n * @private\n */\nexport default class ProgramConfiguration {\n binders: {[_: string]: (AttributeBinder | UniformBinder) };\n cacheKey: string;\n\n _buffers: Array<VertexBuffer>;\n\n constructor(layer: TypedStyleLayer, zoom: number, filterProperties: (_: string) => boolean = () => true) {\n this.binders = {};\n this._buffers = [];\n\n const keys = [];\n\n for (const property in layer.paint._values) {\n if (!filterProperties(property)) continue;\n const value = layer.paint.get(property);\n if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) {\n continue;\n }\n const names = paintAttributeNames(property, layer.type);\n const expression = value.value;\n const type = value.property.specification.type;\n const useIntegerZoom = !!value.property.useIntegerZoom;\n const isPattern = property === 'line-dasharray' || property.endsWith('pattern');\n const sourceException = property === 'line-dasharray' && (layer.layout: any).get('line-cap').value.kind !== 'constant';\n\n if (expression.kind === 'constant' && !sourceException) {\n this.binders[property] = isPattern ?\n new PatternConstantBinder(expression.value, names) :\n new ConstantBinder(expression.value, names, type);\n keys.push(`/u_${property}`);\n\n } else if (expression.kind === 'source' || sourceException || isPattern) {\n const StructArrayLayout = layoutType(property, type, 'source');\n this.binders[property] = isPattern ?\n // $FlowFixMe[prop-missing]\n // $FlowFixMe[incompatible-call] - expression can be a `composite` or `constant` kind expression\n new PatternCompositeBinder(expression, names, type, StructArrayLayout, layer.id) :\n // $FlowFixMe[prop-missing]\n // $FlowFixMe[incompatible-call] - expression can be a `composite` or `constant` kind expression\n new SourceExpressionBinder(expression, names, type, StructArrayLayout);\n\n keys.push(`/a_${property}`);\n\n } else {\n const StructArrayLayout = layoutType(property, type, 'composite');\n // $FlowFixMe[prop-missing]\n // $FlowFixMe[incompatible-call] — expression can be a `constant` kind expression\n this.binders[property] = new CompositeExpressionBinder(expression, names, type, useIntegerZoom, zoom, StructArrayLayout);\n keys.push(`/z_${property}`);\n }\n }\n\n this.cacheKey = keys.sort().join('');\n }\n\n getMaxValue(property: string): number {\n const binder = this.binders[property];\n return binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder ? binder.maxValue : 0;\n }\n\n populatePaintArrays(newLength: number, feature: Feature, imagePositions: SpritePositions, availableImages: Array<string>, canonical?: CanonicalTileID, formattedSection?: FormattedSection) {\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof PatternCompositeBinder)\n (binder: AttributeBinder).populatePaintArray(newLength, feature, imagePositions, availableImages, canonical, formattedSection);\n }\n }\n setConstantPatternPositions(posTo: SpritePosition) {\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof PatternConstantBinder)\n binder.setConstantPatternPositions(posTo);\n }\n }\n\n updatePaintArrays(featureStates: FeatureStates, featureMap: FeaturePositionMap, vtLayer: IVectorTileLayer, layer: TypedStyleLayer, availableImages: Array<string>, imagePositions: SpritePositions): boolean {\n let dirty: boolean = false;\n for (const id in featureStates) {\n const positions = featureMap.getPositions(id);\n\n for (const pos of positions) {\n const feature = vtLayer.feature(pos.index);\n\n for (const property in this.binders) {\n const binder = this.binders[property];\n if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder ||\n binder instanceof PatternCompositeBinder) && (binder: any).expression.isStateDependent === true) {\n //AHM: Remove after https://github.com/mapbox/mapbox-gl-js/issues/6255\n const value = layer.paint.get(property);\n (binder: any).expression = value.value;\n (binder: AttributeBinder).updatePaintArray(pos.start, pos.end, feature, featureStates[id], availableImages, imagePositions);\n dirty = true;\n }\n }\n }\n }\n return dirty;\n }\n\n defines(): Array<string> {\n const result = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof ConstantBinder || binder instanceof PatternConstantBinder) {\n result.push(...binder.uniformNames.map(name => `#define HAS_UNIFORM_${name}`));\n }\n }\n return result;\n }\n\n getBinderAttributes(): Array<string> {\n const result = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof PatternCompositeBinder) {\n for (let i = 0; i < binder.paintVertexAttributes.length; i++) {\n result.push(binder.paintVertexAttributes[i].name);\n }\n }\n }\n return result;\n }\n\n getBinderUniforms(): Array<string> {\n const uniforms = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof ConstantBinder || binder instanceof PatternConstantBinder || binder instanceof CompositeExpressionBinder) {\n for (const uniformName of binder.uniformNames) {\n uniforms.push(uniformName);\n }\n }\n }\n return uniforms;\n }\n\n getPaintVertexBuffers(): Array<VertexBuffer> {\n return this._buffers;\n }\n\n getUniforms(context: Context): Array<BinderUniform> {\n const uniforms = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof ConstantBinder || binder instanceof PatternConstantBinder || binder instanceof CompositeExpressionBinder) {\n for (const name of binder.uniformNames) {\n uniforms.push({name, property, binding: binder.getBinding(context, name)});\n }\n }\n }\n return uniforms;\n }\n\n setUniforms<Properties: Object>(program: WebGLProgram, context: Context, binderUniforms: Array<BinderUniform>, properties: PossiblyEvaluated<Properties>, globals: GlobalProperties) {\n // Uniform state bindings are owned by the Program, but we set them\n // from within the ProgramConfiguration's binder members.\n for (const {name, property, binding} of binderUniforms) {\n (this.binders[property]: any).setUniform(program, binding, globals, properties.get(property), name);\n }\n }\n\n updatePaintBuffers() {\n this._buffers = [];\n\n for (const property in this.binders) {\n const binder = this.binders[property];\n if ((\n binder instanceof SourceExpressionBinder ||\n binder instanceof CompositeExpressionBinder ||\n binder instanceof PatternCompositeBinder) && binder.paintVertexBuffer) {\n this._buffers.push(binder.paintVertexBuffer);\n }\n }\n }\n\n upload(context: Context) {\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof PatternCompositeBinder)\n binder.upload(context);\n }\n this.updatePaintBuffers();\n }\n\n destroy() {\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder || binder instanceof PatternCompositeBinder)\n binder.destroy();\n }\n }\n}\n\nexport class ProgramConfigurationSet<Layer: TypedStyleLayer> {\n programConfigurations: {[_: string]: ProgramConfiguration};\n needsUpload: boolean;\n _featureMap: FeaturePositionMap;\n _bufferOffset: number;\n\n constructor(layers: $ReadOnlyArray<Layer>, zoom: number, filterProperties: (_: string) => boolean = () => true) {\n this.programConfigurations = {};\n for (const layer of layers) {\n this.programConfigurations[layer.id] = new ProgramConfiguration(layer, zoom, filterProperties);\n }\n this.needsUpload = false;\n this._featureMap = new FeaturePositionMap();\n this._bufferOffset = 0;\n }\n\n populatePaintArrays(length: number, feature: Feature, index: number, imagePositions: SpritePositions, availableImages: Array<string>, canonical: CanonicalTileID, formattedSection?: FormattedSection) {\n for (const key in this.programConfigurations) {\n this.programConfigurations[key].populatePaintArrays(length, feature, imagePositions, availableImages, canonical, formattedSection);\n }\n\n if (feature.id !== undefined) {\n this._featureMap.add(feature.id, index, this._bufferOffset, length);\n }\n this._bufferOffset = length;\n\n this.needsUpload = true;\n }\n\n updatePaintArrays(featureStates: FeatureStates, vtLayer: IVectorTileLayer, layers: $ReadOnlyArray<TypedStyleLayer>, availableImages: Array<string>, imagePositions: SpritePositions) {\n for (const layer of layers) {\n this.needsUpload = this.programConfigurations[layer.id].updatePaintArrays(featureStates, this._featureMap, vtLayer, layer, availableImages, imagePositions) || this.needsUpload;\n }\n }\n\n get(layerId: string): ProgramConfiguration {\n return this.programConfigurations[layerId];\n }\n\n upload(context: Context) {\n if (!this.needsUpload) return;\n for (const layerId in this.programConfigurations) {\n this.programConfigurations[layerId].upload(context);\n }\n this.needsUpload = false;\n }\n\n destroy() {\n for (const layerId in this.programConfigurations) {\n this.programConfigurations[layerId].destroy();\n }\n }\n}\n\nconst attributeNameExceptions = {\n 'text-opacity': ['opacity'],\n 'icon-opacity': ['opacity'],\n 'text-color': ['fill_color'],\n 'icon-color': ['fill_color'],\n 'text-halo-color': ['halo_color'],\n 'icon-halo-color': ['halo_color'],\n 'text-halo-blur': ['halo_blur'],\n 'icon-halo-blur': ['halo_blur'],\n 'text-halo-width': ['halo_width'],\n 'icon-halo-width': ['halo_width'],\n 'line-gap-width': ['gapwidth'],\n 'line-pattern': ['pattern', 'pixel_ratio'],\n 'fill-pattern': ['pattern', 'pixel_ratio'],\n 'fill-extrusion-pattern': ['pattern', 'pixel_ratio'],\n 'line-dasharray': ['dash']\n};\n\nfunction paintAttributeNames(property: string, type: string) {\n return attributeNameExceptions[property] || [property.replace(`${type}-`, '').replace(/-/g, '_')];\n}\n\nconst propertyExceptions = {\n 'line-pattern': {\n 'source': PatternLayoutArray,\n 'composite': PatternLayoutArray\n },\n 'fill-pattern': {\n 'source': PatternLayoutArray,\n 'composite': PatternLayoutArray\n },\n 'fill-extrusion-pattern':{\n 'source': PatternLayoutArray,\n 'composite': PatternLayoutArray\n },\n 'line-dasharray': { // temporary layout\n 'source': DashLayoutArray,\n 'composite': DashLayoutArray\n }\n};\n\nconst defaultLayouts = {\n 'color': {\n 'source': StructArrayLayout2f8,\n 'composite': StructArrayLayout4f16\n },\n 'number': {\n 'source': StructArrayLayout1f4,\n 'composite': StructArrayLayout2f8\n }\n};\n\ntype LayoutType = 'array' | 'boolean' | 'color' | 'enum' | 'number' | 'resolvedImage' | 'string';\n\nfunction layoutType(property: string, type: LayoutType, binderType: string) {\n const layoutException = propertyExceptions[property];\n // $FlowFixMe[prop-missing] - we don't cover all types in defaultLayouts for some reason\n return (layoutException && layoutException[binderType]) || defaultLayouts[type][binderType];\n}\n\nregister(ConstantBinder, 'ConstantBinder');\nregister(PatternConstantBinder, 'PatternConstantBinder');\nregister(SourceExpressionBinder, 'SourceExpressionBinder');\nregister(PatternCompositeBinder, 'PatternCompositeBinder');\nregister(CompositeExpressionBinder, 'CompositeExpressionBinder');\nregister(ProgramConfiguration, 'ProgramConfiguration', {omit: ['_buffers']});\nregister(ProgramConfigurationSet, 'ProgramConfigurationSet');\n","// @flow\n\nimport {endsWith, filterObject} from '../util/util.js';\n\nimport styleSpec from '../style-spec/reference/latest.js';\nimport {\n validateStyle,\n validateLayoutProperty,\n validatePaintProperty,\n emitValidationErrors\n} from './validate_style.js';\nimport {Evented} from '../util/evented.js';\nimport {Layout, Transitionable, Transitioning, Properties, PossiblyEvaluated, PossiblyEvaluatedPropertyValue} from './properties.js';\nimport {supportsPropertyExpression} from '../style-spec/util/properties.js';\nimport ProgramConfiguration from '../data/program_configuration.js';\nimport featureFilter from '../style-spec/feature_filter/index.js';\n\nimport type {FeatureState} from '../style-spec/expression/index.js';\nimport type {Bucket} from '../data/bucket.js';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureFilter, FilterExpression} from '../style-spec/feature_filter/index.js';\nimport type {TransitionParameters, PropertyValue} from './properties.js';\nimport type EvaluationParameters from './evaluation_parameters.js';\nimport type Transform from '../geo/transform.js';\nimport type {\n LayerSpecification,\n FilterSpecification,\n TransitionSpecification,\n PropertyValueSpecification\n} from '../style-spec/types.js';\nimport type {CustomLayerInterface} from './style_layer/custom_style_layer.js';\nimport type Map from '../ui/map.js';\nimport type {StyleSetterOptions} from './style.js';\nimport type {TilespaceQueryGeometry} from './query_geometry.js';\nimport type {DEMSampler} from '../terrain/elevation.js';\nimport type {IVectorTileFeature} from '@mapbox/vector-tile';\n\nconst TRANSITION_SUFFIX = '-transition';\n\nclass StyleLayer extends Evented {\n id: string;\n metadata: mixed;\n type: string;\n source: string;\n sourceLayer: ?string;\n minzoom: ?number;\n maxzoom: ?number;\n filter: FilterSpecification | void;\n visibility: 'visible' | 'none' | void;\n\n _unevaluatedLayout: Layout<any>;\n +layout: mixed;\n\n _transitionablePaint: Transitionable<any>;\n _transitioningPaint: Transitioning<any>;\n +paint: mixed;\n\n _featureFilter: FeatureFilter;\n _filterCompiled: boolean;\n\n +queryRadius: (bucket: Bucket) => number;\n +queryIntersectsFeature: (queryGeometry: TilespaceQueryGeometry,\n feature: IVectorTileFeature,\n featureState: FeatureState,\n geometry: Array<Array<Point>>,\n zoom: number,\n transform: Transform,\n pixelPosMatrix: Float32Array,\n elevationHelper: ?DEMSampler,\n layoutVertexArrayOffset: number) => boolean | number;\n\n +onAdd: ?(map: Map) => void;\n +onRemove: ?(map: Map) => void;\n\n constructor(layer: LayerSpecification | CustomLayerInterface, properties: $ReadOnly<{layout?: Properties<*>, paint?: Properties<*>}>) {\n super();\n\n this.id = layer.id;\n this.type = layer.type;\n this._featureFilter = {filter: () => true, needGeometry: false, needFeature: false};\n this._filterCompiled = false;\n\n if (layer.type === 'custom') return;\n\n layer = ((layer: any): LayerSpecification);\n\n this.metadata = layer.metadata;\n this.minzoom = layer.minzoom;\n this.maxzoom = layer.maxzoom;\n\n if (layer.type !== 'background' && layer.type !== 'sky') {\n this.source = layer.source;\n this.sourceLayer = layer['source-layer'];\n this.filter = layer.filter;\n }\n\n if (properties.layout) {\n this._unevaluatedLayout = new Layout(properties.layout);\n }\n\n if (properties.paint) {\n this._transitionablePaint = new Transitionable(properties.paint);\n\n for (const property in layer.paint) {\n this.setPaintProperty(property, layer.paint[property], {validate: false});\n }\n for (const property in layer.layout) {\n this.setLayoutProperty(property, layer.layout[property], {validate: false});\n }\n\n this._transitioningPaint = this._transitionablePaint.untransitioned();\n //$FlowFixMe\n this.paint = new PossiblyEvaluated(properties.paint);\n }\n }\n\n getLayoutProperty(name: string): PropertyValueSpecification<mixed> {\n if (name === 'visibility') {\n return this.visibility;\n }\n\n return this._unevaluatedLayout.getValue(name);\n }\n\n setLayoutProperty(name: string, value: any, options: StyleSetterOptions = {}) {\n if (value !== null && value !== undefined) {\n const key = `layers.${this.id}.layout.${name}`;\n if (this._validate(validateLayoutProperty, key, name, value, options)) {\n return;\n }\n }\n\n if (name === 'visibility') {\n this.visibility = value;\n return;\n }\n\n this._unevaluatedLayout.setValue(name, value);\n }\n\n getPaintProperty(name: string): void | TransitionSpecification | PropertyValueSpecification<mixed> {\n if (endsWith(name, TRANSITION_SUFFIX)) {\n return this._transitionablePaint.getTransition(name.slice(0, -TRANSITION_SUFFIX.length));\n } else {\n return this._transitionablePaint.getValue(name);\n }\n }\n\n setPaintProperty(name: string, value: mixed, options: StyleSetterOptions = {}): boolean {\n if (value !== null && value !== undefined) {\n const key = `layers.${this.id}.paint.${name}`;\n if (this._validate(validatePaintProperty, key, name, value, options)) {\n return false;\n }\n }\n\n if (endsWith(name, TRANSITION_SUFFIX)) {\n this._transitionablePaint.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), (value: any) || undefined);\n return false;\n } else {\n const transitionable = this._transitionablePaint._values[name];\n const wasDataDriven = transitionable.value.isDataDriven();\n const oldValue = transitionable.value;\n\n this._transitionablePaint.setValue(name, value);\n this._handleSpecialPaintPropertyUpdate(name);\n\n const newValue = this._transitionablePaint._values[name].value;\n const isDataDriven = newValue.isDataDriven();\n const isPattern = endsWith(name, 'pattern') || name === 'line-dasharray';\n\n // if a pattern value is changed, we need to make sure the new icons get added to each tile's iconAtlas\n // so a call to _updateLayer is necessary, and we return true from this function so it gets called in\n // Style#setPaintProperty\n return isDataDriven || wasDataDriven || isPattern || this._handleOverridablePaintPropertyUpdate(name, oldValue, newValue);\n }\n }\n\n _handleSpecialPaintPropertyUpdate(_: string) {\n // No-op; can be overridden by derived classes.\n }\n\n getProgramIds(): string[] | null {\n // No-op; can be overridden by derived classes.\n return null;\n }\n\n getProgramConfiguration(_: number): ProgramConfiguration | null {\n // No-op; can be overridden by derived classes.\n return null;\n }\n\n // eslint-disable-next-line no-unused-vars\n _handleOverridablePaintPropertyUpdate<T, R>(name: string, oldValue: PropertyValue<T, R>, newValue: PropertyValue<T, R>): boolean {\n // No-op; can be overridden by derived classes.\n return false;\n }\n\n isHidden(zoom: number): boolean {\n if (this.minzoom && zoom < this.minzoom) return true;\n if (this.maxzoom && zoom >= this.maxzoom) return true;\n return this.visibility === 'none';\n }\n\n updateTransitions(parameters: TransitionParameters) {\n this._transitioningPaint = this._transitionablePaint.transitioned(parameters, this._transitioningPaint);\n }\n\n hasTransition(): boolean {\n return this._transitioningPaint.hasTransition();\n }\n\n recalculate(parameters: EvaluationParameters, availableImages: Array<string>) {\n if (this._unevaluatedLayout) {\n (this: any).layout = this._unevaluatedLayout.possiblyEvaluate(parameters, undefined, availableImages);\n }\n\n (this: any).paint = this._transitioningPaint.possiblyEvaluate(parameters, undefined, availableImages);\n }\n\n serialize(): LayerSpecification {\n const output: any = {\n 'id': this.id,\n 'type': this.type,\n 'source': this.source,\n 'source-layer': this.sourceLayer,\n 'metadata': this.metadata,\n 'minzoom': this.minzoom,\n 'maxzoom': this.maxzoom,\n 'filter': this.filter,\n 'layout': this._unevaluatedLayout && this._unevaluatedLayout.serialize(),\n 'paint': this._transitionablePaint && this._transitionablePaint.serialize()\n };\n\n if (this.visibility) {\n output.layout = output.layout || {};\n output.layout.visibility = this.visibility;\n }\n\n return filterObject(output, (value, key) => {\n return value !== undefined &&\n !(key === 'layout' && !Object.keys(value).length) &&\n !(key === 'paint' && !Object.keys(value).length);\n });\n }\n\n _validate(validate: Function, key: string, name: string, value: mixed, options: StyleSetterOptions = {}): boolean {\n if (options && options.validate === false) {\n return false;\n }\n return emitValidationErrors(this, validate.call(validateStyle, {\n key,\n layerType: this.type,\n objectKey: name,\n value,\n styleSpec,\n // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407\n style: {glyphs: true, sprite: true}\n }));\n }\n\n is3D(): boolean {\n return false;\n }\n\n isSky(): boolean {\n return false;\n }\n\n isTileClipped(): boolean {\n return false;\n }\n\n hasOffscreenPass(): boolean {\n return false;\n }\n\n resize() {\n // noop\n }\n\n isStateDependent(): boolean {\n for (const property in (this: any).paint._values) {\n const value = (this: any).paint.get(property);\n if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) {\n continue;\n }\n\n if ((value.value.kind === 'source' || value.value.kind === 'composite') &&\n value.value.isStateDependent) {\n return true;\n }\n }\n return false;\n }\n\n compileFilter() {\n if (!this._filterCompiled) {\n this._featureFilter = featureFilter(this.filter);\n this._filterCompiled = true;\n }\n }\n\n invalidateCompiledFilter() {\n this._filterCompiled = false;\n }\n\n dynamicFilter(): ?FilterExpression {\n return this._featureFilter.dynamicFilter;\n }\n\n dynamicFilterNeedsFeature(): boolean {\n return this._featureFilter.needFeature;\n }\n}\n\nexport default StyleLayer;\n","// @flow\nimport {ErrorEvent} from '../util/evented.js';\n\nimport type {Evented} from '../util/evented.js';\nimport type {ValidationErrors as _ValidationErrors} from '../style-spec/validate_style.min.js';\n\nexport type {Validator, ValidationErrors} from '../style-spec/validate_style.min.js';\n\nexport function emitValidationErrors(emitter: Evented, errors: ?_ValidationErrors): boolean {\n let hasErrors = false;\n if (errors && errors.length) {\n for (const error of errors) {\n emitter.fire(new ErrorEvent(new Error(error.message)));\n hasErrors = true;\n }\n }\n return hasErrors;\n}\n\nexport {\n validateStyle,\n validateSource,\n validateLight,\n validateTerrain,\n validateFog,\n validateLayer,\n validateFilter,\n validatePaintProperty,\n validateLayoutProperty\n} from '../style-spec/validate_style.min.js';\n","// @flow\nimport {createLayout} from '../../util/struct_array.js';\n\nimport type {StructArrayLayout} from '../../util/struct_array.js';\n\nexport const circleAttributes: StructArrayLayout = createLayout([\n {name: 'a_pos', components: 2, type: 'Int16'}\n], 4);\n\nexport const circleGlobeAttributesExt: StructArrayLayout = createLayout([\n {name: 'a_pos_3', components: 3, type: 'Int16'},\n {name: 'a_pos_normal_3', components: 3, type: 'Int16'}\n]);\n\nexport const {members, size, alignment} = circleAttributes;\n","// @flow\n\nimport {warnOnce} from '../util/util.js';\n\nimport {register} from '../util/web_worker_transfer.js';\n\nimport type VertexArrayObject from '../render/vertex_array_object.js';\nimport type {StructArray} from '../util/struct_array.js';\n\nexport type Segment = {\n sortKey: number | void,\n vertexOffset: number,\n primitiveOffset: number,\n vertexLength: number,\n primitiveLength: number,\n vaos: {[_: string]: VertexArrayObject}\n}\n\nclass SegmentVector {\n static MAX_VERTEX_ARRAY_LENGTH: number;\n segments: Array<Segment>;\n\n constructor(segments?: Array<Segment> = []) {\n this.segments = segments;\n }\n\n prepareSegment(numVertices: number, layoutVertexArray: StructArray, indexArray: StructArray, sortKey?: number): Segment {\n let segment: Segment = this.segments[this.segments.length - 1];\n if (numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) warnOnce(`Max vertices per segment is ${SegmentVector.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${numVertices}`);\n if (!segment || segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH || segment.sortKey !== sortKey) {\n segment = ({\n vertexOffset: layoutVertexArray.length,\n primitiveOffset: indexArray.length,\n vertexLength: 0,\n primitiveLength: 0\n }: any);\n if (sortKey !== undefined) segment.sortKey = sortKey;\n this.segments.push(segment);\n }\n return segment;\n }\n\n get(): Array<Segment> {\n return this.segments;\n }\n\n destroy() {\n for (const segment of this.segments) {\n for (const k in segment.vaos) {\n segment.vaos[k].destroy();\n }\n }\n }\n\n static simpleSegment(vertexOffset: number, primitiveOffset: number, vertexLength: number, primitiveLength: number): SegmentVector {\n return new SegmentVector([{\n vertexOffset,\n primitiveOffset,\n vertexLength,\n primitiveLength,\n vaos: {},\n sortKey: 0\n }]);\n }\n}\n\n/*\n * The maximum size of a vertex array. This limit is imposed by WebGL's 16 bit\n * addressing of vertex buffers.\n * @private\n * @readonly\n */\nSegmentVector.MAX_VERTEX_ARRAY_LENGTH = Math.pow(2, 16) - 1;\n\nregister(SegmentVector, 'SegmentVector');\nexport default SegmentVector;\n","// @flow\n\n/**\n * The maximum value of a coordinate in the internal tile coordinate system. Coordinates of\n * all source features normalized to this extent upon load.\n *\n * The value is a consequence of the following:\n *\n * * Vertex buffer store positions as signed 16 bit integers.\n * * One bit is lost for signedness to support tile buffers.\n * * One bit is lost because the line vertex buffer used to pack 1 bit of other data into the int.\n * * One bit is lost to support features extending past the extent on the right edge of the tile.\n * * This leaves us with 2^13 = 8192\n *\n * @private\n * @readonly\n */\nexport default 8192;\n","// @flow\n\nimport LngLat from './lng_lat.js';\n\nimport type {LngLatLike} from './lng_lat.js';\n\n/**\n * A `LngLatBounds` object represents a geographical bounding box,\n * defined by its southwest and northeast points in longitude and latitude.\n *\n * If no arguments are provided to the constructor, a `null` bounding box is created.\n *\n * Note that any Mapbox GL method that accepts a `LngLatBounds` object as an argument or option\n * can also accept an `Array` of two {@link LngLatLike} constructs and will perform an implicit conversion.\n * This flexible type is documented as {@link LngLatBoundsLike}.\n *\n * @param {LngLatLike} [sw] The southwest corner of the bounding box.\n * @param {LngLatLike} [ne] The northeast corner of the bounding box.\n * @example\n * const sw = new mapboxgl.LngLat(-73.9876, 40.7661);\n * const ne = new mapboxgl.LngLat(-73.9397, 40.8002);\n * const llb = new mapboxgl.LngLatBounds(sw, ne);\n */\nclass LngLatBounds {\n _ne: LngLat;\n _sw: LngLat;\n\n // This constructor is too flexible to type. It should not be so flexible.\n constructor(sw: any, ne: any) {\n if (!sw) {\n // noop\n } else if (ne) {\n this.setSouthWest(sw).setNorthEast(ne);\n } else if (sw.length === 4) {\n this.setSouthWest([sw[0], sw[1]]).setNorthEast([sw[2], sw[3]]);\n } else {\n this.setSouthWest(sw[0]).setNorthEast(sw[1]);\n }\n }\n\n /**\n * Set the northeast corner of the bounding box.\n *\n * @param {LngLatLike} ne A {@link LngLatLike} object describing the northeast corner of the bounding box.\n * @returns {LngLatBounds} Returns itself to allow for method chaining.\n * @example\n * const sw = new mapboxgl.LngLat(-73.9876, 40.7661);\n * const ne = new mapboxgl.LngLat(-73.9397, 40.8002);\n * const llb = new mapboxgl.LngLatBounds(sw, ne);\n * llb.setNorthEast([-73.9397, 42.8002]);\n */\n setNorthEast(ne: LngLatLike): this {\n this._ne = ne instanceof LngLat ? new LngLat(ne.lng, ne.lat) : LngLat.convert(ne);\n return this;\n }\n\n /**\n * Set the southwest corner of the bounding box.\n *\n * @param {LngLatLike} sw A {@link LngLatLike} object describing the southwest corner of the bounding box.\n * @returns {LngLatBounds} Returns itself to allow for method chaining.\n * @example\n * const sw = new mapboxgl.LngLat(-73.9876, 40.7661);\n * const ne = new mapboxgl.LngLat(-73.9397, 40.8002);\n * const llb = new mapboxgl.LngLatBounds(sw, ne);\n * llb.setSouthWest([-73.9876, 40.2661]);\n */\n setSouthWest(sw: LngLatLike): this {\n this._sw = sw instanceof LngLat ? new LngLat(sw.lng, sw.lat) : LngLat.convert(sw);\n return this;\n }\n\n /**\n * Extend the bounds to include a given LngLatLike or LngLatBoundsLike.\n *\n * @param {LngLatLike|LngLatBoundsLike} obj Object to extend to.\n * @returns {LngLatBounds} Returns itself to allow for method chaining.\n * @example\n * const sw = new mapboxgl.LngLat(-73.9876, 40.7661);\n * const ne = new mapboxgl.LngLat(-73.9397, 40.8002);\n * const llb = new mapboxgl.LngLatBounds(sw, ne);\n * llb.extend([-72.9876, 42.2661]);\n */\n extend(obj: LngLatLike | LngLatBoundsLike): this {\n const sw = this._sw,\n ne = this._ne;\n let sw2, ne2;\n\n if (obj instanceof LngLat) {\n sw2 = obj;\n ne2 = obj;\n\n } else if (obj instanceof LngLatBounds) {\n sw2 = obj._sw;\n ne2 = obj._ne;\n\n if (!sw2 || !ne2) return this;\n\n } else if (Array.isArray(obj)) {\n // $FlowFixMe[method-unbinding]\n if (obj.length === 4 || obj.every(Array.isArray)) {\n const lngLatBoundsObj = ((obj: any): LngLatBoundsLike);\n return this.extend(LngLatBounds.convert(lngLatBoundsObj));\n } else {\n const lngLatObj = ((obj: any): LngLatLike);\n return this.extend(LngLat.convert(lngLatObj));\n }\n } else if (typeof obj === 'object' && obj !== null && obj.hasOwnProperty(\"lat\") && (obj.hasOwnProperty(\"lon\") || obj.hasOwnProperty(\"lng\"))) {\n return this.extend(LngLat.convert(obj));\n } else {\n return this;\n }\n\n if (!sw && !ne) {\n this._sw = new LngLat(sw2.lng, sw2.lat);\n this._ne = new LngLat(ne2.lng, ne2.lat);\n\n } else {\n sw.lng = Math.min(sw2.lng, sw.lng);\n sw.lat = Math.min(sw2.lat, sw.lat);\n ne.lng = Math.max(ne2.lng, ne.lng);\n ne.lat = Math.max(ne2.lat, ne.lat);\n }\n\n return this;\n }\n\n /**\n * Returns the geographical coordinate equidistant from the bounding box's corners.\n *\n * @returns {LngLat} The bounding box's center.\n * @example\n * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.getCenter(); // = LngLat {lng: -73.96365, lat: 40.78315}\n */\n getCenter(): LngLat {\n return new LngLat((this._sw.lng + this._ne.lng) / 2, (this._sw.lat + this._ne.lat) / 2);\n }\n\n /**\n * Returns the southwest corner of the bounding box.\n *\n * @returns {LngLat} The southwest corner of the bounding box.\n * @example\n * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.getSouthWest(); // LngLat {lng: -73.9876, lat: 40.7661}\n */\n getSouthWest(): LngLat { return this._sw; }\n\n /**\n * Returns the northeast corner of the bounding box.\n *\n * @returns {LngLat} The northeast corner of the bounding box.\n * @example\n * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.getNorthEast(); // LngLat {lng: -73.9397, lat: 40.8002}\n */\n getNorthEast(): LngLat { return this._ne; }\n\n /**\n * Returns the northwest corner of the bounding box.\n *\n * @returns {LngLat} The northwest corner of the bounding box.\n * @example\n * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.getNorthWest(); // LngLat {lng: -73.9876, lat: 40.8002}\n */\n getNorthWest(): LngLat { return new LngLat(this.getWest(), this.getNorth()); }\n\n /**\n * Returns the southeast corner of the bounding box.\n *\n * @returns {LngLat} The southeast corner of the bounding box.\n * @example\n * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.getSouthEast(); // LngLat {lng: -73.9397, lat: 40.7661}\n */\n getSouthEast(): LngLat { return new LngLat(this.getEast(), this.getSouth()); }\n\n /**\n * Returns the west edge of the bounding box.\n *\n * @returns {number} The west edge of the bounding box.\n * @example\n * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.getWest(); // -73.9876\n */\n getWest(): number { return this._sw.lng; }\n\n /**\n * Returns the south edge of the bounding box.\n *\n * @returns {number} The south edge of the bounding box.\n * @example\n * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.getSouth(); // 40.7661\n */\n getSouth(): number { return this._sw.lat; }\n\n /**\n * Returns the east edge of the bounding box.\n *\n * @returns {number} The east edge of the bounding box.\n * @example\n * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.getEast(); // -73.9397\n */\n getEast(): number { return this._ne.lng; }\n\n /**\n * Returns the north edge of the bounding box.\n *\n * @returns {number} The north edge of the bounding box.\n * @example\n * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.getNorth(); // 40.8002\n */\n getNorth(): number { return this._ne.lat; }\n\n /**\n * Returns the bounding box represented as an array.\n *\n * @returns {Array<Array<number>>} The bounding box represented as an array, consisting of the\n * southwest and northeast coordinates of the bounding represented as arrays of numbers.\n * @example\n * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.toArray(); // = [[-73.9876, 40.7661], [-73.9397, 40.8002]]\n */\n toArray(): [[number, number], [number, number]] {\n return [this._sw.toArray(), this._ne.toArray()];\n }\n\n /**\n * Return the bounding box represented as a string.\n *\n * @returns {string} The bounding box represents as a string of the format\n * `'LngLatBounds(LngLat(lng, lat), LngLat(lng, lat))'`.\n * @example\n * const llb = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * llb.toString(); // = \"LngLatBounds(LngLat(-73.9876, 40.7661), LngLat(-73.9397, 40.8002))\"\n */\n toString(): string {\n return `LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`;\n }\n\n /**\n * Check if the bounding box is an empty/`null`-type box.\n *\n * @returns {boolean} True if bounds have been defined, otherwise false.\n * @example\n * const llb = new mapboxgl.LngLatBounds();\n * llb.isEmpty(); // true\n * llb.setNorthEast([-73.9876, 40.7661]);\n * llb.setSouthWest([-73.9397, 40.8002]);\n * llb.isEmpty(); // false\n */\n isEmpty(): boolean {\n return !(this._sw && this._ne);\n }\n\n /**\n * Check if the point is within the bounding box.\n *\n * @param {LngLatLike} lnglat Geographic point to check against.\n * @returns {boolean} True if the point is within the bounding box.\n * @example\n * const llb = new mapboxgl.LngLatBounds(\n * new mapboxgl.LngLat(-73.9876, 40.7661),\n * new mapboxgl.LngLat(-73.9397, 40.8002)\n * );\n *\n * const ll = new mapboxgl.LngLat(-73.9567, 40.7789);\n *\n * console.log(llb.contains(ll)); // = true\n */\n contains(lnglat: LngLatLike): boolean {\n const {lng, lat} = LngLat.convert(lnglat);\n\n const containsLatitude = this._sw.lat <= lat && lat <= this._ne.lat;\n let containsLongitude = this._sw.lng <= lng && lng <= this._ne.lng;\n if (this._sw.lng > this._ne.lng) { // wrapped coordinates\n containsLongitude = this._sw.lng >= lng && lng >= this._ne.lng;\n }\n\n return containsLatitude && containsLongitude;\n }\n\n /**\n * Converts an array to a `LngLatBounds` object.\n *\n * If a `LngLatBounds` object is passed in, the function returns it unchanged.\n *\n * Internally, the function calls `LngLat#convert` to convert arrays to `LngLat` values.\n *\n * @param {LngLatBoundsLike} input An array of two coordinates to convert, or a `LngLatBounds` object to return.\n * @returns {LngLatBounds} A new `LngLatBounds` object, if a conversion occurred, or the original `LngLatBounds` object.\n * @example\n * const arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]];\n * const llb = mapboxgl.LngLatBounds.convert(arr);\n * console.log(llb); // = LngLatBounds {_sw: LngLat {lng: -73.9876, lat: 40.7661}, _ne: LngLat {lng: -73.9397, lat: 40.8002}}\n */\n static convert(input: LngLatBoundsLike): LngLatBounds {\n if (!input || input instanceof LngLatBounds) return input;\n return new LngLatBounds(input);\n }\n}\n\n/**\n * A {@link LngLatBounds} object, an array of {@link LngLatLike} objects in [sw, ne] order,\n * or an array of numbers in [west, south, east, north] order.\n *\n * @typedef {LngLatBounds | [LngLatLike, LngLatLike] | [number, number, number, number]} LngLatBoundsLike\n * @example\n * const v1 = new mapboxgl.LngLatBounds(\n * new mapboxgl.LngLat(-73.9876, 40.7661),\n * new mapboxgl.LngLat(-73.9397, 40.8002)\n * );\n * const v2 = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002]);\n * const v3 = [[-73.9876, 40.7661], [-73.9397, 40.8002]];\n */\nexport type LngLatBoundsLike = LngLatBounds | [LngLatLike, LngLatLike] | [number, number, number, number];\n\nexport default LngLatBounds;\n","/**\n * Common utilities\n * @module glMatrix\n */\n// Configuration Constants\nexport var EPSILON = 0.000001;\nexport var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;\nexport var RANDOM = Math.random;\n/**\n * Sets the type of array used when creating new vectors and matrices\n *\n * @param {Float32ArrayConstructor | ArrayConstructor} type Array type, such as Float32Array or Array\n */\n\nexport function setMatrixArrayType(type) {\n ARRAY_TYPE = type;\n}\nvar degree = Math.PI / 180;\n/**\n * Convert Degree To Radian\n *\n * @param {Number} a Angle in Degrees\n */\n\nexport function toRadian(a) {\n return a * degree;\n}\n/**\n * Tests whether or not the arguments have approximately the same value, within an absolute\n * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less\n * than or equal to 1.0, and a relative tolerance is used for larger values)\n *\n * @param {Number} a The first number to test.\n * @param {Number} b The second number to test.\n * @returns {Boolean} True if the numbers are approximately equal, false otherwise.\n */\n\nexport function equals(a, b) {\n return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b));\n}\nif (!Math.hypot) Math.hypot = function () {\n var y = 0,\n i = arguments.length;\n\n while (i--) {\n y += arguments[i] * arguments[i];\n }\n\n return Math.sqrt(y);\n};","import * as glMatrix from \"./common.js\";\n/**\n * 4x4 Matrix<br>Format: column-major, when typed out it looks like row-major<br>The matrices are being post multiplied.\n * @module mat4\n */\n\n/**\n * Creates a new identity mat4\n *\n * @returns {mat4} a new 4x4 matrix\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(16);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n }\n\n out[0] = 1;\n out[5] = 1;\n out[10] = 1;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a new mat4 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat4} a matrix to clone\n * @returns {mat4} a new 4x4 matrix\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Copy the values from one mat4 to another\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Create a new mat4 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} A new mat4\n */\n\nexport function fromValues(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n var out = new glMatrix.ARRAY_TYPE(16);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n/**\n * Set the components of a mat4 to the given values\n *\n * @param {mat4} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\n * @returns {mat4} out\n */\n\nexport function set(out, m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m03;\n out[4] = m10;\n out[5] = m11;\n out[6] = m12;\n out[7] = m13;\n out[8] = m20;\n out[9] = m21;\n out[10] = m22;\n out[11] = m23;\n out[12] = m30;\n out[13] = m31;\n out[14] = m32;\n out[15] = m33;\n return out;\n}\n/**\n * Set a mat4 to the identity matrix\n *\n * @param {mat4} out the receiving matrix\n * @returns {mat4} out\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Transpose the values of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a12 = a[6],\n a13 = a[7];\n var a23 = a[11];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a01;\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a02;\n out[9] = a12;\n out[11] = a[14];\n out[12] = a03;\n out[13] = a13;\n out[14] = a23;\n } else {\n out[0] = a[0];\n out[1] = a[4];\n out[2] = a[8];\n out[3] = a[12];\n out[4] = a[1];\n out[5] = a[5];\n out[6] = a[9];\n out[7] = a[13];\n out[8] = a[2];\n out[9] = a[6];\n out[10] = a[10];\n out[11] = a[14];\n out[12] = a[3];\n out[13] = a[7];\n out[14] = a[11];\n out[15] = a[15];\n }\n\n return out;\n}\n/**\n * Inverts a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;\n out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;\n out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;\n out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;\n out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;\n out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;\n out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;\n return out;\n}\n/**\n * Calculates the adjugate of a mat4\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the source matrix\n * @returns {mat4} out\n */\n\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22);\n out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22));\n out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12);\n out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12));\n out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22));\n out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22);\n out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12));\n out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12);\n out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21);\n out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21));\n out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11);\n out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11));\n out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21));\n out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21);\n out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11));\n out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11);\n return out;\n}\n/**\n * Calculates the determinant of a mat4\n *\n * @param {ReadonlyMat4} a the source matrix\n * @returns {Number} determinant of a\n */\n\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n}\n/**\n * Multiplies two mat4s\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15]; // Cache only the current line of the second matrix\n\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[4];\n b1 = b[5];\n b2 = b[6];\n b3 = b[7];\n out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[8];\n b1 = b[9];\n b2 = b[10];\n b3 = b[11];\n out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n b0 = b[12];\n b1 = b[13];\n b2 = b[14];\n b3 = b[15];\n out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;\n out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;\n out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;\n out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;\n return out;\n}\n/**\n * Translate a mat4 by the given vector\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to translate\n * @param {ReadonlyVec3} v vector to translate by\n * @returns {mat4} out\n */\n\nexport function translate(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n\n if (a === out) {\n out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];\n out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];\n out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];\n out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];\n } else {\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a03;\n out[4] = a10;\n out[5] = a11;\n out[6] = a12;\n out[7] = a13;\n out[8] = a20;\n out[9] = a21;\n out[10] = a22;\n out[11] = a23;\n out[12] = a00 * x + a10 * y + a20 * z + a[12];\n out[13] = a01 * x + a11 * y + a21 * z + a[13];\n out[14] = a02 * x + a12 * y + a22 * z + a[14];\n out[15] = a03 * x + a13 * y + a23 * z + a[15];\n }\n\n return out;\n}\n/**\n * Scales the mat4 by the dimensions in the given vec3 not using vectorization\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {ReadonlyVec3} v the vec3 to scale the matrix by\n * @returns {mat4} out\n **/\n\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1],\n z = v[2];\n out[0] = a[0] * x;\n out[1] = a[1] * x;\n out[2] = a[2] * x;\n out[3] = a[3] * x;\n out[4] = a[4] * y;\n out[5] = a[5] * y;\n out[6] = a[6] * y;\n out[7] = a[7] * y;\n out[8] = a[8] * z;\n out[9] = a[9] * z;\n out[10] = a[10] * z;\n out[11] = a[11] * z;\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n return out;\n}\n/**\n * Rotates a mat4 by the given angle around the given axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\n\nexport function rotate(out, a, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.hypot(x, y, z);\n var s, c, t;\n var a00, a01, a02, a03;\n var a10, a11, a12, a13;\n var a20, a21, a22, a23;\n var b00, b01, b02;\n var b10, b11, b12;\n var b20, b21, b22;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c;\n a00 = a[0];\n a01 = a[1];\n a02 = a[2];\n a03 = a[3];\n a10 = a[4];\n a11 = a[5];\n a12 = a[6];\n a13 = a[7];\n a20 = a[8];\n a21 = a[9];\n a22 = a[10];\n a23 = a[11]; // Construct the elements of the rotation matrix\n\n b00 = x * x * t + c;\n b01 = y * x * t + z * s;\n b02 = z * x * t - y * s;\n b10 = x * y * t - z * s;\n b11 = y * y * t + c;\n b12 = z * y * t + x * s;\n b20 = x * z * t + y * s;\n b21 = y * z * t - x * s;\n b22 = z * z * t + c; // Perform rotation-specific matrix multiplication\n\n out[0] = a00 * b00 + a10 * b01 + a20 * b02;\n out[1] = a01 * b00 + a11 * b01 + a21 * b02;\n out[2] = a02 * b00 + a12 * b01 + a22 * b02;\n out[3] = a03 * b00 + a13 * b01 + a23 * b02;\n out[4] = a00 * b10 + a10 * b11 + a20 * b12;\n out[5] = a01 * b10 + a11 * b11 + a21 * b12;\n out[6] = a02 * b10 + a12 * b11 + a22 * b12;\n out[7] = a03 * b10 + a13 * b11 + a23 * b12;\n out[8] = a00 * b20 + a10 * b21 + a20 * b22;\n out[9] = a01 * b20 + a11 * b21 + a21 * b22;\n out[10] = a02 * b20 + a12 * b21 + a22 * b22;\n out[11] = a03 * b20 + a13 * b21 + a23 * b22;\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n }\n\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the X axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateX(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[4] = a10 * c + a20 * s;\n out[5] = a11 * c + a21 * s;\n out[6] = a12 * c + a22 * s;\n out[7] = a13 * c + a23 * s;\n out[8] = a20 * c - a10 * s;\n out[9] = a21 * c - a11 * s;\n out[10] = a22 * c - a12 * s;\n out[11] = a23 * c - a13 * s;\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the Y axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateY(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a20 = a[8];\n var a21 = a[9];\n var a22 = a[10];\n var a23 = a[11];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged rows\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[0] = a00 * c - a20 * s;\n out[1] = a01 * c - a21 * s;\n out[2] = a02 * c - a22 * s;\n out[3] = a03 * c - a23 * s;\n out[8] = a00 * s + a20 * c;\n out[9] = a01 * s + a21 * c;\n out[10] = a02 * s + a22 * c;\n out[11] = a03 * s + a23 * c;\n return out;\n}\n/**\n * Rotates a matrix by the given angle around the Z axis\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function rotateZ(out, a, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n var a00 = a[0];\n var a01 = a[1];\n var a02 = a[2];\n var a03 = a[3];\n var a10 = a[4];\n var a11 = a[5];\n var a12 = a[6];\n var a13 = a[7];\n\n if (a !== out) {\n // If the source and destination differ, copy the unchanged last row\n out[8] = a[8];\n out[9] = a[9];\n out[10] = a[10];\n out[11] = a[11];\n out[12] = a[12];\n out[13] = a[13];\n out[14] = a[14];\n out[15] = a[15];\n } // Perform axis-specific matrix multiplication\n\n\n out[0] = a00 * c + a10 * s;\n out[1] = a01 * c + a11 * s;\n out[2] = a02 * c + a12 * s;\n out[3] = a03 * c + a13 * s;\n out[4] = a10 * c - a00 * s;\n out[5] = a11 * c - a01 * s;\n out[6] = a12 * c - a02 * s;\n out[7] = a13 * c - a03 * s;\n return out;\n}\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\n\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.scale(dest, dest, vec);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyVec3} v Scaling vector\n * @returns {mat4} out\n */\n\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = v[1];\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = v[2];\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a given angle around a given axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotate(dest, dest, rad, axis);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @param {ReadonlyVec3} axis the axis to rotate around\n * @returns {mat4} out\n */\n\nexport function fromRotation(out, rad, axis) {\n var x = axis[0],\n y = axis[1],\n z = axis[2];\n var len = Math.hypot(x, y, z);\n var s, c, t;\n\n if (len < glMatrix.EPSILON) {\n return null;\n }\n\n len = 1 / len;\n x *= len;\n y *= len;\n z *= len;\n s = Math.sin(rad);\n c = Math.cos(rad);\n t = 1 - c; // Perform rotation-specific matrix multiplication\n\n out[0] = x * x * t + c;\n out[1] = y * x * t + z * s;\n out[2] = z * x * t - y * s;\n out[3] = 0;\n out[4] = x * y * t - z * s;\n out[5] = y * y * t + c;\n out[6] = z * y * t + x * s;\n out[7] = 0;\n out[8] = x * z * t + y * s;\n out[9] = y * z * t - x * s;\n out[10] = z * z * t + c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the X axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateX(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromXRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = c;\n out[6] = s;\n out[7] = 0;\n out[8] = 0;\n out[9] = -s;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the Y axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateY(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromYRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = c;\n out[1] = 0;\n out[2] = -s;\n out[3] = 0;\n out[4] = 0;\n out[5] = 1;\n out[6] = 0;\n out[7] = 0;\n out[8] = s;\n out[9] = 0;\n out[10] = c;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from the given angle around the Z axis\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.rotateZ(dest, dest, rad);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat4} out\n */\n\nexport function fromZRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad); // Perform axis-specific matrix multiplication\n\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = 0;\n out[4] = -s;\n out[5] = c;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 1;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation and vector translation\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslation(out, q, v) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - (yy + zz);\n out[1] = xy + wz;\n out[2] = xz - wy;\n out[3] = 0;\n out[4] = xy - wz;\n out[5] = 1 - (xx + zz);\n out[6] = yz + wx;\n out[7] = 0;\n out[8] = xz + wy;\n out[9] = yz - wx;\n out[10] = 1 - (xx + yy);\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a new mat4 from a dual quat.\n *\n * @param {mat4} out Matrix\n * @param {ReadonlyQuat2} a Dual Quaternion\n * @returns {mat4} mat4 receiving operation result\n */\n\nexport function fromQuat2(out, a) {\n var translation = new glMatrix.ARRAY_TYPE(3);\n var bx = -a[0],\n by = -a[1],\n bz = -a[2],\n bw = a[3],\n ax = a[4],\n ay = a[5],\n az = a[6],\n aw = a[7];\n var magnitude = bx * bx + by * by + bz * bz + bw * bw; //Only scale if it makes sense\n\n if (magnitude > 0) {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2 / magnitude;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2 / magnitude;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2 / magnitude;\n } else {\n translation[0] = (ax * bw + aw * bx + ay * bz - az * by) * 2;\n translation[1] = (ay * bw + aw * by + az * bx - ax * bz) * 2;\n translation[2] = (az * bw + aw * bz + ax * by - ay * bx) * 2;\n }\n\n fromRotationTranslation(out, a, translation);\n return out;\n}\n/**\n * Returns the translation vector component of a transformation\n * matrix. If a matrix is built with fromRotationTranslation,\n * the returned vector will be the same as the translation vector\n * originally supplied.\n * @param {vec3} out Vector to receive translation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\n\nexport function getTranslation(out, mat) {\n out[0] = mat[12];\n out[1] = mat[13];\n out[2] = mat[14];\n return out;\n}\n/**\n * Returns the scaling factor component of a transformation\n * matrix. If a matrix is built with fromRotationTranslationScale\n * with a normalized Quaternion paramter, the returned vector will be\n * the same as the scaling vector\n * originally supplied.\n * @param {vec3} out Vector to receive scaling factor component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {vec3} out\n */\n\nexport function getScaling(out, mat) {\n var m11 = mat[0];\n var m12 = mat[1];\n var m13 = mat[2];\n var m21 = mat[4];\n var m22 = mat[5];\n var m23 = mat[6];\n var m31 = mat[8];\n var m32 = mat[9];\n var m33 = mat[10];\n out[0] = Math.hypot(m11, m12, m13);\n out[1] = Math.hypot(m21, m22, m23);\n out[2] = Math.hypot(m31, m32, m33);\n return out;\n}\n/**\n * Returns a quaternion representing the rotational component\n * of a transformation matrix. If a matrix is built with\n * fromRotationTranslation, the returned quaternion will be the\n * same as the quaternion originally supplied.\n * @param {quat} out Quaternion to receive the rotation component\n * @param {ReadonlyMat4} mat Matrix to be decomposed (input)\n * @return {quat} out\n */\n\nexport function getRotation(out, mat) {\n var scaling = new glMatrix.ARRAY_TYPE(3);\n getScaling(scaling, mat);\n var is1 = 1 / scaling[0];\n var is2 = 1 / scaling[1];\n var is3 = 1 / scaling[2];\n var sm11 = mat[0] * is1;\n var sm12 = mat[1] * is2;\n var sm13 = mat[2] * is3;\n var sm21 = mat[4] * is1;\n var sm22 = mat[5] * is2;\n var sm23 = mat[6] * is3;\n var sm31 = mat[8] * is1;\n var sm32 = mat[9] * is2;\n var sm33 = mat[10] * is3;\n var trace = sm11 + sm22 + sm33;\n var S = 0;\n\n if (trace > 0) {\n S = Math.sqrt(trace + 1.0) * 2;\n out[3] = 0.25 * S;\n out[0] = (sm23 - sm32) / S;\n out[1] = (sm31 - sm13) / S;\n out[2] = (sm12 - sm21) / S;\n } else if (sm11 > sm22 && sm11 > sm33) {\n S = Math.sqrt(1.0 + sm11 - sm22 - sm33) * 2;\n out[3] = (sm23 - sm32) / S;\n out[0] = 0.25 * S;\n out[1] = (sm12 + sm21) / S;\n out[2] = (sm31 + sm13) / S;\n } else if (sm22 > sm33) {\n S = Math.sqrt(1.0 + sm22 - sm11 - sm33) * 2;\n out[3] = (sm31 - sm13) / S;\n out[0] = (sm12 + sm21) / S;\n out[1] = 0.25 * S;\n out[2] = (sm23 + sm32) / S;\n } else {\n S = Math.sqrt(1.0 + sm33 - sm11 - sm22) * 2;\n out[3] = (sm12 - sm21) / S;\n out[0] = (sm31 + sm13) / S;\n out[1] = (sm23 + sm32) / S;\n out[2] = 0.25 * S;\n }\n\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n * mat4.scale(dest, scale)\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslationScale(out, q, v, s) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n out[0] = (1 - (yy + zz)) * sx;\n out[1] = (xy + wz) * sx;\n out[2] = (xz - wy) * sx;\n out[3] = 0;\n out[4] = (xy - wz) * sy;\n out[5] = (1 - (xx + zz)) * sy;\n out[6] = (yz + wx) * sy;\n out[7] = 0;\n out[8] = (xz + wy) * sz;\n out[9] = (yz - wx) * sz;\n out[10] = (1 - (xx + yy)) * sz;\n out[11] = 0;\n out[12] = v[0];\n out[13] = v[1];\n out[14] = v[2];\n out[15] = 1;\n return out;\n}\n/**\n * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin\n * This is equivalent to (but much faster than):\n *\n * mat4.identity(dest);\n * mat4.translate(dest, vec);\n * mat4.translate(dest, origin);\n * let quatMat = mat4.create();\n * quat4.toMat4(quat, quatMat);\n * mat4.multiply(dest, quatMat);\n * mat4.scale(dest, scale)\n * mat4.translate(dest, negativeOrigin);\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {quat4} q Rotation quaternion\n * @param {ReadonlyVec3} v Translation vector\n * @param {ReadonlyVec3} s Scaling vector\n * @param {ReadonlyVec3} o The origin vector around which to scale and rotate\n * @returns {mat4} out\n */\n\nexport function fromRotationTranslationScaleOrigin(out, q, v, s, o) {\n // Quaternion math\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var xy = x * y2;\n var xz = x * z2;\n var yy = y * y2;\n var yz = y * z2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n var sx = s[0];\n var sy = s[1];\n var sz = s[2];\n var ox = o[0];\n var oy = o[1];\n var oz = o[2];\n var out0 = (1 - (yy + zz)) * sx;\n var out1 = (xy + wz) * sx;\n var out2 = (xz - wy) * sx;\n var out4 = (xy - wz) * sy;\n var out5 = (1 - (xx + zz)) * sy;\n var out6 = (yz + wx) * sy;\n var out8 = (xz + wy) * sz;\n var out9 = (yz - wx) * sz;\n var out10 = (1 - (xx + yy)) * sz;\n out[0] = out0;\n out[1] = out1;\n out[2] = out2;\n out[3] = 0;\n out[4] = out4;\n out[5] = out5;\n out[6] = out6;\n out[7] = 0;\n out[8] = out8;\n out[9] = out9;\n out[10] = out10;\n out[11] = 0;\n out[12] = v[0] + ox - (out0 * ox + out4 * oy + out8 * oz);\n out[13] = v[1] + oy - (out1 * ox + out5 * oy + out9 * oz);\n out[14] = v[2] + oz - (out2 * ox + out6 * oy + out10 * oz);\n out[15] = 1;\n return out;\n}\n/**\n * Calculates a 4x4 matrix from the given quaternion\n *\n * @param {mat4} out mat4 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat4} out\n */\n\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[1] = yx + wz;\n out[2] = zx - wy;\n out[3] = 0;\n out[4] = yx - wz;\n out[5] = 1 - xx - zz;\n out[6] = zy + wx;\n out[7] = 0;\n out[8] = zx + wy;\n out[9] = zy - wx;\n out[10] = 1 - xx - yy;\n out[11] = 0;\n out[12] = 0;\n out[13] = 0;\n out[14] = 0;\n out[15] = 1;\n return out;\n}\n/**\n * Generates a frustum matrix with the given bounds\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Number} left Left bound of the frustum\n * @param {Number} right Right bound of the frustum\n * @param {Number} bottom Bottom bound of the frustum\n * @param {Number} top Top bound of the frustum\n * @param {Number} near Near bound of the frustum\n * @param {Number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function frustum(out, left, right, bottom, top, near, far) {\n var rl = 1 / (right - left);\n var tb = 1 / (top - bottom);\n var nf = 1 / (near - far);\n out[0] = near * 2 * rl;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = near * 2 * tb;\n out[6] = 0;\n out[7] = 0;\n out[8] = (right + left) * rl;\n out[9] = (top + bottom) * tb;\n out[10] = (far + near) * nf;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[14] = far * near * 2 * nf;\n out[15] = 0;\n return out;\n}\n/**\n * Generates a perspective projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\n\nexport function perspectiveNO(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2),\n nf;\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n\n if (far != null && far !== Infinity) {\n nf = 1 / (near - far);\n out[10] = (far + near) * nf;\n out[14] = 2 * far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -2 * near;\n }\n\n return out;\n}\n/**\n * Alias for {@link mat4.perspectiveNO}\n * @function\n */\n\nexport var perspective = perspectiveNO;\n/**\n * Generates a perspective projection matrix suitable for WebGPU with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n * Passing null/undefined/no value for far will generate infinite projection matrix.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} fovy Vertical field of view in radians\n * @param {number} aspect Aspect ratio. typically viewport width/height\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum, can be null or Infinity\n * @returns {mat4} out\n */\n\nexport function perspectiveZO(out, fovy, aspect, near, far) {\n var f = 1.0 / Math.tan(fovy / 2),\n nf;\n out[0] = f / aspect;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = f;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[11] = -1;\n out[12] = 0;\n out[13] = 0;\n out[15] = 0;\n\n if (far != null && far !== Infinity) {\n nf = 1 / (near - far);\n out[10] = far * nf;\n out[14] = far * near * nf;\n } else {\n out[10] = -1;\n out[14] = -near;\n }\n\n return out;\n}\n/**\n * Generates a perspective projection matrix with the given field of view.\n * This is primarily useful for generating projection matrices to be used\n * with the still experiemental WebVR API.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function perspectiveFromFieldOfView(out, fov, near, far) {\n var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);\n var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);\n var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);\n var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);\n var xScale = 2.0 / (leftTan + rightTan);\n var yScale = 2.0 / (upTan + downTan);\n out[0] = xScale;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n out[4] = 0.0;\n out[5] = yScale;\n out[6] = 0.0;\n out[7] = 0.0;\n out[8] = -((leftTan - rightTan) * xScale * 0.5);\n out[9] = (upTan - downTan) * yScale * 0.5;\n out[10] = far / (near - far);\n out[11] = -1.0;\n out[12] = 0.0;\n out[13] = 0.0;\n out[14] = far * near / (near - far);\n out[15] = 0.0;\n return out;\n}\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [-1, 1],\n * which matches WebGL/OpenGL's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function orthoNO(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = 2 * nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = (far + near) * nf;\n out[15] = 1;\n return out;\n}\n/**\n * Alias for {@link mat4.orthoNO}\n * @function\n */\n\nexport var ortho = orthoNO;\n/**\n * Generates a orthogonal projection matrix with the given bounds.\n * The near/far clip planes correspond to a normalized device coordinate Z range of [0, 1],\n * which matches WebGPU/Vulkan/DirectX/Metal's clip volume.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {number} left Left bound of the frustum\n * @param {number} right Right bound of the frustum\n * @param {number} bottom Bottom bound of the frustum\n * @param {number} top Top bound of the frustum\n * @param {number} near Near bound of the frustum\n * @param {number} far Far bound of the frustum\n * @returns {mat4} out\n */\n\nexport function orthoZO(out, left, right, bottom, top, near, far) {\n var lr = 1 / (left - right);\n var bt = 1 / (bottom - top);\n var nf = 1 / (near - far);\n out[0] = -2 * lr;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 0;\n out[5] = -2 * bt;\n out[6] = 0;\n out[7] = 0;\n out[8] = 0;\n out[9] = 0;\n out[10] = nf;\n out[11] = 0;\n out[12] = (left + right) * lr;\n out[13] = (top + bottom) * bt;\n out[14] = near * nf;\n out[15] = 1;\n return out;\n}\n/**\n * Generates a look-at matrix with the given eye position, focal point, and up axis.\n * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\n\nexport function lookAt(out, eye, center, up) {\n var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;\n var eyex = eye[0];\n var eyey = eye[1];\n var eyez = eye[2];\n var upx = up[0];\n var upy = up[1];\n var upz = up[2];\n var centerx = center[0];\n var centery = center[1];\n var centerz = center[2];\n\n if (Math.abs(eyex - centerx) < glMatrix.EPSILON && Math.abs(eyey - centery) < glMatrix.EPSILON && Math.abs(eyez - centerz) < glMatrix.EPSILON) {\n return identity(out);\n }\n\n z0 = eyex - centerx;\n z1 = eyey - centery;\n z2 = eyez - centerz;\n len = 1 / Math.hypot(z0, z1, z2);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n x0 = upy * z2 - upz * z1;\n x1 = upz * z0 - upx * z2;\n x2 = upx * z1 - upy * z0;\n len = Math.hypot(x0, x1, x2);\n\n if (!len) {\n x0 = 0;\n x1 = 0;\n x2 = 0;\n } else {\n len = 1 / len;\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n y0 = z1 * x2 - z2 * x1;\n y1 = z2 * x0 - z0 * x2;\n y2 = z0 * x1 - z1 * x0;\n len = Math.hypot(y0, y1, y2);\n\n if (!len) {\n y0 = 0;\n y1 = 0;\n y2 = 0;\n } else {\n len = 1 / len;\n y0 *= len;\n y1 *= len;\n y2 *= len;\n }\n\n out[0] = x0;\n out[1] = y0;\n out[2] = z0;\n out[3] = 0;\n out[4] = x1;\n out[5] = y1;\n out[6] = z1;\n out[7] = 0;\n out[8] = x2;\n out[9] = y2;\n out[10] = z2;\n out[11] = 0;\n out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);\n out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);\n out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);\n out[15] = 1;\n return out;\n}\n/**\n * Generates a matrix that makes something look at something else.\n *\n * @param {mat4} out mat4 frustum matrix will be written into\n * @param {ReadonlyVec3} eye Position of the viewer\n * @param {ReadonlyVec3} center Point the viewer is looking at\n * @param {ReadonlyVec3} up vec3 pointing up\n * @returns {mat4} out\n */\n\nexport function targetTo(out, eye, target, up) {\n var eyex = eye[0],\n eyey = eye[1],\n eyez = eye[2],\n upx = up[0],\n upy = up[1],\n upz = up[2];\n var z0 = eyex - target[0],\n z1 = eyey - target[1],\n z2 = eyez - target[2];\n var len = z0 * z0 + z1 * z1 + z2 * z2;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n z0 *= len;\n z1 *= len;\n z2 *= len;\n }\n\n var x0 = upy * z2 - upz * z1,\n x1 = upz * z0 - upx * z2,\n x2 = upx * z1 - upy * z0;\n len = x0 * x0 + x1 * x1 + x2 * x2;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n x0 *= len;\n x1 *= len;\n x2 *= len;\n }\n\n out[0] = x0;\n out[1] = x1;\n out[2] = x2;\n out[3] = 0;\n out[4] = z1 * x2 - z2 * x1;\n out[5] = z2 * x0 - z0 * x2;\n out[6] = z0 * x1 - z1 * x0;\n out[7] = 0;\n out[8] = z0;\n out[9] = z1;\n out[10] = z2;\n out[11] = 0;\n out[12] = eyex;\n out[13] = eyey;\n out[14] = eyez;\n out[15] = 1;\n return out;\n}\n/**\n * Returns a string representation of a mat4\n *\n * @param {ReadonlyMat4} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\n\nexport function str(a) {\n return \"mat4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \", \" + a[9] + \", \" + a[10] + \", \" + a[11] + \", \" + a[12] + \", \" + a[13] + \", \" + a[14] + \", \" + a[15] + \")\";\n}\n/**\n * Returns Frobenius norm of a mat4\n *\n * @param {ReadonlyMat4} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15]);\n}\n/**\n * Adds two mat4's\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n out[9] = a[9] + b[9];\n out[10] = a[10] + b[10];\n out[11] = a[11] + b[11];\n out[12] = a[12] + b[12];\n out[13] = a[13] + b[13];\n out[14] = a[14] + b[14];\n out[15] = a[15] + b[15];\n return out;\n}\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @returns {mat4} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n out[9] = a[9] - b[9];\n out[10] = a[10] - b[10];\n out[11] = a[11] - b[11];\n out[12] = a[12] - b[12];\n out[13] = a[13] - b[13];\n out[14] = a[14] - b[14];\n out[15] = a[15] - b[15];\n return out;\n}\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat4} out the receiving matrix\n * @param {ReadonlyMat4} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat4} out\n */\n\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n out[9] = a[9] * b;\n out[10] = a[10] * b;\n out[11] = a[11] * b;\n out[12] = a[12] * b;\n out[13] = a[13] * b;\n out[14] = a[14] * b;\n out[15] = a[15] * b;\n return out;\n}\n/**\n * Adds two mat4's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat4} out the receiving vector\n * @param {ReadonlyMat4} a the first operand\n * @param {ReadonlyMat4} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat4} out\n */\n\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n out[9] = a[9] + b[9] * scale;\n out[10] = a[10] + b[10] * scale;\n out[11] = a[11] + b[11] * scale;\n out[12] = a[12] + b[12] * scale;\n out[13] = a[13] + b[13] * scale;\n out[14] = a[14] + b[14] * scale;\n out[15] = a[15] + b[15] * scale;\n return out;\n}\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8] && a[9] === b[9] && a[10] === b[10] && a[11] === b[11] && a[12] === b[12] && a[13] === b[13] && a[14] === b[14] && a[15] === b[15];\n}\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat4} a The first matrix.\n * @param {ReadonlyMat4} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7];\n var a8 = a[8],\n a9 = a[9],\n a10 = a[10],\n a11 = a[11];\n var a12 = a[12],\n a13 = a[13],\n a14 = a[14],\n a15 = a[15];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n var b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7];\n var b8 = b[8],\n b9 = b[9],\n b10 = b[10],\n b11 = b[11];\n var b12 = b[12],\n b13 = b[13],\n b14 = b[14],\n b15 = b[15];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)) && Math.abs(a9 - b9) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a9), Math.abs(b9)) && Math.abs(a10 - b10) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a10), Math.abs(b10)) && Math.abs(a11 - b11) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a11), Math.abs(b11)) && Math.abs(a12 - b12) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a12), Math.abs(b12)) && Math.abs(a13 - b13) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a13), Math.abs(b13)) && Math.abs(a14 - b14) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a14), Math.abs(b14)) && Math.abs(a15 - b15) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a15), Math.abs(b15));\n}\n/**\n * Alias for {@link mat4.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link mat4.subtract}\n * @function\n */\n\nexport var sub = subtract;","import * as glMatrix from \"./common.js\";\n/**\n * 3 Dimensional Vector\n * @module vec3\n */\n\n/**\n * Creates a new, empty vec3\n *\n * @returns {vec3} a new 3D vector\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(3);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n\n return out;\n}\n/**\n * Creates a new vec3 initialized with values from an existing vector\n *\n * @param {ReadonlyVec3} a vector to clone\n * @returns {vec3} a new 3D vector\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n/**\n * Calculates the length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport function length(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n return Math.hypot(x, y, z);\n}\n/**\n * Creates a new vec3 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} a new 3D vector\n */\n\nexport function fromValues(x, y, z) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n/**\n * Copy the values from one vec3 to another\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the source vector\n * @returns {vec3} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n/**\n * Set the components of a vec3 to the given values\n *\n * @param {vec3} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @returns {vec3} out\n */\n\nexport function set(out, x, y, z) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n/**\n * Adds two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n return out;\n}\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n return out;\n}\n/**\n * Multiplies two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n return out;\n}\n/**\n * Divides two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n return out;\n}\n/**\n * Math.ceil the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to ceil\n * @returns {vec3} out\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n return out;\n}\n/**\n * Math.floor the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to floor\n * @returns {vec3} out\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n return out;\n}\n/**\n * Returns the minimum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n return out;\n}\n/**\n * Returns the maximum of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n return out;\n}\n/**\n * Math.round the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to round\n * @returns {vec3} out\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n out[2] = Math.round(a[2]);\n return out;\n}\n/**\n * Scales a vec3 by a scalar number\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec3} out\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n return out;\n}\n/**\n * Adds two vec3's after scaling the second operand by a scalar value\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec3} out\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n return out;\n}\n/**\n * Calculates the euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} distance between a and b\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n return Math.hypot(x, y, z);\n}\n/**\n * Calculates the squared euclidian distance between two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} squared distance between a and b\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n return x * x + y * y + z * z;\n}\n/**\n * Calculates the squared length of a vec3\n *\n * @param {ReadonlyVec3} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\n\nexport function squaredLength(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n return x * x + y * y + z * z;\n}\n/**\n * Negates the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to negate\n * @returns {vec3} out\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n return out;\n}\n/**\n * Returns the inverse of the components of a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to invert\n * @returns {vec3} out\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n return out;\n}\n/**\n * Normalize a vec3\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a vector to normalize\n * @returns {vec3} out\n */\n\nexport function normalize(out, a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var len = x * x + y * y + z * z;\n\n if (len > 0) {\n //TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n out[2] = a[2] * len;\n return out;\n}\n/**\n * Calculates the dot product of two vec3's\n *\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {Number} dot product of a and b\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];\n}\n/**\n * Computes the cross product of two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @returns {vec3} out\n */\n\nexport function cross(out, a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2];\n var bx = b[0],\n by = b[1],\n bz = b[2];\n out[0] = ay * bz - az * by;\n out[1] = az * bx - ax * bz;\n out[2] = ax * by - ay * bx;\n return out;\n}\n/**\n * Performs a linear interpolation between two vec3's\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0];\n var ay = a[1];\n var az = a[2];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n return out;\n}\n/**\n * Performs a hermite interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function hermite(out, a, b, c, d, t) {\n var factorTimes2 = t * t;\n var factor1 = factorTimes2 * (2 * t - 3) + 1;\n var factor2 = factorTimes2 * (t - 2) + t;\n var factor3 = factorTimes2 * (t - 1);\n var factor4 = factorTimes2 * (3 - 2 * t);\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n/**\n * Performs a bezier interpolation with two control points\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the first operand\n * @param {ReadonlyVec3} b the second operand\n * @param {ReadonlyVec3} c the third operand\n * @param {ReadonlyVec3} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec3} out\n */\n\nexport function bezier(out, a, b, c, d, t) {\n var inverseFactor = 1 - t;\n var inverseFactorTimesTwo = inverseFactor * inverseFactor;\n var factorTimes2 = t * t;\n var factor1 = inverseFactorTimesTwo * inverseFactor;\n var factor2 = 3 * t * inverseFactorTimesTwo;\n var factor3 = 3 * factorTimes2 * inverseFactor;\n var factor4 = factorTimes2 * t;\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec3} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\n * @returns {vec3} out\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0;\n var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n var z = glMatrix.RANDOM() * 2.0 - 1.0;\n var zScale = Math.sqrt(1.0 - z * z) * scale;\n out[0] = Math.cos(r) * zScale;\n out[1] = Math.sin(r) * zScale;\n out[2] = z * scale;\n return out;\n}\n/**\n * Transforms the vec3 with a mat4.\n * 4th vector component is implicitly '1'\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec3} out\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var w = m[3] * x + m[7] * y + m[11] * z + m[15];\n w = w || 1.0;\n out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;\n out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;\n out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;\n return out;\n}\n/**\n * Transforms the vec3 with a mat3.\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyMat3} m the 3x3 matrix to transform with\n * @returns {vec3} out\n */\n\nexport function transformMat3(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n out[0] = x * m[0] + y * m[3] + z * m[6];\n out[1] = x * m[1] + y * m[4] + z * m[7];\n out[2] = x * m[2] + y * m[5] + z * m[8];\n return out;\n}\n/**\n * Transforms the vec3 with a quat\n * Can also be used for dual quaternions. (Multiply it with the real part)\n *\n * @param {vec3} out the receiving vector\n * @param {ReadonlyVec3} a the vector to transform\n * @param {ReadonlyQuat} q quaternion to transform with\n * @returns {vec3} out\n */\n\nexport function transformQuat(out, a, q) {\n // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3];\n var x = a[0],\n y = a[1],\n z = a[2]; // var qvec = [qx, qy, qz];\n // var uv = vec3.cross([], qvec, a);\n\n var uvx = qy * z - qz * y,\n uvy = qz * x - qx * z,\n uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);\n\n var uuvx = qy * uvz - qz * uvy,\n uuvy = qz * uvx - qx * uvz,\n uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);\n\n var w2 = qw * 2;\n uvx *= w2;\n uvy *= w2;\n uvz *= w2; // vec3.scale(uuv, uuv, 2);\n\n uuvx *= 2;\n uuvy *= 2;\n uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));\n\n out[0] = x + uvx + uuvx;\n out[1] = y + uvy + uuvy;\n out[2] = z + uvz + uuvz;\n return out;\n}\n/**\n * Rotate a 3D vector around the x-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateX(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[0];\n r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);\n r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Rotate a 3D vector around the y-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateY(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);\n r[1] = p[1];\n r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Rotate a 3D vector around the z-axis\n * @param {vec3} out The receiving vec3\n * @param {ReadonlyVec3} a The vec3 point to rotate\n * @param {ReadonlyVec3} b The origin of the rotation\n * @param {Number} rad The angle of rotation in radians\n * @returns {vec3} out\n */\n\nexport function rotateZ(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);\n r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);\n r[2] = p[2]; //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\n * Get the angle between two 3D vectors\n * @param {ReadonlyVec3} a The first operand\n * @param {ReadonlyVec3} b The second operand\n * @returns {Number} The angle in radians\n */\n\nexport function angle(a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2],\n bx = b[0],\n by = b[1],\n bz = b[2],\n mag1 = Math.sqrt(ax * ax + ay * ay + az * az),\n mag2 = Math.sqrt(bx * bx + by * by + bz * bz),\n mag = mag1 * mag2,\n cosine = mag && dot(a, b) / mag;\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n/**\n * Set the components of a vec3 to zero\n *\n * @param {vec3} out the receiving vector\n * @returns {vec3} out\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n return out;\n}\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec3} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"vec3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \")\";\n}\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];\n}\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec3} a The first vector.\n * @param {ReadonlyVec3} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2));\n}\n/**\n * Alias for {@link vec3.subtract}\n * @function\n */\n\nexport var sub = subtract;\n/**\n * Alias for {@link vec3.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link vec3.divide}\n * @function\n */\n\nexport var div = divide;\n/**\n * Alias for {@link vec3.distance}\n * @function\n */\n\nexport var dist = distance;\n/**\n * Alias for {@link vec3.squaredDistance}\n * @function\n */\n\nexport var sqrDist = squaredDistance;\n/**\n * Alias for {@link vec3.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Alias for {@link vec3.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Perform some operation over an array of vec3s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 3;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n }\n\n return a;\n };\n}();","import * as glMatrix from \"./common.js\";\n/**\n * 3x3 Matrix\n * @module mat3\n */\n\n/**\n * Creates a new identity mat3\n *\n * @returns {mat3} a new 3x3 matrix\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(9);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n }\n\n out[0] = 1;\n out[4] = 1;\n out[8] = 1;\n return out;\n}\n/**\n * Copies the upper-left 3x3 values into the given mat3.\n *\n * @param {mat3} out the receiving 3x3 matrix\n * @param {ReadonlyMat4} a the source 4x4 matrix\n * @returns {mat3} out\n */\n\nexport function fromMat4(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[4];\n out[4] = a[5];\n out[5] = a[6];\n out[6] = a[8];\n out[7] = a[9];\n out[8] = a[10];\n return out;\n}\n/**\n * Creates a new mat3 initialized with values from an existing matrix\n *\n * @param {ReadonlyMat3} a matrix to clone\n * @returns {mat3} a new 3x3 matrix\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Copy the values from one mat3 to another\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Create a new mat3 with the given values\n *\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\n * @returns {mat3} A new mat3\n */\n\nexport function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\n * Set the components of a mat3 to the given values\n *\n * @param {mat3} out the receiving matrix\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\n * @param {Number} m10 Component in column 1, row 0 position (index 3)\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\n * @returns {mat3} out\n */\n\nexport function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\n * Set a mat3 to the identity matrix\n *\n * @param {mat3} out the receiving matrix\n * @returns {mat3} out\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Transpose the values of a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function transpose(out, a) {\n // If we are transposing ourselves we can skip a few steps but have to cache some values\n if (out === a) {\n var a01 = a[1],\n a02 = a[2],\n a12 = a[5];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a01;\n out[5] = a[7];\n out[6] = a02;\n out[7] = a12;\n } else {\n out[0] = a[0];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a[1];\n out[4] = a[4];\n out[5] = a[7];\n out[6] = a[2];\n out[7] = a[5];\n out[8] = a[8];\n }\n\n return out;\n}\n/**\n * Inverts a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b01 = a22 * a11 - a12 * a21;\n var b11 = -a22 * a10 + a12 * a20;\n var b21 = a21 * a10 - a11 * a20; // Calculate the determinant\n\n var det = a00 * b01 + a01 * b11 + a02 * b21;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = b01 * det;\n out[1] = (-a22 * a01 + a02 * a21) * det;\n out[2] = (a12 * a01 - a02 * a11) * det;\n out[3] = b11 * det;\n out[4] = (a22 * a00 - a02 * a20) * det;\n out[5] = (-a12 * a00 + a02 * a10) * det;\n out[6] = b21 * det;\n out[7] = (-a21 * a00 + a01 * a20) * det;\n out[8] = (a11 * a00 - a01 * a10) * det;\n return out;\n}\n/**\n * Calculates the adjugate of a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the source matrix\n * @returns {mat3} out\n */\n\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n out[0] = a11 * a22 - a12 * a21;\n out[1] = a02 * a21 - a01 * a22;\n out[2] = a01 * a12 - a02 * a11;\n out[3] = a12 * a20 - a10 * a22;\n out[4] = a00 * a22 - a02 * a20;\n out[5] = a02 * a10 - a00 * a12;\n out[6] = a10 * a21 - a11 * a20;\n out[7] = a01 * a20 - a00 * a21;\n out[8] = a00 * a11 - a01 * a10;\n return out;\n}\n/**\n * Calculates the determinant of a mat3\n *\n * @param {ReadonlyMat3} a the source matrix\n * @returns {Number} determinant of a\n */\n\nexport function determinant(a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);\n}\n/**\n * Multiplies two mat3's\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b00 = b[0],\n b01 = b[1],\n b02 = b[2];\n var b10 = b[3],\n b11 = b[4],\n b12 = b[5];\n var b20 = b[6],\n b21 = b[7],\n b22 = b[8];\n out[0] = b00 * a00 + b01 * a10 + b02 * a20;\n out[1] = b00 * a01 + b01 * a11 + b02 * a21;\n out[2] = b00 * a02 + b01 * a12 + b02 * a22;\n out[3] = b10 * a00 + b11 * a10 + b12 * a20;\n out[4] = b10 * a01 + b11 * a11 + b12 * a21;\n out[5] = b10 * a02 + b11 * a12 + b12 * a22;\n out[6] = b20 * a00 + b21 * a10 + b22 * a20;\n out[7] = b20 * a01 + b21 * a11 + b22 * a21;\n out[8] = b20 * a02 + b21 * a12 + b22 * a22;\n return out;\n}\n/**\n * Translate a mat3 by the given vector\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to translate\n * @param {ReadonlyVec2} v vector to translate by\n * @returns {mat3} out\n */\n\nexport function translate(out, a, v) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n x = v[0],\n y = v[1];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a10;\n out[4] = a11;\n out[5] = a12;\n out[6] = x * a00 + y * a10 + a20;\n out[7] = x * a01 + y * a11 + a21;\n out[8] = x * a02 + y * a12 + a22;\n return out;\n}\n/**\n * Rotates a mat3 by the given angle\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat3} out\n */\n\nexport function rotate(out, a, rad) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c * a00 + s * a10;\n out[1] = c * a01 + s * a11;\n out[2] = c * a02 + s * a12;\n out[3] = c * a10 - s * a00;\n out[4] = c * a11 - s * a01;\n out[5] = c * a12 - s * a02;\n out[6] = a20;\n out[7] = a21;\n out[8] = a22;\n return out;\n}\n/**\n * Scales the mat3 by the dimensions in the given vec2\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to rotate\n * @param {ReadonlyVec2} v the vec2 to scale the matrix by\n * @returns {mat3} out\n **/\n\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1];\n out[0] = x * a[0];\n out[1] = x * a[1];\n out[2] = x * a[2];\n out[3] = y * a[3];\n out[4] = y * a[4];\n out[5] = y * a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\n * Creates a matrix from a vector translation\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.translate(dest, dest, vec);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyVec2} v Translation vector\n * @returns {mat3} out\n */\n\nexport function fromTranslation(out, v) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = 1;\n out[5] = 0;\n out[6] = v[0];\n out[7] = v[1];\n out[8] = 1;\n return out;\n}\n/**\n * Creates a matrix from a given angle\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.rotate(dest, dest, rad);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {Number} rad the angle to rotate the matrix by\n * @returns {mat3} out\n */\n\nexport function fromRotation(out, rad) {\n var s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = -s;\n out[4] = c;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Creates a matrix from a vector scaling\n * This is equivalent to (but much faster than):\n *\n * mat3.identity(dest);\n * mat3.scale(dest, dest, vec);\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyVec2} v Scaling vector\n * @returns {mat3} out\n */\n\nexport function fromScaling(out, v) {\n out[0] = v[0];\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = v[1];\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\n * Copies the values from a mat2d into a mat3\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat2d} a the matrix to copy\n * @returns {mat3} out\n **/\n\nexport function fromMat2d(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = 0;\n out[3] = a[2];\n out[4] = a[3];\n out[5] = 0;\n out[6] = a[4];\n out[7] = a[5];\n out[8] = 1;\n return out;\n}\n/**\n * Calculates a 3x3 matrix from the given quaternion\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyQuat} q Quaternion to create matrix from\n *\n * @returns {mat3} out\n */\n\nexport function fromQuat(out, q) {\n var x = q[0],\n y = q[1],\n z = q[2],\n w = q[3];\n var x2 = x + x;\n var y2 = y + y;\n var z2 = z + z;\n var xx = x * x2;\n var yx = y * x2;\n var yy = y * y2;\n var zx = z * x2;\n var zy = z * y2;\n var zz = z * z2;\n var wx = w * x2;\n var wy = w * y2;\n var wz = w * z2;\n out[0] = 1 - yy - zz;\n out[3] = yx - wz;\n out[6] = zx + wy;\n out[1] = yx + wz;\n out[4] = 1 - xx - zz;\n out[7] = zy - wx;\n out[2] = zx - wy;\n out[5] = zy + wx;\n out[8] = 1 - xx - yy;\n return out;\n}\n/**\n * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix\n *\n * @param {mat3} out mat3 receiving operation result\n * @param {ReadonlyMat4} a Mat4 to derive the normal matrix from\n *\n * @returns {mat3} out\n */\n\nexport function normalFromMat4(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n return out;\n}\n/**\n * Generates a 2D projection matrix with the given bounds\n *\n * @param {mat3} out mat3 frustum matrix will be written into\n * @param {number} width Width of your gl context\n * @param {number} height Height of gl context\n * @returns {mat3} out\n */\n\nexport function projection(out, width, height) {\n out[0] = 2 / width;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = -2 / height;\n out[5] = 0;\n out[6] = -1;\n out[7] = 1;\n out[8] = 1;\n return out;\n}\n/**\n * Returns a string representation of a mat3\n *\n * @param {ReadonlyMat3} a matrix to represent as a string\n * @returns {String} string representation of the matrix\n */\n\nexport function str(a) {\n return \"mat3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \")\";\n}\n/**\n * Returns Frobenius norm of a mat3\n *\n * @param {ReadonlyMat3} a the matrix to calculate Frobenius norm of\n * @returns {Number} Frobenius norm\n */\n\nexport function frob(a) {\n return Math.hypot(a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7], a[8]);\n}\n/**\n * Adds two mat3's\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n out[4] = a[4] + b[4];\n out[5] = a[5] + b[5];\n out[6] = a[6] + b[6];\n out[7] = a[7] + b[7];\n out[8] = a[8] + b[8];\n return out;\n}\n/**\n * Subtracts matrix b from matrix a\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @returns {mat3} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n out[4] = a[4] - b[4];\n out[5] = a[5] - b[5];\n out[6] = a[6] - b[6];\n out[7] = a[7] - b[7];\n out[8] = a[8] - b[8];\n return out;\n}\n/**\n * Multiply each element of the matrix by a scalar.\n *\n * @param {mat3} out the receiving matrix\n * @param {ReadonlyMat3} a the matrix to scale\n * @param {Number} b amount to scale the matrix's elements by\n * @returns {mat3} out\n */\n\nexport function multiplyScalar(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n out[4] = a[4] * b;\n out[5] = a[5] * b;\n out[6] = a[6] * b;\n out[7] = a[7] * b;\n out[8] = a[8] * b;\n return out;\n}\n/**\n * Adds two mat3's after multiplying each element of the second operand by a scalar value.\n *\n * @param {mat3} out the receiving vector\n * @param {ReadonlyMat3} a the first operand\n * @param {ReadonlyMat3} b the second operand\n * @param {Number} scale the amount to scale b's elements by before adding\n * @returns {mat3} out\n */\n\nexport function multiplyScalarAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n out[4] = a[4] + b[4] * scale;\n out[5] = a[5] + b[5] * scale;\n out[6] = a[6] + b[6] * scale;\n out[7] = a[7] + b[7] * scale;\n out[8] = a[8] + b[8] * scale;\n return out;\n}\n/**\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyMat3} a The first matrix.\n * @param {ReadonlyMat3} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8];\n}\n/**\n * Returns whether or not the matrices have approximately the same elements in the same position.\n *\n * @param {ReadonlyMat3} a The first matrix.\n * @param {ReadonlyMat3} b The second matrix.\n * @returns {Boolean} True if the matrices are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3],\n a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7],\n a8 = a[8];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8));\n}\n/**\n * Alias for {@link mat3.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link mat3.subtract}\n * @function\n */\n\nexport var sub = subtract;","import * as glMatrix from \"./common.js\";\n/**\n * 4 Dimensional Vector\n * @module vec4\n */\n\n/**\n * Creates a new, empty vec4\n *\n * @returns {vec4} a new 4D vector\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(4);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n }\n\n return out;\n}\n/**\n * Creates a new vec4 initialized with values from an existing vector\n *\n * @param {ReadonlyVec4} a vector to clone\n * @returns {vec4} a new 4D vector\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Creates a new vec4 initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} a new 4D vector\n */\n\nexport function fromValues(x, y, z, w) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n/**\n * Copy the values from one vec4 to another\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the source vector\n * @returns {vec4} out\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Set the components of a vec4 to the given values\n *\n * @param {vec4} out the receiving vector\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {vec4} out\n */\n\nexport function set(out, x, y, z, w) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = w;\n return out;\n}\n/**\n * Adds two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function add(out, a, b) {\n out[0] = a[0] + b[0];\n out[1] = a[1] + b[1];\n out[2] = a[2] + b[2];\n out[3] = a[3] + b[3];\n return out;\n}\n/**\n * Subtracts vector b from vector a\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function subtract(out, a, b) {\n out[0] = a[0] - b[0];\n out[1] = a[1] - b[1];\n out[2] = a[2] - b[2];\n out[3] = a[3] - b[3];\n return out;\n}\n/**\n * Multiplies two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function multiply(out, a, b) {\n out[0] = a[0] * b[0];\n out[1] = a[1] * b[1];\n out[2] = a[2] * b[2];\n out[3] = a[3] * b[3];\n return out;\n}\n/**\n * Divides two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function divide(out, a, b) {\n out[0] = a[0] / b[0];\n out[1] = a[1] / b[1];\n out[2] = a[2] / b[2];\n out[3] = a[3] / b[3];\n return out;\n}\n/**\n * Math.ceil the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to ceil\n * @returns {vec4} out\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n out[2] = Math.ceil(a[2]);\n out[3] = Math.ceil(a[3]);\n return out;\n}\n/**\n * Math.floor the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to floor\n * @returns {vec4} out\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n out[2] = Math.floor(a[2]);\n out[3] = Math.floor(a[3]);\n return out;\n}\n/**\n * Returns the minimum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function min(out, a, b) {\n out[0] = Math.min(a[0], b[0]);\n out[1] = Math.min(a[1], b[1]);\n out[2] = Math.min(a[2], b[2]);\n out[3] = Math.min(a[3], b[3]);\n return out;\n}\n/**\n * Returns the maximum of two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {vec4} out\n */\n\nexport function max(out, a, b) {\n out[0] = Math.max(a[0], b[0]);\n out[1] = Math.max(a[1], b[1]);\n out[2] = Math.max(a[2], b[2]);\n out[3] = Math.max(a[3], b[3]);\n return out;\n}\n/**\n * Math.round the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to round\n * @returns {vec4} out\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n out[2] = Math.round(a[2]);\n out[3] = Math.round(a[3]);\n return out;\n}\n/**\n * Scales a vec4 by a scalar number\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {vec4} out\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n out[2] = a[2] * b;\n out[3] = a[3] * b;\n return out;\n}\n/**\n * Adds two vec4's after scaling the second operand by a scalar value\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} scale the amount to scale b by before adding\n * @returns {vec4} out\n */\n\nexport function scaleAndAdd(out, a, b, scale) {\n out[0] = a[0] + b[0] * scale;\n out[1] = a[1] + b[1] * scale;\n out[2] = a[2] + b[2] * scale;\n out[3] = a[3] + b[3] * scale;\n return out;\n}\n/**\n * Calculates the euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} distance between a and b\n */\n\nexport function distance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n var w = b[3] - a[3];\n return Math.hypot(x, y, z, w);\n}\n/**\n * Calculates the squared euclidian distance between two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} squared distance between a and b\n */\n\nexport function squaredDistance(a, b) {\n var x = b[0] - a[0];\n var y = b[1] - a[1];\n var z = b[2] - a[2];\n var w = b[3] - a[3];\n return x * x + y * y + z * z + w * w;\n}\n/**\n * Calculates the length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport function length(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n return Math.hypot(x, y, z, w);\n}\n/**\n * Calculates the squared length of a vec4\n *\n * @param {ReadonlyVec4} a vector to calculate squared length of\n * @returns {Number} squared length of a\n */\n\nexport function squaredLength(a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n return x * x + y * y + z * z + w * w;\n}\n/**\n * Negates the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to negate\n * @returns {vec4} out\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = -a[3];\n return out;\n}\n/**\n * Returns the inverse of the components of a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to invert\n * @returns {vec4} out\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n out[2] = 1.0 / a[2];\n out[3] = 1.0 / a[3];\n return out;\n}\n/**\n * Normalize a vec4\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a vector to normalize\n * @returns {vec4} out\n */\n\nexport function normalize(out, a) {\n var x = a[0];\n var y = a[1];\n var z = a[2];\n var w = a[3];\n var len = x * x + y * y + z * z + w * w;\n\n if (len > 0) {\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = x * len;\n out[1] = y * len;\n out[2] = z * len;\n out[3] = w * len;\n return out;\n}\n/**\n * Calculates the dot product of two vec4's\n *\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @returns {Number} dot product of a and b\n */\n\nexport function dot(a, b) {\n return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];\n}\n/**\n * Returns the cross-product of three vectors in a 4-dimensional space\n *\n * @param {ReadonlyVec4} result the receiving vector\n * @param {ReadonlyVec4} U the first vector\n * @param {ReadonlyVec4} V the second vector\n * @param {ReadonlyVec4} W the third vector\n * @returns {vec4} result\n */\n\nexport function cross(out, u, v, w) {\n var A = v[0] * w[1] - v[1] * w[0],\n B = v[0] * w[2] - v[2] * w[0],\n C = v[0] * w[3] - v[3] * w[0],\n D = v[1] * w[2] - v[2] * w[1],\n E = v[1] * w[3] - v[3] * w[1],\n F = v[2] * w[3] - v[3] * w[2];\n var G = u[0];\n var H = u[1];\n var I = u[2];\n var J = u[3];\n out[0] = H * F - I * E + J * D;\n out[1] = -(G * F) + I * C - J * B;\n out[2] = G * E - H * C + J * A;\n out[3] = -(G * D) + H * B - I * A;\n return out;\n}\n/**\n * Performs a linear interpolation between two vec4's\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the first operand\n * @param {ReadonlyVec4} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {vec4} out\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0];\n var ay = a[1];\n var az = a[2];\n var aw = a[3];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n out[3] = aw + t * (b[3] - aw);\n return out;\n}\n/**\n * Generates a random vector with the given scale\n *\n * @param {vec4} out the receiving vector\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\n * @returns {vec4} out\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0; // Marsaglia, George. Choosing a Point from the Surface of a\n // Sphere. Ann. Math. Statist. 43 (1972), no. 2, 645--646.\n // http://projecteuclid.org/euclid.aoms/1177692644;\n\n var v1, v2, v3, v4;\n var s1, s2;\n\n do {\n v1 = glMatrix.RANDOM() * 2 - 1;\n v2 = glMatrix.RANDOM() * 2 - 1;\n s1 = v1 * v1 + v2 * v2;\n } while (s1 >= 1);\n\n do {\n v3 = glMatrix.RANDOM() * 2 - 1;\n v4 = glMatrix.RANDOM() * 2 - 1;\n s2 = v3 * v3 + v4 * v4;\n } while (s2 >= 1);\n\n var d = Math.sqrt((1 - s1) / s2);\n out[0] = scale * v1;\n out[1] = scale * v2;\n out[2] = scale * v3 * d;\n out[3] = scale * v4 * d;\n return out;\n}\n/**\n * Transforms the vec4 with a mat4.\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyMat4} m matrix to transform with\n * @returns {vec4} out\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n out[0] = m[0] * x + m[4] * y + m[8] * z + m[12] * w;\n out[1] = m[1] * x + m[5] * y + m[9] * z + m[13] * w;\n out[2] = m[2] * x + m[6] * y + m[10] * z + m[14] * w;\n out[3] = m[3] * x + m[7] * y + m[11] * z + m[15] * w;\n return out;\n}\n/**\n * Transforms the vec4 with a quat\n *\n * @param {vec4} out the receiving vector\n * @param {ReadonlyVec4} a the vector to transform\n * @param {ReadonlyQuat} q quaternion to transform with\n * @returns {vec4} out\n */\n\nexport function transformQuat(out, a, q) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3]; // calculate quat * vec\n\n var ix = qw * x + qy * z - qz * y;\n var iy = qw * y + qz * x - qx * z;\n var iz = qw * z + qx * y - qy * x;\n var iw = -qx * x - qy * y - qz * z; // calculate result * inverse quat\n\n out[0] = ix * qw + iw * -qx + iy * -qz - iz * -qy;\n out[1] = iy * qw + iw * -qy + iz * -qx - ix * -qz;\n out[2] = iz * qw + iw * -qz + ix * -qy - iy * -qx;\n out[3] = a[3];\n return out;\n}\n/**\n * Set the components of a vec4 to zero\n *\n * @param {vec4} out the receiving vector\n * @returns {vec4} out\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n out[3] = 0.0;\n return out;\n}\n/**\n * Returns a string representation of a vector\n *\n * @param {ReadonlyVec4} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"vec4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function exactEquals(a, b) {\n return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];\n}\n/**\n * Returns whether or not the vectors have approximately the same elements in the same position.\n *\n * @param {ReadonlyVec4} a The first vector.\n * @param {ReadonlyVec4} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport function equals(a, b) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3));\n}\n/**\n * Alias for {@link vec4.subtract}\n * @function\n */\n\nexport var sub = subtract;\n/**\n * Alias for {@link vec4.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Alias for {@link vec4.divide}\n * @function\n */\n\nexport var div = divide;\n/**\n * Alias for {@link vec4.distance}\n * @function\n */\n\nexport var dist = distance;\n/**\n * Alias for {@link vec4.squaredDistance}\n * @function\n */\n\nexport var sqrDist = squaredDistance;\n/**\n * Alias for {@link vec4.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Alias for {@link vec4.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Perform some operation over an array of vec4s.\n *\n * @param {Array} a the array of vectors to iterate over\n * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed\n * @param {Number} offset Number of elements to skip at the beginning of the array\n * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array\n * @param {Function} fn Function to call for each vector in the array\n * @param {Object} [arg] additional argument to pass to fn\n * @returns {Array} a\n * @function\n */\n\nexport var forEach = function () {\n var vec = create();\n return function (a, stride, offset, count, fn, arg) {\n var i, l;\n\n if (!stride) {\n stride = 4;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n vec[3] = a[i + 3];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n a[i + 3] = vec[3];\n }\n\n return a;\n };\n}();","import * as glMatrix from \"./common.js\";\nimport * as mat3 from \"./mat3.js\";\nimport * as vec3 from \"./vec3.js\";\nimport * as vec4 from \"./vec4.js\";\n/**\n * Quaternion\n * @module quat\n */\n\n/**\n * Creates a new identity quat\n *\n * @returns {quat} a new quaternion\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(4);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n\n out[3] = 1;\n return out;\n}\n/**\n * Set a quat to the identity quaternion\n *\n * @param {quat} out the receiving quaternion\n * @returns {quat} out\n */\n\nexport function identity(out) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 1;\n return out;\n}\n/**\n * Sets a quat from the given angle and rotation axis,\n * then returns it.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyVec3} axis the axis around which to rotate\n * @param {Number} rad the angle in radians\n * @returns {quat} out\n **/\n\nexport function setAxisAngle(out, axis, rad) {\n rad = rad * 0.5;\n var s = Math.sin(rad);\n out[0] = s * axis[0];\n out[1] = s * axis[1];\n out[2] = s * axis[2];\n out[3] = Math.cos(rad);\n return out;\n}\n/**\n * Gets the rotation axis and angle for a given\n * quaternion. If a quaternion is created with\n * setAxisAngle, this method will return the same\n * values as providied in the original parameter list\n * OR functionally equivalent values.\n * Example: The quaternion formed by axis [0, 0, 1] and\n * angle -90 is the same as the quaternion formed by\n * [0, 0, 1] and 270. This method favors the latter.\n * @param {vec3} out_axis Vector receiving the axis of rotation\n * @param {ReadonlyQuat} q Quaternion to be decomposed\n * @return {Number} Angle, in radians, of the rotation\n */\n\nexport function getAxisAngle(out_axis, q) {\n var rad = Math.acos(q[3]) * 2.0;\n var s = Math.sin(rad / 2.0);\n\n if (s > glMatrix.EPSILON) {\n out_axis[0] = q[0] / s;\n out_axis[1] = q[1] / s;\n out_axis[2] = q[2] / s;\n } else {\n // If s is zero, return any axis (no rotation - axis does not matter)\n out_axis[0] = 1;\n out_axis[1] = 0;\n out_axis[2] = 0;\n }\n\n return rad;\n}\n/**\n * Gets the angular distance between two unit quaternions\n *\n * @param {ReadonlyQuat} a Origin unit quaternion\n * @param {ReadonlyQuat} b Destination unit quaternion\n * @return {Number} Angle, in radians, between the two quaternions\n */\n\nexport function getAngle(a, b) {\n var dotproduct = dot(a, b);\n return Math.acos(2 * dotproduct * dotproduct - 1);\n}\n/**\n * Multiplies two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {quat} out\n */\n\nexport function multiply(out, a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = b[0],\n by = b[1],\n bz = b[2],\n bw = b[3];\n out[0] = ax * bw + aw * bx + ay * bz - az * by;\n out[1] = ay * bw + aw * by + az * bx - ax * bz;\n out[2] = az * bw + aw * bz + ax * by - ay * bx;\n out[3] = aw * bw - ax * bx - ay * by - az * bz;\n return out;\n}\n/**\n * Rotates a quaternion by the given angle about the X axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\n\nexport function rotateX(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw + aw * bx;\n out[1] = ay * bw + az * bx;\n out[2] = az * bw - ay * bx;\n out[3] = aw * bw - ax * bx;\n return out;\n}\n/**\n * Rotates a quaternion by the given angle about the Y axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\n\nexport function rotateY(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var by = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw - az * by;\n out[1] = ay * bw + aw * by;\n out[2] = az * bw + ax * by;\n out[3] = aw * bw - ay * by;\n return out;\n}\n/**\n * Rotates a quaternion by the given angle about the Z axis\n *\n * @param {quat} out quat receiving operation result\n * @param {ReadonlyQuat} a quat to rotate\n * @param {number} rad angle (in radians) to rotate\n * @returns {quat} out\n */\n\nexport function rotateZ(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bz = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw + ay * bz;\n out[1] = ay * bw - ax * bz;\n out[2] = az * bw + aw * bz;\n out[3] = aw * bw - az * bz;\n return out;\n}\n/**\n * Calculates the W component of a quat from the X, Y, and Z components.\n * Assumes that quaternion is 1 unit in length.\n * Any existing W component will be ignored.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate W component of\n * @returns {quat} out\n */\n\nexport function calculateW(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2];\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));\n return out;\n}\n/**\n * Calculate the exponential of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @returns {quat} out\n */\n\nexport function exp(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n var r = Math.sqrt(x * x + y * y + z * z);\n var et = Math.exp(w);\n var s = r > 0 ? et * Math.sin(r) / r : 0;\n out[0] = x * s;\n out[1] = y * s;\n out[2] = z * s;\n out[3] = et * Math.cos(r);\n return out;\n}\n/**\n * Calculate the natural logarithm of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @returns {quat} out\n */\n\nexport function ln(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n var r = Math.sqrt(x * x + y * y + z * z);\n var t = r > 0 ? Math.atan2(r, w) / r : 0;\n out[0] = x * t;\n out[1] = y * t;\n out[2] = z * t;\n out[3] = 0.5 * Math.log(x * x + y * y + z * z + w * w);\n return out;\n}\n/**\n * Calculate the scalar power of a unit quaternion.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate the exponential of\n * @param {Number} b amount to scale the quaternion by\n * @returns {quat} out\n */\n\nexport function pow(out, a, b) {\n ln(out, a);\n scale(out, out, b);\n exp(out, out);\n return out;\n}\n/**\n * Performs a spherical linear interpolation between two quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n */\n\nexport function slerp(out, a, b, t) {\n // benchmarks:\n // http://jsperf.com/quaternion-slerp-implementations\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = b[0],\n by = b[1],\n bz = b[2],\n bw = b[3];\n var omega, cosom, sinom, scale0, scale1; // calc cosine\n\n cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)\n\n if (cosom < 0.0) {\n cosom = -cosom;\n bx = -bx;\n by = -by;\n bz = -bz;\n bw = -bw;\n } // calculate coefficients\n\n\n if (1.0 - cosom > glMatrix.EPSILON) {\n // standard case (slerp)\n omega = Math.acos(cosom);\n sinom = Math.sin(omega);\n scale0 = Math.sin((1.0 - t) * omega) / sinom;\n scale1 = Math.sin(t * omega) / sinom;\n } else {\n // \"from\" and \"to\" quaternions are very close\n // ... so we can do a linear interpolation\n scale0 = 1.0 - t;\n scale1 = t;\n } // calculate final values\n\n\n out[0] = scale0 * ax + scale1 * bx;\n out[1] = scale0 * ay + scale1 * by;\n out[2] = scale0 * az + scale1 * bz;\n out[3] = scale0 * aw + scale1 * bw;\n return out;\n}\n/**\n * Generates a random unit quaternion\n *\n * @param {quat} out the receiving quaternion\n * @returns {quat} out\n */\n\nexport function random(out) {\n // Implementation of http://planning.cs.uiuc.edu/node198.html\n // TODO: Calling random 3 times is probably not the fastest solution\n var u1 = glMatrix.RANDOM();\n var u2 = glMatrix.RANDOM();\n var u3 = glMatrix.RANDOM();\n var sqrt1MinusU1 = Math.sqrt(1 - u1);\n var sqrtU1 = Math.sqrt(u1);\n out[0] = sqrt1MinusU1 * Math.sin(2.0 * Math.PI * u2);\n out[1] = sqrt1MinusU1 * Math.cos(2.0 * Math.PI * u2);\n out[2] = sqrtU1 * Math.sin(2.0 * Math.PI * u3);\n out[3] = sqrtU1 * Math.cos(2.0 * Math.PI * u3);\n return out;\n}\n/**\n * Calculates the inverse of a quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate inverse of\n * @returns {quat} out\n */\n\nexport function invert(out, a) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;\n var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0\n\n out[0] = -a0 * invDot;\n out[1] = -a1 * invDot;\n out[2] = -a2 * invDot;\n out[3] = a3 * invDot;\n return out;\n}\n/**\n * Calculates the conjugate of a quat\n * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quat to calculate conjugate of\n * @returns {quat} out\n */\n\nexport function conjugate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = a[3];\n return out;\n}\n/**\n * Creates a quaternion from the given 3x3 rotation matrix.\n *\n * NOTE: The resultant quaternion is not normalized, so you should be sure\n * to renormalize the quaternion yourself where necessary.\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyMat3} m rotation matrix\n * @returns {quat} out\n * @function\n */\n\nexport function fromMat3(out, m) {\n // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\n // article \"Quaternion Calculus and Fast Animation\".\n var fTrace = m[0] + m[4] + m[8];\n var fRoot;\n\n if (fTrace > 0.0) {\n // |w| > 1/2, may as well choose w > 1/2\n fRoot = Math.sqrt(fTrace + 1.0); // 2w\n\n out[3] = 0.5 * fRoot;\n fRoot = 0.5 / fRoot; // 1/(4w)\n\n out[0] = (m[5] - m[7]) * fRoot;\n out[1] = (m[6] - m[2]) * fRoot;\n out[2] = (m[1] - m[3]) * fRoot;\n } else {\n // |w| <= 1/2\n var i = 0;\n if (m[4] > m[0]) i = 1;\n if (m[8] > m[i * 3 + i]) i = 2;\n var j = (i + 1) % 3;\n var k = (i + 2) % 3;\n fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);\n out[i] = 0.5 * fRoot;\n fRoot = 0.5 / fRoot;\n out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;\n out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;\n out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;\n }\n\n return out;\n}\n/**\n * Creates a quaternion from the given euler angle x, y, z.\n *\n * @param {quat} out the receiving quaternion\n * @param {x} Angle to rotate around X axis in degrees.\n * @param {y} Angle to rotate around Y axis in degrees.\n * @param {z} Angle to rotate around Z axis in degrees.\n * @returns {quat} out\n * @function\n */\n\nexport function fromEuler(out, x, y, z) {\n var halfToRad = 0.5 * Math.PI / 180.0;\n x *= halfToRad;\n y *= halfToRad;\n z *= halfToRad;\n var sx = Math.sin(x);\n var cx = Math.cos(x);\n var sy = Math.sin(y);\n var cy = Math.cos(y);\n var sz = Math.sin(z);\n var cz = Math.cos(z);\n out[0] = sx * cy * cz - cx * sy * sz;\n out[1] = cx * sy * cz + sx * cy * sz;\n out[2] = cx * cy * sz - sx * sy * cz;\n out[3] = cx * cy * cz + sx * sy * sz;\n return out;\n}\n/**\n * Returns a string representation of a quatenion\n *\n * @param {ReadonlyQuat} a vector to represent as a string\n * @returns {String} string representation of the vector\n */\n\nexport function str(a) {\n return \"quat(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\n * Creates a new quat initialized with values from an existing quaternion\n *\n * @param {ReadonlyQuat} a quaternion to clone\n * @returns {quat} a new quaternion\n * @function\n */\n\nexport var clone = vec4.clone;\n/**\n * Creates a new quat initialized with the given values\n *\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {quat} a new quaternion\n * @function\n */\n\nexport var fromValues = vec4.fromValues;\n/**\n * Copy the values from one quat to another\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the source quaternion\n * @returns {quat} out\n * @function\n */\n\nexport var copy = vec4.copy;\n/**\n * Set the components of a quat to the given values\n *\n * @param {quat} out the receiving quaternion\n * @param {Number} x X component\n * @param {Number} y Y component\n * @param {Number} z Z component\n * @param {Number} w W component\n * @returns {quat} out\n * @function\n */\n\nexport var set = vec4.set;\n/**\n * Adds two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {quat} out\n * @function\n */\n\nexport var add = vec4.add;\n/**\n * Alias for {@link quat.multiply}\n * @function\n */\n\nexport var mul = multiply;\n/**\n * Scales a quat by a scalar number\n *\n * @param {quat} out the receiving vector\n * @param {ReadonlyQuat} a the vector to scale\n * @param {Number} b amount to scale the vector by\n * @returns {quat} out\n * @function\n */\n\nexport var scale = vec4.scale;\n/**\n * Calculates the dot product of two quat's\n *\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @returns {Number} dot product of a and b\n * @function\n */\n\nexport var dot = vec4.dot;\n/**\n * Performs a linear interpolation between two quat's\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n * @function\n */\n\nexport var lerp = vec4.lerp;\n/**\n * Calculates the length of a quat\n *\n * @param {ReadonlyQuat} a vector to calculate length of\n * @returns {Number} length of a\n */\n\nexport var length = vec4.length;\n/**\n * Alias for {@link quat.length}\n * @function\n */\n\nexport var len = length;\n/**\n * Calculates the squared length of a quat\n *\n * @param {ReadonlyQuat} a vector to calculate squared length of\n * @returns {Number} squared length of a\n * @function\n */\n\nexport var squaredLength = vec4.squaredLength;\n/**\n * Alias for {@link quat.squaredLength}\n * @function\n */\n\nexport var sqrLen = squaredLength;\n/**\n * Normalize a quat\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a quaternion to normalize\n * @returns {quat} out\n * @function\n */\n\nexport var normalize = vec4.normalize;\n/**\n * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===)\n *\n * @param {ReadonlyQuat} a The first quaternion.\n * @param {ReadonlyQuat} b The second quaternion.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport var exactEquals = vec4.exactEquals;\n/**\n * Returns whether or not the quaternions have approximately the same elements in the same position.\n *\n * @param {ReadonlyQuat} a The first vector.\n * @param {ReadonlyQuat} b The second vector.\n * @returns {Boolean} True if the vectors are equal, false otherwise.\n */\n\nexport var equals = vec4.equals;\n/**\n * Sets a quaternion to represent the shortest rotation from one\n * vector to another.\n *\n * Both vectors are assumed to be unit length.\n *\n * @param {quat} out the receiving quaternion.\n * @param {ReadonlyVec3} a the initial vector\n * @param {ReadonlyVec3} b the destination vector\n * @returns {quat} out\n */\n\nexport var rotationTo = function () {\n var tmpvec3 = vec3.create();\n var xUnitVec3 = vec3.fromValues(1, 0, 0);\n var yUnitVec3 = vec3.fromValues(0, 1, 0);\n return function (out, a, b) {\n var dot = vec3.dot(a, b);\n\n if (dot < -0.999999) {\n vec3.cross(tmpvec3, xUnitVec3, a);\n if (vec3.len(tmpvec3) < 0.000001) vec3.cross(tmpvec3, yUnitVec3, a);\n vec3.normalize(tmpvec3, tmpvec3);\n setAxisAngle(out, tmpvec3, Math.PI);\n return out;\n } else if (dot > 0.999999) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 1;\n return out;\n } else {\n vec3.cross(tmpvec3, a, b);\n out[0] = tmpvec3[0];\n out[1] = tmpvec3[1];\n out[2] = tmpvec3[2];\n out[3] = 1 + dot;\n return normalize(out, out);\n }\n };\n}();\n/**\n * Performs a spherical linear interpolation with two control points\n *\n * @param {quat} out the receiving quaternion\n * @param {ReadonlyQuat} a the first operand\n * @param {ReadonlyQuat} b the second operand\n * @param {ReadonlyQuat} c the third operand\n * @param {ReadonlyQuat} d the fourth operand\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\n * @returns {quat} out\n */\n\nexport var sqlerp = function () {\n var temp1 = create();\n var temp2 = create();\n return function (out, a, b, c, d, t) {\n slerp(temp1, a, d, t);\n slerp(temp2, b, c, t);\n slerp(out, temp1, temp2, 2 * t * (1 - t));\n return out;\n };\n}();\n/**\n * Sets the specified quaternion with values corresponding to the given\n * axes. Each axis is a vec3 and is expected to be unit length and\n * perpendicular to all other specified axes.\n *\n * @param {ReadonlyVec3} view the vector representing the viewing direction\n * @param {ReadonlyVec3} right the vector representing the local \"right\" direction\n * @param {ReadonlyVec3} up the vector representing the local \"up\" direction\n * @returns {quat} out\n */\n\nexport var setAxes = function () {\n var matr = mat3.create();\n return function (out, view, right, up) {\n matr[0] = right[0];\n matr[3] = right[1];\n matr[6] = right[2];\n matr[1] = up[0];\n matr[4] = up[1];\n matr[7] = up[2];\n matr[2] = -view[0];\n matr[5] = -view[1];\n matr[8] = -view[2];\n return normalize(out, fromMat3(out, matr));\n };\n}();","// @flow\nimport {createLayout} from '../util/struct_array.js';\n\nimport type {StructArrayLayout} from '../util/struct_array.js';\n\nconst layout: StructArrayLayout = createLayout([\n {type: 'Float32', name: 'a_globe_pos', components: 3},\n {type: 'Float32', name: 'a_uv', components: 2}\n]);\n\nexport default layout;\nexport const {members, size, alignment} = layout;\n","// @flow\nimport {createLayout} from '../util/struct_array.js';\n\nimport type {StructArrayLayout} from '../util/struct_array.js';\n\nexport const posAttributesGlobeExt: StructArrayLayout = createLayout([\n {name: 'a_pos_3', components: 3, type: 'Int16'},\n]);\n\nexport default (createLayout([\n {name: 'a_pos', type: 'Int16', components: 2}\n]): StructArrayLayout);\n","// @flow\n\nimport {vec3, vec4} from 'gl-matrix';\nimport assert from 'assert';\n\nimport type {Vec3, Mat4} from 'gl-matrix';\n\nclass Ray {\n pos: Vec3;\n dir: Vec3;\n\n constructor(pos_: Vec3, dir_: Vec3) {\n this.pos = pos_;\n this.dir = dir_;\n }\n\n intersectsPlane(pt: Vec3, normal: Vec3, out: Vec3): boolean {\n const D = vec3.dot(normal, this.dir);\n\n // ray is parallel to plane, so it misses\n if (Math.abs(D) < 1e-6) { return false; }\n\n const t = (\n (pt[0] - this.pos[0]) * normal[0] +\n (pt[1] - this.pos[1]) * normal[1] +\n (pt[2] - this.pos[2]) * normal[2]) / D;\n\n out[0] = this.pos[0] + this.dir[0] * t;\n out[1] = this.pos[1] + this.dir[1] * t;\n out[2] = this.pos[2] + this.dir[2] * t;\n\n return true;\n }\n\n closestPointOnSphere(center: Vec3, r: number, out: Vec3): boolean {\n assert(vec3.squaredLength(this.dir) > 0.0 && r >= 0.0);\n\n if (vec3.equals(this.pos, center) || r === 0.0) {\n out[0] = out[1] = out[2] = 0;\n return false;\n }\n\n const [dx, dy, dz] = this.dir;\n\n const px = this.pos[0] - center[0];\n const py = this.pos[1] - center[1];\n const pz = this.pos[2] - center[2];\n\n const a = dx * dx + dy * dy + dz * dz;\n const b = 2.0 * (px * dx + py * dy + pz * dz);\n const c = (px * px + py * py + pz * pz) - r * r;\n const d = b * b - 4 * a * c;\n\n if (d < 0.0) {\n // No intersection, find distance between closest points\n const t = Math.max(-b / 2, 0.0);\n const gx = px + dx * t; // point to globe\n const gy = py + dy * t;\n const gz = pz + dz * t;\n const glen = Math.hypot(gx, gy, gz);\n out[0] = gx * r / glen;\n out[1] = gy * r / glen;\n out[2] = gz * r / glen;\n return false;\n\n } else {\n assert(a > 0.0);\n const t = (-b - Math.sqrt(d)) / (2.0 * a);\n\n if (t < 0.0) {\n // Ray is pointing away from the sphere\n const plen = Math.hypot(px, py, pz);\n out[0] = px * r / plen;\n out[1] = py * r / plen;\n out[2] = pz * r / plen;\n return false;\n\n } else {\n out[0] = px + dx * t;\n out[1] = py + dy * t;\n out[2] = pz + dz * t;\n return true;\n }\n }\n }\n}\n\nclass FrustumCorners {\n TL: [number, number, number];\n TR: [number, number, number];\n BR: [number, number, number];\n BL: [number, number, number];\n horizon: number;\n\n constructor(TL_: [number, number, number], TR_: [number, number, number], BR_: [number, number, number], BL_: [number, number, number], horizon_: number) {\n this.TL = TL_;\n this.TR = TR_;\n this.BR = BR_;\n this.BL = BL_;\n this.horizon = horizon_;\n }\n\n static fromInvProjectionMatrix(invProj: Array<number>, horizonFromTop: number, viewportHeight: number): FrustumCorners {\n const TLClip = [-1, 1, 1];\n const TRClip = [1, 1, 1];\n const BRClip = [1, -1, 1];\n const BLClip = [-1, -1, 1];\n\n const TL = vec3.transformMat4(TLClip, TLClip, invProj);\n const TR = vec3.transformMat4(TRClip, TRClip, invProj);\n const BR = vec3.transformMat4(BRClip, BRClip, invProj);\n const BL = vec3.transformMat4(BLClip, BLClip, invProj);\n\n return new FrustumCorners(TL, TR, BR, BL, horizonFromTop / viewportHeight);\n }\n}\n\nclass Frustum {\n points: Array<Array<number>>;\n planes: Array<Array<number>>;\n\n constructor(points_: Array<Array<number>>, planes_: Array<Array<number>>) {\n this.points = points_;\n this.planes = planes_;\n }\n\n static fromInvProjectionMatrix(invProj: Float64Array, worldSize: number, zoom: number, zInMeters: boolean): Frustum {\n const clipSpaceCorners = [\n [-1, 1, -1, 1],\n [ 1, 1, -1, 1],\n [ 1, -1, -1, 1],\n [-1, -1, -1, 1],\n [-1, 1, 1, 1],\n [ 1, 1, 1, 1],\n [ 1, -1, 1, 1],\n [-1, -1, 1, 1]\n ];\n\n const scale = Math.pow(2, zoom);\n\n // Transform frustum corner points from clip space to tile space\n const frustumCoords = clipSpaceCorners\n .map(v => {\n const s = vec4.transformMat4([], v, invProj);\n const k = 1.0 / s[3] / worldSize * scale;\n // Z scale in meters.\n return vec4.mul(s, s, [k, k, zInMeters ? 1.0 / s[3] : k, k]);\n });\n\n const frustumPlanePointIndices = [\n [0, 1, 2], // near\n [6, 5, 4], // far\n [0, 3, 7], // left\n [2, 1, 5], // right\n [3, 2, 6], // bottom\n [0, 4, 5] // top\n ];\n\n const frustumPlanes = frustumPlanePointIndices.map((p: Array<number>) => {\n const a = vec3.sub([], frustumCoords[p[0]], frustumCoords[p[1]]);\n const b = vec3.sub([], frustumCoords[p[2]], frustumCoords[p[1]]);\n const n = vec3.normalize([], vec3.cross([], a, b));\n const d = -vec3.dot(n, frustumCoords[p[1]]);\n return n.concat(d);\n });\n\n return new Frustum(frustumCoords, frustumPlanes);\n }\n}\n\nclass Aabb {\n min: Vec3;\n max: Vec3;\n center: Vec3;\n\n static fromPoints(points: Array<Vec3>): Aabb {\n const min = [Infinity, Infinity, Infinity];\n const max = [-Infinity, -Infinity, -Infinity];\n\n for (const p of points) {\n vec3.min(min, min, p);\n vec3.max(max, max, p);\n }\n\n return new Aabb(min, max);\n }\n\n static applyTransform(aabb: Aabb, transform: Mat4): Aabb {\n const corners = aabb.getCorners();\n\n for (let i = 0; i < corners.length; ++i) {\n vec3.transformMat4(corners[i], corners[i], transform);\n }\n return Aabb.fromPoints(corners);\n }\n\n constructor(min_: Vec3, max_: Vec3) {\n this.min = min_;\n this.max = max_;\n this.center = vec3.scale([], vec3.add([], this.min, this.max), 0.5);\n }\n\n quadrant(index: number): Aabb {\n const split = [(index % 2) === 0, index < 2];\n const qMin = vec3.clone(this.min);\n const qMax = vec3.clone(this.max);\n for (let axis = 0; axis < split.length; axis++) {\n qMin[axis] = split[axis] ? this.min[axis] : this.center[axis];\n qMax[axis] = split[axis] ? this.center[axis] : this.max[axis];\n }\n // Temporarily, elevation is constant, hence quadrant.max.z = this.max.z\n qMax[2] = this.max[2];\n return new Aabb(qMin, qMax);\n }\n\n distanceX(point: Array<number>): number {\n const pointOnAabb = Math.max(Math.min(this.max[0], point[0]), this.min[0]);\n return pointOnAabb - point[0];\n }\n\n distanceY(point: Array<number>): number {\n const pointOnAabb = Math.max(Math.min(this.max[1], point[1]), this.min[1]);\n return pointOnAabb - point[1];\n }\n\n distanceZ(point: Array<number>): number {\n const pointOnAabb = Math.max(Math.min(this.max[2], point[2]), this.min[2]);\n return pointOnAabb - point[2];\n }\n\n getCorners(): Array<Vec3> {\n const mn = this.min;\n const mx = this.max;\n return [\n [mn[0], mn[1], mn[2]],\n [mx[0], mn[1], mn[2]],\n [mx[0], mx[1], mn[2]],\n [mn[0], mx[1], mn[2]],\n [mn[0], mn[1], mx[2]],\n [mx[0], mn[1], mx[2]],\n [mx[0], mx[1], mx[2]],\n [mn[0], mx[1], mx[2]],\n ];\n }\n\n // Performs a frustum-aabb intersection test. Returns 0 if there's no intersection,\n // 1 if shapes are intersecting and 2 if the aabb if fully inside the frustum.\n intersects(frustum: Frustum): number {\n // Execute separating axis test between two convex objects to find intersections\n // Each frustum plane together with 3 major axes define the separating axes\n\n const aabbPoints = this.getCorners();\n let fullyInside = true;\n\n for (let p = 0; p < frustum.planes.length; p++) {\n const plane = frustum.planes[p];\n let pointsInside = 0;\n\n for (let i = 0; i < aabbPoints.length; i++) {\n pointsInside += vec3.dot(plane, aabbPoints[i]) + plane[3] >= 0;\n }\n\n if (pointsInside === 0)\n return 0;\n\n if (pointsInside !== aabbPoints.length)\n fullyInside = false;\n }\n\n if (fullyInside)\n return 2;\n\n for (let axis = 0; axis < 3; axis++) {\n let projMin = Number.MAX_VALUE;\n let projMax = -Number.MAX_VALUE;\n\n for (let p = 0; p < frustum.points.length; p++) {\n const projectedPoint = frustum.points[p][axis] - this.min[axis];\n\n projMin = Math.min(projMin, projectedPoint);\n projMax = Math.max(projMax, projectedPoint);\n }\n\n if (projMax < 0 || projMin > this.max[axis] - this.min[axis])\n return 0;\n }\n\n return 1;\n }\n}\nexport {\n Aabb,\n Frustum,\n FrustumCorners,\n Ray\n};\n","// @flow\nimport MercatorCoordinate, {\n lngFromMercatorX,\n latFromMercatorY,\n mercatorZfromAltitude,\n mercatorXfromLng,\n mercatorYfromLat,\n MAX_MERCATOR_LATITUDE\n} from '../mercator_coordinate.js';\nimport EXTENT from '../../data/extent.js';\nimport {number as interpolate} from '../../style-spec/util/interpolate.js';\nimport {degToRad, radToDeg, clamp, smoothstep, getColumn, shortestAngle} from '../../util/util.js';\nimport {vec3, vec4, mat3, mat4} from 'gl-matrix';\nimport SegmentVector from '../../data/segment.js';\nimport {members as globeLayoutAttributes} from '../../terrain/globe_attributes.js';\nimport posAttributes from '../../data/pos_attributes.js';\nimport {TriangleIndexArray, GlobeVertexArray, LineIndexArray, PosArray} from '../../data/array_types.js';\nimport {Aabb, Ray} from '../../util/primitives.js';\nimport LngLat, {earthRadius} from '../lng_lat.js';\nimport LngLatBounds from '../lng_lat_bounds.js';\n\nimport type Painter from '../../render/painter.js';\nimport type {CanonicalTileID, UnwrappedTileID} from '../../source/tile_id.js';\nimport type Context from '../../gl/context.js';\nimport type {Vec3, Mat4} from 'gl-matrix';\nimport type IndexBuffer from '../../gl/index_buffer.js';\nimport type VertexBuffer from '../../gl/vertex_buffer.js';\nimport type Transform from '../transform.js';\nimport Point from '@mapbox/point-geometry';\nimport assert from 'assert';\n\nexport const GLOBE_ZOOM_THRESHOLD_MIN = 5;\nexport const GLOBE_ZOOM_THRESHOLD_MAX = 6;\n\n// At low zoom levels the globe gets rendered so that the scale at this\n// latitude matches it's scale in a mercator map. The choice of latitude is\n// a bit arbitrary. Different choices will match mercator more closely in different\n// views. 45 is a good enough choice because:\n// - it's half way from the pole to the equator\n// - matches most middle latitudes reasonably well\n// - biases towards increasing size rather than decreasing\n// - makes the globe slightly larger at very low zoom levels, where it already\n// covers less pixels than mercator (due to the curved surface)\n//\n// Changing this value will change how large a globe is rendered and could affect\n// end users. This should only be done of the tradeoffs between change and improvement\n// are carefully considered.\nexport const GLOBE_SCALE_MATCH_LATITUDE = 45;\n\nexport const GLOBE_RADIUS = EXTENT / Math.PI / 2.0;\nconst GLOBE_NORMALIZATION_BIT_RANGE = 15;\nconst GLOBE_NORMALIZATION_MASK = (1 << (GLOBE_NORMALIZATION_BIT_RANGE - 1)) - 1;\nconst GLOBE_VERTEX_GRID_SIZE = 64;\nconst GLOBE_LATITUDINAL_GRID_LOD_TABLE = [GLOBE_VERTEX_GRID_SIZE, GLOBE_VERTEX_GRID_SIZE / 2, GLOBE_VERTEX_GRID_SIZE / 4];\nconst TILE_SIZE = 512;\n\nconst GLOBE_MIN = -GLOBE_RADIUS;\nconst GLOBE_MAX = GLOBE_RADIUS;\n\nconst GLOBE_LOW_ZOOM_TILE_AABBS = [\n // z == 0\n new Aabb([GLOBE_MIN, GLOBE_MIN, GLOBE_MIN], [GLOBE_MAX, GLOBE_MAX, GLOBE_MAX]),\n // z == 1\n new Aabb([GLOBE_MIN, GLOBE_MIN, GLOBE_MIN], [0, 0, GLOBE_MAX]), // x=0, y=0\n new Aabb([0, GLOBE_MIN, GLOBE_MIN], [GLOBE_MAX, 0, GLOBE_MAX]), // x=1, y=0\n new Aabb([GLOBE_MIN, 0, GLOBE_MIN], [0, GLOBE_MAX, GLOBE_MAX]), // x=0, y=1\n new Aabb([0, 0, GLOBE_MIN], [GLOBE_MAX, GLOBE_MAX, GLOBE_MAX]) // x=1, y=1\n];\n\nexport function globeMetersToEcef(d: number): number {\n return d * GLOBE_RADIUS / earthRadius;\n}\n\nexport function globePointCoordinate(tr: Transform, x: number, y: number, clampToHorizon: boolean = true): ?MercatorCoordinate {\n const point0 = vec3.scale([], tr._camera.position, tr.worldSize);\n const point1 = [x, y, 1, 1];\n\n vec4.transformMat4(point1, point1, tr.pixelMatrixInverse);\n vec4.scale(point1, point1, 1 / point1[3]);\n\n const p0p1 = vec3.sub([], point1, point0);\n const dir = vec3.normalize([], p0p1);\n\n // Find closest point on the sphere to the ray. This is a bit more involving operation\n // if the ray is not intersecting with the sphere, in which case we \"clamp\" the ray\n // to the surface of the sphere, i.e. find a tangent vector that originates from the camera position\n const m = tr.globeMatrix;\n const globeCenter = [m[12], m[13], m[14]];\n const p0toCenter = vec3.sub([], globeCenter, point0);\n const p0toCenterDist = vec3.length(p0toCenter);\n const centerDir = vec3.normalize([], p0toCenter);\n const radius = tr.worldSize / (2.0 * Math.PI);\n const cosAngle = vec3.dot(centerDir, dir);\n\n const origoTangentAngle = Math.asin(radius / p0toCenterDist);\n const origoDirAngle = Math.acos(cosAngle);\n\n if (origoTangentAngle < origoDirAngle) {\n if (!clampToHorizon) return null;\n\n // Find the tangent vector by interpolating between camera-to-globe and camera-to-click vectors.\n // First we'll find a point P1 on the clicked ray that forms a right-angled triangle with the camera position\n // and the center of the globe. Angle of the tanget vector is then used as the interpolation factor\n const clampedP1 = [], origoToP1 = [];\n\n vec3.scale(clampedP1, dir, p0toCenterDist / cosAngle);\n vec3.normalize(origoToP1, vec3.sub(origoToP1, clampedP1, p0toCenter));\n vec3.normalize(dir, vec3.add(dir, p0toCenter, vec3.scale(dir, origoToP1, Math.tan(origoTangentAngle) * p0toCenterDist)));\n }\n\n const pointOnGlobe = [];\n const ray = new Ray(point0, dir);\n\n ray.closestPointOnSphere(globeCenter, radius, pointOnGlobe);\n\n // Transform coordinate axes to find lat & lng of the position\n const xa = vec3.normalize([], getColumn(m, 0));\n const ya = vec3.normalize([], getColumn(m, 1));\n const za = vec3.normalize([], getColumn(m, 2));\n\n const xp = vec3.dot(xa, pointOnGlobe);\n const yp = vec3.dot(ya, pointOnGlobe);\n const zp = vec3.dot(za, pointOnGlobe);\n\n const lat = radToDeg(Math.asin(-yp / radius));\n let lng = radToDeg(Math.atan2(xp, zp));\n\n // Check that the returned longitude angle is not wrapped\n lng = tr.center.lng + shortestAngle(tr.center.lng, lng);\n\n const mx = mercatorXfromLng(lng);\n const my = clamp(mercatorYfromLat(lat), 0, 1);\n\n return new MercatorCoordinate(mx, my);\n}\n\nexport class Arc {\n constructor(p0: Vec3, p1: Vec3, center: Vec3) {\n this.a = vec3.sub([], p0, center);\n this.b = vec3.sub([], p1, center);\n this.center = center;\n const an = vec3.normalize([], this.a);\n const bn = vec3.normalize([], this.b);\n this.angle = Math.acos(vec3.dot(an, bn));\n }\n\n a: Vec3;\n b: Vec3;\n center: Vec3;\n angle: number;\n}\n\nexport function slerp(a: number, b: number, angle: number, t: number): number {\n const sina = Math.sin(angle);\n return a * (Math.sin((1.0 - t) * angle) / sina) + b * (Math.sin(t * angle) / sina);\n}\n\n// Computes local extremum point of an arc on one of the dimensions (x, y or z),\n// i.e. value of a point where d/dt*f(x,y,t) == 0\nexport function localExtremum(arc: Arc, dim: number): ?number {\n // d/dt*slerp(x,y,t) = 0\n // => t = (1/a)*atan(y/(x*sin(a))-1/tan(a)), x > 0\n // => t = (1/a)*(pi/2), x == 0\n if (arc.angle === 0) {\n return null;\n }\n\n let t: number;\n if (arc.a[dim] === 0) {\n t = (1.0 / arc.angle) * 0.5 * Math.PI;\n } else {\n t = 1.0 / arc.angle * Math.atan(arc.b[dim] / arc.a[dim] / Math.sin(arc.angle) - 1.0 / Math.tan(arc.angle));\n }\n\n if (t < 0 || t > 1) {\n return null;\n }\n\n return slerp(arc.a[dim], arc.b[dim], arc.angle, clamp(t, 0.0, 1.0)) + arc.center[dim];\n}\n\nexport function globeTileBounds(id: CanonicalTileID): Aabb {\n if (id.z <= 1) {\n return GLOBE_LOW_ZOOM_TILE_AABBS[id.z + id.y * 2 + id.x];\n }\n\n // After zoom 1 surface function is monotonic for all tile patches\n // => it is enough to project corner points\n const bounds = tileCornersToBounds(id);\n const corners = boundsToECEF(bounds);\n\n return Aabb.fromPoints(corners);\n}\n\nexport function interpolateVec3(from: Vec3, to: Vec3, phase: number): Vec3 {\n vec3.scale(from, from, 1 - phase);\n return vec3.scaleAndAdd(from, from, to, phase);\n}\n\n// Similar to globeTileBounds() but accounts for globe to Mercator transition.\nexport function transitionTileAABBinECEF(id: CanonicalTileID, tr: Transform): Aabb {\n const phase = globeToMercatorTransition(tr.zoom);\n if (phase === 0) {\n return globeTileBounds(id);\n }\n\n const bounds = tileCornersToBounds(id);\n const corners = boundsToECEF(bounds);\n\n const w = mercatorXfromLng(bounds.getWest()) * tr.worldSize;\n const e = mercatorXfromLng(bounds.getEast()) * tr.worldSize;\n const n = mercatorYfromLat(bounds.getNorth()) * tr.worldSize;\n const s = mercatorYfromLat(bounds.getSouth()) * tr.worldSize;\n // Mercator bounds globeCorners in world/pixel space\n const nw = [w, n, 0];\n const ne = [e, n, 0];\n const sw = [w, s, 0];\n const se = [e, s, 0];\n // Transform Mercator globeCorners to ECEF\n const worldToECEFMatrix = mat4.invert([], tr.globeMatrix);\n vec3.transformMat4(nw, nw, worldToECEFMatrix);\n vec3.transformMat4(ne, ne, worldToECEFMatrix);\n vec3.transformMat4(sw, sw, worldToECEFMatrix);\n vec3.transformMat4(se, se, worldToECEFMatrix);\n // Interpolate Mercator corners and globe corners\n corners[0] = interpolateVec3(corners[0], sw, phase);\n corners[1] = interpolateVec3(corners[1], se, phase);\n corners[2] = interpolateVec3(corners[2], ne, phase);\n corners[3] = interpolateVec3(corners[3], nw, phase);\n\n return Aabb.fromPoints(corners);\n}\n\nfunction transformPoints(corners: Array<Vec3>, globeMatrix: Mat4, scale: number) {\n for (const corner of corners) {\n vec3.transformMat4(corner, corner, globeMatrix);\n vec3.scale(corner, corner, scale);\n }\n}\n\n// Returns AABB in world/camera space scaled by numTiles / tr.worldSize\nexport function aabbForTileOnGlobe(tr: Transform, numTiles: number, tileId: CanonicalTileID): Aabb {\n const scale = numTiles / tr.worldSize;\n const m = tr.globeMatrix;\n\n if (tileId.z <= 1) {\n // Compute world/pixel space AABB that fully encapsulates\n // transformed corners of the ECEF AABB\n const corners = globeTileBounds(tileId).getCorners();\n transformPoints(corners, m, scale);\n return Aabb.fromPoints(corners);\n }\n\n // Find minimal aabb for a tile. Correct solution would be to compute bounding box that\n // fully encapsulates the curved patch that represents the tile on globes surface.\n // This can be simplified a bit as the globe transformation is constrained:\n // 1. Camera always faces the center point on the map\n // 2. Camera is always above (z-coordinate) all of the tiles\n // 3. Up direction of the coordinate space (pixel space) is always +z. This means that\n // the \"highest\" point of the map is at the center.\n // 4. z-coordinate of any point in any tile descends as a function of the distance from the center\n\n // Simplified aabb is computed by first encapsulating 4 transformed corner points of the tile.\n // The resulting aabb is not complete yet as curved edges of the tile might span outside of the boundaries.\n // It is enough to extend the aabb to contain only the edge that's closest to the center point.\n const bounds = tileCornersToBounds(tileId);\n const corners = boundsToECEF(bounds);\n\n // Transform the corners to world space\n transformPoints(corners, m, scale);\n\n const mx = Number.MAX_VALUE;\n const cornerMax = [-mx, -mx, -mx];\n const cornerMin = [mx, mx, mx];\n\n // Extend the aabb by including the center point. There are some corner cases where center point is inside the\n // tile but due to curvature aabb computed from corner points does not cover the curved area.\n if (bounds.contains(tr.center)) {\n\n for (const corner of corners) {\n vec3.min(cornerMin, cornerMin, corner);\n vec3.max(cornerMax, cornerMax, corner);\n }\n cornerMax[2] = 0.0;\n const point = tr.point;\n const center = [point.x * scale, point.y * scale, 0];\n vec3.min(cornerMin, cornerMin, center);\n vec3.max(cornerMax, cornerMax, center);\n\n return new Aabb(cornerMin, cornerMax);\n }\n\n // Compute arcs describing edges of the tile on the globe surface.\n // Vertical edges revolves around the globe origin whereas horizontal edges revolves around the y-axis.\n const arcCenter = [m[12] * scale, m[13] * scale, m[14] * scale];\n\n const tileCenter = bounds.getCenter();\n const centerLat = clamp(tr.center.lat, -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);\n const tileCenterLat = clamp(tileCenter.lat, -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);\n const camX = mercatorXfromLng(tr.center.lng);\n const camY = mercatorYfromLat(centerLat);\n\n let dx = camX - mercatorXfromLng(tileCenter.lng);\n const dy = camY - mercatorYfromLat(tileCenterLat);\n\n // Shortest distance might be across the antimeridian\n if (dx > .5) {\n dx -= 1;\n } else if (dx < -.5) {\n dx += 1;\n }\n\n // Here we determine the arc which is closest to the map center point.\n // Horizontal arcs origin = globe center\n // Vertical arcs origin = globe center + yAxis * shift.\n // Where `shift` is determined by latitude.\n let closestArcIdx = 0;\n if (Math.abs(dx) > Math.abs(dy)) {\n closestArcIdx = dx >= 0 ? 1 : 3;\n } else {\n closestArcIdx = dy >= 0 ? 0 : 2;\n const yAxis = [m[4] * scale, m[5] * scale, m[6] * scale];\n const shift = -Math.sin(degToRad(dy >= 0 ? bounds.getSouth() : bounds.getNorth())) * GLOBE_RADIUS;\n vec3.scaleAndAdd(arcCenter, arcCenter, yAxis, shift);\n }\n\n const arcStart = corners[closestArcIdx];\n const arcEnd = corners[(closestArcIdx + 1) % 4];\n\n const closestArc = new Arc(arcStart, arcEnd, arcCenter);\n const arcExtremum = [\n (localExtremum(closestArc, 0) || arcStart[0]),\n (localExtremum(closestArc, 1) || arcStart[1]),\n (localExtremum(closestArc, 2) || arcStart[2])];\n\n const phase = globeToMercatorTransition(tr.zoom);\n if (phase > 0.0) {\n const mercatorCorners = mercatorTileCornersInCameraSpace(tileId, numTiles, tr._pixelsPerMercatorPixel, camX, camY);\n // Interpolate the four corners towards their world space location in mercator projection during transition.\n for (let i = 0; i < corners.length; i++) {\n interpolateVec3(corners[i], mercatorCorners[i], phase);\n }\n // Calculate the midpoint of the closest edge midpoint in Mercator\n const mercatorMidpoint = vec3.add([], mercatorCorners[closestArcIdx], mercatorCorners[(closestArcIdx + 1) % 4]);\n vec3.scale(mercatorMidpoint, mercatorMidpoint, .5);\n // Interpolate globe extremum toward Mercator midpoint\n interpolateVec3(arcExtremum, mercatorMidpoint, phase);\n }\n\n for (const corner of corners) {\n vec3.min(cornerMin, cornerMin, corner);\n vec3.max(cornerMax, cornerMax, corner);\n }\n\n // Reduce height of the aabb to match height of the closest arc. This reduces false positives\n // of tiles farther away from the center as they would otherwise intersect with far end\n // of the view frustum\n cornerMin[2] = Math.min(arcStart[2], arcEnd[2]);\n\n vec3.min(cornerMin, cornerMin, arcExtremum);\n vec3.max(cornerMax, cornerMax, arcExtremum);\n\n return new Aabb(cornerMin, cornerMax);\n}\n\nexport function tileCornersToBounds({x, y, z}: CanonicalTileID): LngLatBounds {\n const s = 1.0 / (1 << z);\n const sw = new LngLat(lngFromMercatorX(x * s), latFromMercatorY((y + 1) * s));\n const ne = new LngLat(lngFromMercatorX((x + 1) * s), latFromMercatorY(y * s));\n return new LngLatBounds(sw, ne);\n}\n\nfunction mercatorTileCornersInCameraSpace({x, y, z}: CanonicalTileID, numTiles: number, mercatorScale: number, camX: number, camY: number): Array<Vec3> {\n\n const tileScale = 1.0 / (1 << z);\n // Values in Mercator coordinates (0 - 1)\n let w = x * tileScale;\n let e = w + tileScale;\n let n = y * tileScale;\n let s = n + tileScale;\n\n // // Ensure that the tile viewed is the nearest when across the antimeridian\n let wrap = 0;\n const tileCenterXFromCamera = (w + e) / 2 - camX;\n if (tileCenterXFromCamera > .5) {\n wrap = -1;\n } else if (tileCenterXFromCamera < -.5) {\n wrap = 1;\n }\n\n camX *= numTiles;\n camY *= numTiles;\n\n // Transform Mercator coordinates to points on the plane tangent to the globe at cameraCenter.\n w = ((w + wrap) * numTiles - camX) * mercatorScale + camX;\n e = ((e + wrap) * numTiles - camX) * mercatorScale + camX;\n n = (n * numTiles - camY) * mercatorScale + camY;\n s = (s * numTiles - camY) * mercatorScale + camY;\n\n return [[w, s, 0],\n [e, s, 0],\n [e, n, 0],\n [w, n, 0]];\n}\n\nfunction boundsToECEF(bounds: LngLatBounds): Array<Vec3> {\n const ny = degToRad(bounds.getNorth());\n const sy = degToRad(bounds.getSouth());\n const cosN = Math.cos(ny);\n const cosS = Math.cos(sy);\n const sinN = Math.sin(ny);\n const sinS = Math.sin(sy);\n const w = bounds.getWest();\n const e = bounds.getEast();\n return [\n csLatLngToECEF(cosS, sinS, w),\n csLatLngToECEF(cosS, sinS, e),\n csLatLngToECEF(cosN, sinN, e),\n csLatLngToECEF(cosN, sinN, w)\n ];\n}\n\nfunction csLatLngToECEF(cosLat: number, sinLat: number, lng: number, radius: number = GLOBE_RADIUS): Vec3 {\n lng = degToRad(lng);\n\n // Convert lat & lng to spherical representation. Use zoom=0 as a reference\n const sx = cosLat * Math.sin(lng) * radius;\n const sy = -sinLat * radius;\n const sz = cosLat * Math.cos(lng) * radius;\n\n return [sx, sy, sz];\n}\n\nexport function ecefToLatLng([x, y, z]: Array<number>): LngLat {\n const radius = Math.hypot(x, y, z);\n const lng = Math.atan2(x, z);\n const lat = Math.PI * 0.5 - Math.acos(-y / radius);\n\n return new LngLat(radToDeg(lng), radToDeg(lat));\n}\n\nexport function latLngToECEF(lat: number, lng: number, radius?: number): Vec3 {\n assert(lat <= 90 && lat >= -90, 'Lattitude must be between -90 and 90');\n return csLatLngToECEF(Math.cos(degToRad(lat)), Math.sin(degToRad(lat)), lng, radius);\n}\n\nexport function tileCoordToECEF(x: number, y: number, id: CanonicalTileID, radius?: number): Vec3 {\n const tileCount = 1 << id.z;\n const mercatorX = (x / EXTENT + id.x) / tileCount;\n const mercatorY = (y / EXTENT + id.y) / tileCount;\n const lat = latFromMercatorY(mercatorY);\n const lng = lngFromMercatorX(mercatorX);\n const pos = latLngToECEF(lat, lng, radius);\n return pos;\n}\n\nexport function globeECEFOrigin(tileMatrix: Mat4, id: UnwrappedTileID): [number, number, number] {\n const origin = [0, 0, 0];\n const bounds = globeTileBounds(id.canonical);\n const normalizationMatrix = globeNormalizeECEF(bounds);\n vec3.transformMat4(origin, origin, normalizationMatrix);\n vec3.transformMat4(origin, origin, tileMatrix);\n return origin;\n}\n\nexport function globeECEFNormalizationScale({min, max}: Aabb): number {\n return GLOBE_NORMALIZATION_MASK / Math.max(max[0] - min[0], max[1] - min[1], max[2] - min[2]);\n}\n\n// avoid redundant allocations by sharing the same typed array for normalization/denormalization matrices;\n// we never use multiple instances of these at the same time, but this might change, so let's be careful here!\nconst tempMatrix = new Float64Array(16);\n\nexport function globeNormalizeECEF(bounds: Aabb): Float64Array {\n const scale = globeECEFNormalizationScale(bounds);\n const m = mat4.fromScaling(tempMatrix, [scale, scale, scale]);\n return mat4.translate(m, m, vec3.negate([], bounds.min));\n}\n\nexport function globeDenormalizeECEF(bounds: Aabb): Float64Array {\n const m = mat4.fromTranslation(tempMatrix, bounds.min);\n const scale = 1.0 / globeECEFNormalizationScale(bounds);\n return mat4.scale(m, m, [scale, scale, scale]);\n}\n\nexport function globeECEFUnitsToPixelScale(worldSize: number): number {\n const localRadius = EXTENT / (2.0 * Math.PI);\n const wsRadius = worldSize / (2.0 * Math.PI);\n return wsRadius / localRadius;\n}\n\nexport function globePixelsToTileUnits(zoom: number, id: CanonicalTileID): number {\n const ecefPerPixel = EXTENT / (TILE_SIZE * Math.pow(2, zoom));\n const normCoeff = globeECEFNormalizationScale(globeTileBounds(id));\n\n return ecefPerPixel * normCoeff;\n}\n\nfunction calculateGlobePosMatrix(x: number, y: number, worldSize: number, lng: number, lat: number): Float64Array {\n // transform the globe from reference coordinate space to world space\n const scale = globeECEFUnitsToPixelScale(worldSize);\n const offset = [x, y, -worldSize / (2.0 * Math.PI)];\n const m = mat4.identity(new Float64Array(16));\n mat4.translate(m, m, offset);\n mat4.scale(m, m, [scale, scale, scale]);\n mat4.rotateX(m, m, degToRad(-lat));\n mat4.rotateY(m, m, degToRad(-lng));\n return m;\n}\n\nexport function calculateGlobeMatrix(tr: Transform): Float64Array {\n const {x, y} = tr.point;\n const {lng, lat} = tr._center;\n return calculateGlobePosMatrix(x, y, tr.worldSize, lng, lat);\n}\n\nexport function calculateGlobeLabelMatrix(tr: Transform, id: CanonicalTileID): Float64Array {\n const {x, y} = tr.point;\n\n // Map aligned label space for globe view is the non-rotated globe itself in pixel coordinates.\n\n // Camera is moved closer towards the ground near poles as part of\n // compesanting the reprojection. This has to be compensated for the\n // map aligned label space. Whithout this logic map aligned symbols\n // would appear larger than intended.\n const m = calculateGlobePosMatrix(x, y, tr.worldSize / tr._pixelsPerMercatorPixel, 0, 0);\n return mat4.multiply(m, m, globeDenormalizeECEF(globeTileBounds(id)));\n}\n\nexport function calculateGlobeMercatorMatrix(tr: Transform): Float32Array {\n const zScale = tr.pixelsPerMeter;\n const ws = zScale / mercatorZfromAltitude(1, tr.center.lat);\n\n const posMatrix = mat4.identity(new Float64Array(16));\n mat4.translate(posMatrix, posMatrix, [tr.point.x, tr.point.y, 0.0]);\n mat4.scale(posMatrix, posMatrix, [ws, ws, zScale]);\n\n return Float32Array.from(posMatrix);\n}\n\nexport function globeToMercatorTransition(zoom: number): number {\n return smoothstep(GLOBE_ZOOM_THRESHOLD_MIN, GLOBE_ZOOM_THRESHOLD_MAX, zoom);\n}\n\nexport function globeMatrixForTile(id: CanonicalTileID, globeMatrix: Float64Array): Float32Array {\n const decode = globeDenormalizeECEF(globeTileBounds(id));\n return mat4.mul(mat4.create(), globeMatrix, decode);\n}\n\nexport function globePoleMatrixForTile(z: number, x: number, tr: Transform): Float32Array {\n const poleMatrix = mat4.identity(new Float64Array(16));\n\n // Rotate the pole triangle fan to the correct location\n const numTiles = 1 << z;\n const xOffsetAngle = (x / numTiles - 0.5) * Math.PI * 2.0;\n mat4.rotateY(poleMatrix, tr.globeMatrix, xOffsetAngle);\n\n return Float32Array.from(poleMatrix);\n}\n\nexport function globeUseCustomAntiAliasing(painter: Painter, context: Context, transform: Transform): boolean {\n const transitionT = globeToMercatorTransition(transform.zoom);\n const useContextAA = painter.style.map._antialias;\n const hasStandardDerivatives = !!context.extStandardDerivatives;\n const disabled = context.extStandardDerivativesForceOff || (painter.terrain && painter.terrain.exaggeration() > 0.0);\n return transitionT === 0.0 && !useContextAA && !disabled && hasStandardDerivatives;\n}\n\nexport function getGridMatrix(id: CanonicalTileID, bounds: LngLatBounds, latitudinalLod: number, worldSize: number): Mat4 {\n const n = bounds.getNorth();\n const s = bounds.getSouth();\n const w = bounds.getWest();\n const e = bounds.getEast();\n\n // Construct transformation matrix for converting tile coordinates into LatLngs\n const tiles = 1 << id.z;\n const tileWidth = e - w;\n const tileHeight = n - s;\n const tileToLng = tileWidth / GLOBE_VERTEX_GRID_SIZE;\n const tileToLat = -tileHeight / GLOBE_LATITUDINAL_GRID_LOD_TABLE[latitudinalLod];\n\n const matrix = [0, tileToLng, 0, tileToLat, 0, 0, n, w, 0];\n\n if (id.z > 0) {\n // Add slight padding to patch seams between tiles.\n // This is done by extruding vertices by a fixed amount. Pixel padding\n // is first converted to degrees and then to tile units before being\n // applied to the final transformation matrix.\n const pixelPadding = 0.5;\n const padding = pixelPadding * 360.0 / worldSize;\n\n const xScale = padding / tileWidth + 1;\n const yScale = padding / tileHeight + 1;\n const padMatrix = [xScale, 0, 0, 0, yScale, 0, -0.5 * padding / tileToLng, 0.5 * padding / tileToLat, 1];\n\n mat3.multiply(matrix, matrix, padMatrix);\n }\n\n // Embed additional variables to the last row of the matrix\n matrix[2] = tiles;\n matrix[5] = id.x;\n matrix[8] = id.y;\n\n return matrix;\n}\n\nexport function getLatitudinalLod(lat: number): number {\n const UPPER_LATITUDE = MAX_MERCATOR_LATITUDE - 5.0;\n lat = clamp(lat, -UPPER_LATITUDE, UPPER_LATITUDE) / UPPER_LATITUDE * 90.0;\n // const t = Math.pow(1.0 - Math.cos(degToRad(lat)), 2);\n const t = Math.pow(Math.abs(Math.sin(degToRad(lat))), 3);\n const lod = Math.round(t * (GLOBE_LATITUDINAL_GRID_LOD_TABLE.length - 1));\n return lod;\n}\n\nexport function globeCenterToScreenPoint(tr: Transform): Point {\n const pos = [0, 0, 0];\n const matrix = mat4.identity(new Float64Array(16));\n mat4.multiply(matrix, tr.pixelMatrix, tr.globeMatrix);\n vec3.transformMat4(pos, pos, matrix);\n return new Point(pos[0], pos[1]);\n}\n\nfunction cameraPositionInECEF(tr: Transform): Array<number> {\n // Here \"center\" is the center of the globe. We refer to transform._center\n // (the surface of the map on the center of the screen) as \"pivot\" to avoid confusion.\n const centerToPivot = latLngToECEF(tr._center.lat, tr._center.lng);\n\n // Set axis to East-West line tangent to sphere at pivot\n const south = vec3.fromValues(0, 1, 0);\n let axis = vec3.cross([], south, centerToPivot);\n\n // Rotate axis around pivot by bearing\n const rotation = mat4.fromRotation([], -tr.angle, centerToPivot);\n axis = vec3.transformMat4(axis, axis, rotation);\n\n // Rotate camera around axis by pitch\n mat4.fromRotation(rotation, -tr._pitch, axis);\n\n const pivotToCamera = vec3.normalize([], centerToPivot);\n vec3.scale(pivotToCamera, pivotToCamera, globeMetersToEcef(tr.cameraToCenterDistance / tr.pixelsPerMeter));\n vec3.transformMat4(pivotToCamera, pivotToCamera, rotation);\n\n return vec3.add([], centerToPivot, pivotToCamera);\n}\n\n// Return the angle of the normal vector at a point on the globe relative to the camera.\n// i.e. how much to tilt map-aligned markers.\nexport function globeTiltAtLngLat(tr: Transform, lngLat: LngLat): number {\n const centerToPoint = latLngToECEF(lngLat.lat, lngLat.lng);\n const centerToCamera = cameraPositionInECEF(tr);\n const pointToCamera = vec3.subtract([], centerToCamera, centerToPoint);\n return vec3.angle(pointToCamera, centerToPoint);\n}\n\nexport function isLngLatBehindGlobe(tr: Transform, lngLat: LngLat): boolean {\n // We consider 1% past the horizon not occluded, this allows popups to be dragged around the globe edge without fading.\n return (globeTiltAtLngLat(tr, lngLat) > Math.PI / 2 * 1.01);\n}\n\n/**\n * Check if poles are visible inside the current viewport\n *\n * @param {Transform} transform The current map transform.\n * @returns {[boolean, boolean]} A tuple of booleans [northInViewport, southInViewport]\n */\nexport function polesInViewport(tr: Transform): [boolean, boolean] {\n // Create matrix from ECEF to screen coordinates\n const ecefToScreenMatrix = mat4.identity(new Float64Array(16));\n mat4.multiply(ecefToScreenMatrix, tr.pixelMatrix, tr.globeMatrix);\n\n const north = [0, GLOBE_MIN, 0];\n const south = [0, GLOBE_MAX, 0];\n\n // Translate the poles from ECEF to screen coordinates\n vec3.transformMat4(north, north, ecefToScreenMatrix);\n vec3.transformMat4(south, south, ecefToScreenMatrix);\n\n // Check if the poles are inside the viewport and not behind the globe surface\n const northInViewport =\n north[0] > 0 && north[0] <= tr.width &&\n north[1] > 0 && north[1] <= tr.height &&\n !isLngLatBehindGlobe(tr, new LngLat(tr.center.lat, 90));\n\n const southInViewport =\n south[0] > 0 && south[0] <= tr.width &&\n south[1] > 0 && south[1] <= tr.height &&\n !isLngLatBehindGlobe(tr, new LngLat(tr.center.lat, -90));\n\n return [northInViewport, southInViewport];\n}\n\nconst POLE_RAD = degToRad(85.0);\nconst POLE_COS = Math.cos(POLE_RAD);\nconst POLE_SIN = Math.sin(POLE_RAD);\n\n// Generate terrain grid with embedded skirts\nconst EMBED_SKIRTS = true;\n\ntype GridLodSegments = {\n withoutSkirts: SegmentVector,\n withSkirts: SegmentVector\n};\n\ntype GridWithLods = {\n vertices: PosArray,\n indices: TriangleIndexArray,\n segments: Array<GridLodSegments>\n};\n\nexport class GlobeSharedBuffers {\n _poleNorthVertexBuffer: VertexBuffer;\n _poleSouthVertexBuffer: VertexBuffer;\n _poleIndexBuffer: IndexBuffer;\n _poleSegments: Array<SegmentVector>;\n\n _gridBuffer: VertexBuffer;\n _gridIndexBuffer: IndexBuffer;\n _gridSegments: Array<GridLodSegments>;\n\n _wireframeIndexBuffer: IndexBuffer;\n _wireframeSegments: Array<SegmentVector>;\n\n constructor(context: Context) {\n this._createGrid(context);\n this._createPoles(context);\n }\n\n destroy() {\n this._poleIndexBuffer.destroy();\n this._gridBuffer.destroy();\n this._gridIndexBuffer.destroy();\n this._poleNorthVertexBuffer.destroy();\n this._poleSouthVertexBuffer.destroy();\n for (const segments of this._poleSegments) segments.destroy();\n for (const segments of this._gridSegments) {\n segments.withSkirts.destroy();\n segments.withoutSkirts.destroy();\n }\n\n if (this._wireframeIndexBuffer) {\n this._wireframeIndexBuffer.destroy();\n for (const segments of this._wireframeSegments) segments.destroy();\n }\n }\n\n // Generate terrain grid vertices and indices for all LOD's\n //\n // Grid vertices memory layout:\n //\n // First line Skirt\n // ┌───────────────┐\n // │┌─────────────┐│\n // Left ││┼┼┼┼┼┼┼┼┼┼┼┼┼││ Right\n // Border ││┼┼┼┼┼┼┼┼┼┼┼┼┼││ Border\n // Skirt │├─────────────┤│ Skirt\n // ││ Main Grid ││\n // │├─────────────┤│\n // ││┼┼┼┼┼┼┼┼┼┼┼┼┼││\n // ││┼┼┼┼┼┼┼┼┼┼┼┼┼││\n // │└─────────────┘│\n // ├───────────────┤\n // ├───────────────┤\n // └───────────────┘\n // Bottom Skirt = Number of LOD's\n //\n _fillGridMeshWithLods(longitudinalCellsCount: number, latitudinalLods: number[]): GridWithLods {\n const vertices = new PosArray();\n const indices = new TriangleIndexArray();\n const segments: Array<GridLodSegments> = [];\n\n const xVertices = longitudinalCellsCount + 1 + 2 * (EMBED_SKIRTS ? 1 : 0);\n const yVerticesHighLodNoStrip = latitudinalLods[0] + 1;\n const yVerticesHighLodWithStrip = latitudinalLods[0] + 1 + (EMBED_SKIRTS ? 1 + latitudinalLods.length : 0);\n\n // Index adjustment, used to make strip (x, y) vertex input attribute data\n // to match same data on ordinary grid edges\n const prepareVertex = (x: number, y: number, isSkirt: boolean) => {\n if (!EMBED_SKIRTS) return [x, y];\n\n let adjustedX = (() => {\n if (x === xVertices - 1) {\n return x - 2;\n } else if (x === 0) {\n return x;\n } else {\n return x - 1;\n }\n })();\n\n // Skirt factor is introduces as an offset to the .x coordinate, similar to how it's done for mercator grids\n const skirtOffset = 24575;\n adjustedX += isSkirt ? skirtOffset : 0;\n\n return [adjustedX, y];\n };\n\n // Add first horizontal strip if present\n if (EMBED_SKIRTS) {\n for (let x = 0; x < xVertices; ++x) {\n vertices.emplaceBack(...prepareVertex(x, 0, true));\n }\n }\n\n // Add main grid part with vertices strips embedded\n for (let y = 0; y < yVerticesHighLodNoStrip; ++y) {\n for (let x = 0; x < xVertices; ++x) {\n const isSideBorder = (x === 0 || x === xVertices - 1);\n\n vertices.emplaceBack(...prepareVertex(x, y, isSideBorder && EMBED_SKIRTS));\n }\n }\n\n // Add bottom strips for each LOD\n if (EMBED_SKIRTS) {\n for (let lodIdx = 0; lodIdx < latitudinalLods.length; ++lodIdx) {\n const lastYRowForLod = latitudinalLods[lodIdx];\n for (let x = 0; x < xVertices; ++x) {\n vertices.emplaceBack(...prepareVertex(x, lastYRowForLod, true));\n }\n }\n }\n\n // Fill triangles\n for (let lodIdx = 0; lodIdx < latitudinalLods.length; ++lodIdx) {\n const indexOffset = indices.length;\n\n const yVerticesLod = latitudinalLods[lodIdx] + 1 + 2 * (EMBED_SKIRTS ? 1 : 0);\n\n const skirtsOnlyIndices = new TriangleIndexArray();\n\n for (let y = 0; y < yVerticesLod - 1; y++) {\n const isLastLine = (y === yVerticesLod - 2);\n const offsetToNextRow =\n (isLastLine && EMBED_SKIRTS ?\n (xVertices * (yVerticesHighLodWithStrip - latitudinalLods.length + lodIdx - y)) :\n xVertices);\n\n for (let x = 0; x < xVertices - 1; x++) {\n const idx = y * xVertices + x;\n\n const isSkirt = EMBED_SKIRTS && (y === 0 || isLastLine || x === 0 || x === xVertices - 2);\n\n if (isSkirt) {\n skirtsOnlyIndices.emplaceBack(idx + 1, idx, idx + offsetToNextRow);\n skirtsOnlyIndices.emplaceBack(idx + offsetToNextRow, idx + offsetToNextRow + 1, idx + 1);\n } else {\n indices.emplaceBack(idx + 1, idx, idx + offsetToNextRow);\n indices.emplaceBack(idx + offsetToNextRow, idx + offsetToNextRow + 1, idx + 1);\n }\n }\n }\n\n // Segments grid only\n const withoutSkirts = SegmentVector.simpleSegment(0, indexOffset, vertices.length, indices.length - indexOffset);\n\n for (let i = 0; i < skirtsOnlyIndices.uint16.length; i += 3) {\n indices.emplaceBack(skirtsOnlyIndices.uint16[i], skirtsOnlyIndices.uint16[i + 1], skirtsOnlyIndices.uint16[i + 2]);\n }\n\n // Segments grid + skirts only\n const withSkirts = SegmentVector.simpleSegment(0, indexOffset, vertices.length, indices.length - indexOffset);\n segments.push({withoutSkirts, withSkirts});\n }\n\n return {vertices, indices, segments};\n }\n\n _createGrid(context: Context) {\n const gridWithLods = this._fillGridMeshWithLods(GLOBE_VERTEX_GRID_SIZE, GLOBE_LATITUDINAL_GRID_LOD_TABLE);\n this._gridSegments = gridWithLods.segments;\n\n this._gridBuffer = context.createVertexBuffer(gridWithLods.vertices, posAttributes.members);\n this._gridIndexBuffer = context.createIndexBuffer(gridWithLods.indices, true);\n }\n\n _createPoles(context: Context) {\n const poleIndices = new TriangleIndexArray();\n for (let i = 0; i <= GLOBE_VERTEX_GRID_SIZE; i++) {\n poleIndices.emplaceBack(0, i + 1, i + 2);\n }\n this._poleIndexBuffer = context.createIndexBuffer(poleIndices, true);\n\n const northVertices = new GlobeVertexArray();\n const southVertices = new GlobeVertexArray();\n const polePrimitives = GLOBE_VERTEX_GRID_SIZE;\n const poleVertices = GLOBE_VERTEX_GRID_SIZE + 2;\n this._poleSegments = [];\n\n for (let zoom = 0, offset = 0; zoom < GLOBE_ZOOM_THRESHOLD_MIN; zoom++) {\n const tiles = 1 << zoom;\n const endAngle = 360.0 / tiles;\n\n northVertices.emplaceBack(0, -GLOBE_RADIUS, 0, 0.5, 0); // place the tip\n southVertices.emplaceBack(0, -GLOBE_RADIUS, 0, 0.5, 1);\n\n for (let i = 0; i <= GLOBE_VERTEX_GRID_SIZE; i++) {\n const uvX = i / GLOBE_VERTEX_GRID_SIZE;\n const angle = interpolate(0, endAngle, uvX);\n const [gx, gy, gz] = csLatLngToECEF(POLE_COS, POLE_SIN, angle, GLOBE_RADIUS);\n northVertices.emplaceBack(gx, gy, gz, uvX, 0);\n southVertices.emplaceBack(gx, gy, gz, uvX, 1);\n }\n\n this._poleSegments.push(SegmentVector.simpleSegment(offset, 0, poleVertices, polePrimitives));\n\n offset += poleVertices;\n }\n\n this._poleNorthVertexBuffer = context.createVertexBuffer(northVertices, globeLayoutAttributes, false);\n this._poleSouthVertexBuffer = context.createVertexBuffer(southVertices, globeLayoutAttributes, false);\n }\n\n getGridBuffers(latitudinalLod: number, withSkirts: boolean): [VertexBuffer, IndexBuffer, SegmentVector] {\n return [this._gridBuffer, this._gridIndexBuffer, withSkirts ? this._gridSegments[latitudinalLod].withSkirts : this._gridSegments[latitudinalLod].withoutSkirts];\n }\n\n getPoleBuffers(z: number): [VertexBuffer, VertexBuffer, IndexBuffer, SegmentVector] {\n return [this._poleNorthVertexBuffer, this._poleSouthVertexBuffer, this._poleIndexBuffer, this._poleSegments[z]];\n }\n\n getWirefameBuffers(context: Context, lod: number): [VertexBuffer, IndexBuffer, SegmentVector] {\n if (!this._wireframeSegments) {\n const wireframeIndices = new LineIndexArray();\n const quadExt = GLOBE_VERTEX_GRID_SIZE;\n const vertexExt = quadExt + 1 + (EMBED_SKIRTS ? 2 : 0);\n\n const iterOffset = EMBED_SKIRTS ? 1 : 0;\n\n this._wireframeSegments = [];\n for (let k = 0, primitiveOffset = 0; k < GLOBE_LATITUDINAL_GRID_LOD_TABLE.length; k++) {\n const latitudinalLod = GLOBE_LATITUDINAL_GRID_LOD_TABLE[k];\n for (let j = iterOffset; j < latitudinalLod + iterOffset; j++) {\n for (let i = iterOffset; i < quadExt + iterOffset; i++) {\n const index = j * vertexExt + i;\n wireframeIndices.emplaceBack(index, index + 1);\n wireframeIndices.emplaceBack(index, index + vertexExt);\n wireframeIndices.emplaceBack(index, index + vertexExt + 1);\n }\n }\n\n const numVertices = (latitudinalLod + 1) * vertexExt;\n const numPrimitives = latitudinalLod * quadExt * 3;\n\n this._wireframeSegments.push(SegmentVector.simpleSegment(0, primitiveOffset, numVertices, numPrimitives));\n primitiveOffset += numPrimitives;\n }\n\n this._wireframeIndexBuffer = context.createIndexBuffer(wireframeIndices);\n }\n return [this._gridBuffer, this._wireframeIndexBuffer, this._wireframeSegments[lod]];\n }\n}\n","// @flow\n\nimport {wrap} from '../util/util.js';\nimport LngLatBounds from './lng_lat_bounds.js';\nimport {GLOBE_RADIUS, globeMetersToEcef, latLngToECEF} from '../geo/projection/globe_util.js';\n\n/*\n* Approximate radius of the earth in meters.\n* Uses the WGS-84 approximation. The radius at the equator is ~6378137 and at the poles is ~6356752. https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84\n* 6371008.8 is one published \"average radius\" see https://en.wikipedia.org/wiki/Earth_radius#Mean_radius, or ftp://athena.fsv.cvut.cz/ZFG/grs80-Moritz.pdf p.4\n*/\nexport const earthRadius = 6371008.8;\n\n/*\n * The average circumference of the earth in meters.\n */\nexport const earthCircumference = 2 * Math.PI * earthRadius;\n\n/**\n * A `LngLat` object represents a given longitude and latitude coordinate, measured in degrees.\n * These coordinates use longitude, latitude coordinate order (as opposed to latitude, longitude)\n * to match the [GeoJSON specification](https://datatracker.ietf.org/doc/html/rfc7946#section-4),\n * which is equivalent to the OGC:CRS84 coordinate reference system.\n *\n * Note that any Mapbox GL method that accepts a `LngLat` object as an argument or option\n * can also accept an `Array` of two numbers and will perform an implicit conversion.\n * This flexible type is documented as {@link LngLatLike}.\n *\n * @param {number} lng Longitude, measured in degrees.\n * @param {number} lat Latitude, measured in degrees.\n * @example\n * const ll = new mapboxgl.LngLat(-123.9749, 40.7736);\n * console.log(ll.lng); // = -123.9749\n * @see [Example: Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/)\n * @see [Example: Display a popup](https://www.mapbox.com/mapbox-gl-js/example/popup/)\n * @see [Example: Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)\n * @see [Example: Create a timeline animation](https://www.mapbox.com/mapbox-gl-js/example/timeline-animation/)\n */\nclass LngLat {\n lng: number;\n lat: number;\n\n constructor(lng: number, lat: number) {\n if (isNaN(lng) || isNaN(lat)) {\n throw new Error(`Invalid LngLat object: (${lng}, ${lat})`);\n }\n this.lng = +lng;\n this.lat = +lat;\n if (this.lat > 90 || this.lat < -90) {\n throw new Error('Invalid LngLat latitude value: must be between -90 and 90');\n }\n }\n\n /**\n * Returns a new `LngLat` object whose longitude is wrapped to the range (-180, 180).\n *\n * @returns {LngLat} The wrapped `LngLat` object.\n * @example\n * const ll = new mapboxgl.LngLat(286.0251, 40.7736);\n * const wrapped = ll.wrap();\n * console.log(wrapped.lng); // = -73.9749\n */\n wrap(): LngLat {\n return new LngLat(wrap(this.lng, -180, 180), this.lat);\n }\n\n /**\n * Returns the coordinates represented as an array of two numbers.\n *\n * @returns {Array<number>} The coordinates represeted as an array of longitude and latitude.\n * @example\n * const ll = new mapboxgl.LngLat(-73.9749, 40.7736);\n * ll.toArray(); // = [-73.9749, 40.7736]\n */\n toArray(): [number, number] {\n return [this.lng, this.lat];\n }\n\n /**\n * Returns the coordinates represent as a string.\n *\n * @returns {string} The coordinates represented as a string of the format `'LngLat(lng, lat)'`.\n * @example\n * const ll = new mapboxgl.LngLat(-73.9749, 40.7736);\n * ll.toString(); // = \"LngLat(-73.9749, 40.7736)\"\n */\n toString(): string {\n return `LngLat(${this.lng}, ${this.lat})`;\n }\n\n /**\n * Returns the approximate distance between a pair of coordinates in meters.\n * Uses the Haversine Formula (from R.W. Sinnott, \"Virtues of the Haversine\", Sky and Telescope, vol. 68, no. 2, 1984, p. 159).\n *\n * @param {LngLat} lngLat Coordinates to compute the distance to.\n * @returns {number} Distance in meters between the two coordinates.\n * @example\n * const newYork = new mapboxgl.LngLat(-74.0060, 40.7128);\n * const losAngeles = new mapboxgl.LngLat(-118.2437, 34.0522);\n * newYork.distanceTo(losAngeles); // = 3935751.690893987, \"true distance\" using a non-spherical approximation is ~3966km\n */\n distanceTo(lngLat: LngLat): number {\n const rad = Math.PI / 180;\n const lat1 = this.lat * rad;\n const lat2 = lngLat.lat * rad;\n const a = Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos((lngLat.lng - this.lng) * rad);\n\n const maxMeters = earthRadius * Math.acos(Math.min(a, 1));\n return maxMeters;\n }\n\n /**\n * Returns a `LngLatBounds` from the coordinates extended by a given `radius`. The returned `LngLatBounds` completely contains the `radius`.\n *\n * @param {number} [radius=0] Distance in meters from the coordinates to extend the bounds.\n * @returns {LngLatBounds} A new `LngLatBounds` object representing the coordinates extended by the `radius`.\n * @example\n * const ll = new mapboxgl.LngLat(-73.9749, 40.7736);\n * ll.toBounds(100).toArray(); // = [[-73.97501862141328, 40.77351016847229], [-73.97478137858673, 40.77368983152771]]\n */\n toBounds(radius?: number = 0): LngLatBounds {\n const earthCircumferenceInMetersAtEquator = 40075017;\n const latAccuracy = 360 * radius / earthCircumferenceInMetersAtEquator,\n lngAccuracy = latAccuracy / Math.cos((Math.PI / 180) * this.lat);\n\n return new LngLatBounds(new LngLat(this.lng - lngAccuracy, this.lat - latAccuracy),\n new LngLat(this.lng + lngAccuracy, this.lat + latAccuracy));\n }\n\n toEcef(altitude: number): [number, number, number] {\n const altInEcef = globeMetersToEcef(altitude);\n const radius = GLOBE_RADIUS + altInEcef;\n return (latLngToECEF(this.lat, this.lng, radius): any);\n }\n\n /**\n * Converts an array of two numbers or an object with `lng` and `lat` or `lon` and `lat` properties\n * to a `LngLat` object.\n *\n * If a `LngLat` object is passed in, the function returns it unchanged.\n *\n * @param {LngLatLike} input An array of two numbers or object to convert, or a `LngLat` object to return.\n * @returns {LngLat} A new `LngLat` object, if a conversion occurred, or the original `LngLat` object.\n * @example\n * const arr = [-73.9749, 40.7736];\n * const ll = mapboxgl.LngLat.convert(arr);\n * console.log(ll); // = LngLat {lng: -73.9749, lat: 40.7736}\n */\n static convert(input: LngLatLike): LngLat {\n if (input instanceof LngLat) {\n return input;\n }\n if (Array.isArray(input) && (input.length === 2 || input.length === 3)) {\n return new LngLat(Number(input[0]), Number(input[1]));\n }\n if (!Array.isArray(input) && typeof input === 'object' && input !== null) {\n return new LngLat(\n // flow can't refine this to have one of lng or lat, so we have to cast to any\n Number('lng' in input ? (input: any).lng : (input: any).lon),\n Number(input.lat)\n );\n }\n throw new Error(\"`LngLatLike` argument must be specified as a LngLat instance, an object {lng: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]\");\n }\n}\n\n/**\n * A {@link LngLat} object, an array of two numbers representing longitude and latitude,\n * or an object with `lng` and `lat` or `lon` and `lat` properties.\n *\n * @typedef {LngLat | {lng: number, lat: number} | {lon: number, lat: number} | [number, number]} LngLatLike\n * @example\n * const v1 = new mapboxgl.LngLat(-122.420679, 37.772537);\n * const v2 = [-122.420679, 37.772537];\n * const v3 = {lon: -122.420679, lat: 37.772537};\n */\nexport type LngLatLike = LngLat | {lng: number, lat: number} | {lon: number, lat: number} | [number, number];\n\nexport default LngLat;\n","// @flow\n\nimport LngLat, {earthCircumference} from '../geo/lng_lat.js';\nimport type {LngLatLike} from '../geo/lng_lat.js';\n\n/*\n * The circumference at a line of latitude in meters.\n */\nexport function circumferenceAtLatitude(latitude: number): number {\n return earthCircumference * Math.cos(latitude * Math.PI / 180);\n}\n\nexport function mercatorXfromLng(lng: number): number {\n return (180 + lng) / 360;\n}\n\nexport function mercatorYfromLat(lat: number): number {\n return (180 - (180 / Math.PI * Math.log(Math.tan(Math.PI / 4 + lat * Math.PI / 360)))) / 360;\n}\n\nexport function mercatorZfromAltitude(altitude: number, lat: number): number {\n return altitude / circumferenceAtLatitude(lat);\n}\n\nexport function lngFromMercatorX(x: number): number {\n return x * 360 - 180;\n}\n\nexport function latFromMercatorY(y: number): number {\n const y2 = 180 - y * 360;\n return 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90;\n}\n\nexport function altitudeFromMercatorZ(z: number, y: number): number {\n return z * circumferenceAtLatitude(latFromMercatorY(y));\n}\n\nexport const MAX_MERCATOR_LATITUDE = 85.051129;\n\n/**\n * Determine the Mercator scale factor for a given latitude, see\n * https://en.wikipedia.org/wiki/Mercator_projection#Scale_factor\n *\n * At the equator the scale factor will be 1, which increases at higher latitudes.\n *\n * @param {number} lat Latitude\n * @returns {number} scale factor\n * @private\n */\nexport function mercatorScale(lat: number): number {\n return 1 / Math.cos(lat * Math.PI / 180);\n}\n\n/**\n * A `MercatorCoordinate` object represents a projected three dimensional position.\n *\n * `MercatorCoordinate` uses the web mercator projection ([EPSG:3857](https://epsg.io/3857)) with slightly different units:\n * - the size of 1 unit is the width of the projected world instead of the \"mercator meter\"\n * - the origin of the coordinate space is at the north-west corner instead of the middle.\n *\n * For example, `MercatorCoordinate(0, 0, 0)` is the north-west corner of the mercator world and\n * `MercatorCoordinate(1, 1, 0)` is the south-east corner. If you are familiar with\n * [vector tiles](https://github.com/mapbox/vector-tile-spec) it may be helpful to think\n * of the coordinate space as the `0/0/0` tile with an extent of `1`.\n *\n * The `z` dimension of `MercatorCoordinate` is conformal. A cube in the mercator coordinate space would be rendered as a cube.\n *\n * @param {number} x The x component of the position.\n * @param {number} y The y component of the position.\n * @param {number} z The z component of the position.\n * @example\n * const nullIsland = new mapboxgl.MercatorCoordinate(0.5, 0.5, 0);\n *\n * @see [Example: Add a custom style layer](https://www.mapbox.com/mapbox-gl-js/example/custom-style-layer/)\n */\nclass MercatorCoordinate {\n x: number;\n y: number;\n z: number;\n\n constructor(x: number, y: number, z: number = 0) {\n this.x = +x;\n this.y = +y;\n this.z = +z;\n }\n\n /**\n * Project a `LngLat` to a `MercatorCoordinate`.\n *\n * @param {LngLatLike} lngLatLike The location to project.\n * @param {number} altitude The altitude in meters of the position.\n * @returns {MercatorCoordinate} The projected mercator coordinate.\n * @example\n * const coord = mapboxgl.MercatorCoordinate.fromLngLat({lng: 0, lat: 0}, 0);\n * console.log(coord); // MercatorCoordinate(0.5, 0.5, 0)\n */\n static fromLngLat(lngLatLike: LngLatLike, altitude: number = 0): MercatorCoordinate {\n const lngLat = LngLat.convert(lngLatLike);\n\n return new MercatorCoordinate(\n mercatorXfromLng(lngLat.lng),\n mercatorYfromLat(lngLat.lat),\n mercatorZfromAltitude(altitude, lngLat.lat));\n }\n\n /**\n * Returns the `LngLat` for the coordinate.\n *\n * @returns {LngLat} The `LngLat` object.\n * @example\n * const coord = new mapboxgl.MercatorCoordinate(0.5, 0.5, 0);\n * const lngLat = coord.toLngLat(); // LngLat(0, 0)\n */\n toLngLat(): LngLat {\n return new LngLat(\n lngFromMercatorX(this.x),\n latFromMercatorY(this.y));\n }\n\n /**\n * Returns the altitude in meters of the coordinate.\n *\n * @returns {number} The altitude in meters.\n * @example\n * const coord = new mapboxgl.MercatorCoordinate(0, 0, 0.02);\n * coord.toAltitude(); // 6914.281956295339\n */\n toAltitude(): number {\n return altitudeFromMercatorZ(this.z, this.y);\n }\n\n /**\n * Returns the distance of 1 meter in `MercatorCoordinate` units at this latitude.\n *\n * For coordinates in real world units using meters, this naturally provides the scale\n * to transform into `MercatorCoordinate`s.\n *\n * @returns {number} Distance of 1 meter in `MercatorCoordinate` units.\n * @example\n * // Calculate a new MercatorCoordinate that is 150 meters west of the other coord.\n * const coord = new mapboxgl.MercatorCoordinate(0.5, 0.25, 0);\n * const offsetInMeters = 150;\n * const offsetInMercatorCoordinateUnits = offsetInMeters * coord.meterInMercatorCoordinateUnits();\n * const westCoord = new mapboxgl.MercatorCoordinate(coord.x - offsetInMercatorCoordinateUnits, coord.y, coord.z);\n */\n meterInMercatorCoordinateUnits(): number {\n // 1 meter / circumference at equator in meters * Mercator projection scale factor at this latitude\n return 1 / earthCircumference * mercatorScale(latFromMercatorY(this.y));\n }\n\n}\n\nexport default MercatorCoordinate;\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nfunction pointToLineDist(px: number, py: number, ax: number, ay: number, bx: number, by: number) {\n const dx = ax - bx;\n const dy = ay - by;\n return Math.abs((ay - py) * dx - (ax - px) * dy) / Math.hypot(dx, dy);\n}\n\nfunction addResampled(resampled: Array<Point>, mx0: number, my0: number, mx2: number, my2: number, start: Point, end: Point, reproject: ((Point) => void), tolerance: number) {\n const mx1 = (mx0 + mx2) / 2;\n const my1 = (my0 + my2) / 2;\n const mid = new Point(mx1, my1);\n reproject(mid);\n const err = pointToLineDist(mid.x, mid.y, start.x, start.y, end.x, end.y);\n\n // if reprojected midPoint is too far from geometric midpoint, recurse into two halves\n if (err >= tolerance) {\n // we're very unlikely to hit max call stack exceeded here,\n // but we might want to safeguard against it in the future\n addResampled(resampled, mx0, my0, mx1, my1, start, mid, reproject, tolerance);\n addResampled(resampled, mx1, my1, mx2, my2, mid, end, reproject, tolerance);\n\n } else { // otherwise, just add the point\n resampled.push(end);\n }\n}\n\n// reproject and resample a line, adding point where necessary for lines that become curves;\n// note that this operation is mutable (modifying original points) for performance\nexport default function resample(line: Array<Point>, reproject: (Point) => void, tolerance: number): Array<Point> {\n let prev = line[0];\n let mx0 = prev.x;\n let my0 = prev.y;\n reproject(prev);\n const resampled = [prev];\n\n for (let i = 1; i < line.length; i++) {\n const point = line[i];\n const {x, y} = point;\n reproject(point);\n addResampled(resampled, mx0, my0, x, y, prev, point, reproject, tolerance);\n mx0 = x;\n my0 = y;\n prev = point;\n }\n\n return resampled;\n}\n\nfunction addResampledPred(resampled: Point[], a: Point, b: Point, pred: ((Point, Point) => boolean)) {\n const split = pred(a, b);\n\n // if the predicate condition is met, recurse into two halves\n if (split) {\n const mid = a.add(b)._mult(0.5);\n addResampledPred(resampled, a, mid, pred);\n addResampledPred(resampled, mid, b, pred);\n\n } else {\n resampled.push(b);\n }\n}\n\nexport function resamplePred(line: Point[], predicate: (Point, Point) => boolean): Point[] {\n let prev = line[0];\n const resampled = [prev];\n\n for (let i = 1; i < line.length; i++) {\n const point = line[i];\n addResampledPred(resampled, prev, point, predicate);\n prev = point;\n }\n\n return resampled;\n}\n","// @flow\n\nimport {warnOnce, clamp} from '../util/util.js';\n\nimport EXTENT from './extent.js';\nimport {lngFromMercatorX, latFromMercatorY} from '../geo/mercator_coordinate.js';\nimport resample from '../geo/projection/resample.js';\nimport Point from '@mapbox/point-geometry';\n\nimport type {CanonicalTileID} from '../source/tile_id.js';\nimport type {TileTransform} from '../geo/projection/tile_transform.js';\n\n// These bounds define the minimum and maximum supported coordinate values.\n// While visible coordinates are within [0, EXTENT], tiles may theoretically\n// contain coordinates within [-Infinity, Infinity]. Our range is limited by the\n// number of bits used to represent the coordinate.\nconst BITS = 15;\nconst MAX = Math.pow(2, BITS - 1) - 1;\nconst MIN = -MAX - 1;\n\nfunction preparePoint(point: Point, scale: number) {\n const x = Math.round(point.x * scale);\n const y = Math.round(point.y * scale);\n point.x = clamp(x, MIN, MAX);\n point.y = clamp(y, MIN, MAX);\n if (x < point.x || x > point.x + 1 || y < point.y || y > point.y + 1) {\n // warn when exceeding allowed extent except for the 1-px-off case\n // https://github.com/mapbox/mapbox-gl-js/issues/8992\n warnOnce('Geometry exceeds allowed extent, reduce your vector tile buffer size');\n }\n return point;\n}\n\n// a subset of VectorTileGeometry\ninterface FeatureWithGeometry {\n extent: number;\n type: 1 | 2 | 3;\n loadGeometry(): Array<Array<Point>>;\n}\n\n/**\n * Loads a geometry from a VectorTileFeature and scales it to the common extent\n * used internally.\n * @param {VectorTileFeature} feature\n * @private\n */\nexport default function loadGeometry(feature: FeatureWithGeometry, canonical?: CanonicalTileID, tileTransform?: TileTransform): Array<Array<Point>> {\n const geometry = feature.loadGeometry();\n const extent = feature.extent;\n const extentScale = EXTENT / extent;\n\n if (canonical && tileTransform && tileTransform.projection.isReprojectedInTileSpace) {\n const z2 = 1 << canonical.z;\n const {scale, x, y, projection} = tileTransform;\n\n const reproject = (p: Point) => {\n const lng = lngFromMercatorX((canonical.x + p.x / extent) / z2);\n const lat = latFromMercatorY((canonical.y + p.y / extent) / z2);\n const p2 = projection.project(lng, lat);\n p.x = (p2.x * scale - x) * extent;\n p.y = (p2.y * scale - y) * extent;\n };\n\n for (let i = 0; i < geometry.length; i++) {\n if (feature.type !== 1) {\n geometry[i] = resample(geometry[i], reproject, 1); // resample lines and polygons\n\n } else { // points\n const line = [];\n for (const p of geometry[i]) {\n // filter out point features outside tile boundaries now; it'd be harder to do later\n // when the coords are reprojected and no longer axis-aligned; ideally this would happen\n // or not depending on how the geometry is used, but we forego the complexity for now\n if (p.x < 0 || p.x >= extent || p.y < 0 || p.y >= extent) continue;\n reproject(p);\n line.push(p);\n }\n geometry[i] = line;\n }\n }\n }\n\n for (const line of geometry) {\n for (const p of line) {\n preparePoint(p, extentScale);\n }\n }\n\n return geometry;\n}\n","// @flow\n\nimport loadGeometry from './load_geometry.js';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {IVectorTileFeature} from '@mapbox/vector-tile';\n\ntype EvaluationFeature = {\n +type: 1 | 2 | 3 | 'Unknown' | 'Point' | 'LineString' | 'Polygon',\n +id?: any,\n +properties: {[_: string]: any},\n +patterns?: {[_: string]: string},\n geometry: Array<Array<Point>>\n};\n\n/**\n * Construct a new feature based on a VectorTileFeature for expression evaluation, the geometry of which\n * will be loaded based on necessity.\n * @param {VectorTileFeature} feature\n * @param {boolean} needGeometry\n * @private\n */\nexport default function toEvaluationFeature(feature: IVectorTileFeature, needGeometry: boolean): EvaluationFeature {\n return {type: feature.type,\n id: feature.id,\n properties:feature.properties,\n geometry: needGeometry ? loadGeometry(feature) : []};\n}\n","// @flow\n\nimport {CircleLayoutArray, CircleGlobeExtArray} from '../array_types.js';\n\nimport {circleAttributes, circleGlobeAttributesExt} from './circle_attributes.js';\nimport SegmentVector from '../segment.js';\nimport {ProgramConfigurationSet} from '../program_configuration.js';\nimport {TriangleIndexArray} from '../index_array_type.js';\nimport loadGeometry from '../load_geometry.js';\nimport toEvaluationFeature from '../evaluation_feature.js';\nimport EXTENT from '../extent.js';\nimport {register} from '../../util/web_worker_transfer.js';\nimport EvaluationParameters from '../../style/evaluation_parameters.js';\n\nimport type {CanonicalTileID} from '../../source/tile_id.js';\nimport type {\n Bucket,\n BucketParameters,\n BucketFeature,\n IndexedFeature,\n PopulateParameters\n} from '../bucket.js';\nimport type CircleStyleLayer from '../../style/style_layer/circle_style_layer.js';\nimport type HeatmapStyleLayer from '../../style/style_layer/heatmap_style_layer.js';\nimport type Context from '../../gl/context.js';\nimport type IndexBuffer from '../../gl/index_buffer.js';\nimport type VertexBuffer from '../../gl/vertex_buffer.js';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureStates} from '../../source/source_state.js';\nimport type {SpritePositions} from '../../util/image.js';\nimport type {TileTransform} from '../../geo/projection/tile_transform.js';\nimport type {ProjectionSpecification} from '../../style-spec/types.js';\nimport type Projection from '../../geo/projection/projection.js';\nimport type {Vec3} from 'gl-matrix';\nimport type {IVectorTileLayer} from '@mapbox/vector-tile';\n\nfunction addCircleVertex(layoutVertexArray: CircleLayoutArray, x: number, y: number, extrudeX: number, extrudeY: number) {\n layoutVertexArray.emplaceBack(\n (x * 2) + ((extrudeX + 1) / 2),\n (y * 2) + ((extrudeY + 1) / 2));\n}\n\nfunction addGlobeExtVertex(vertexArray: CircleGlobeExtArray, pos: {x: number, y: number, z: number}, normal: Vec3) {\n const encode = 1 << 14;\n vertexArray.emplaceBack(\n pos.x, pos.y, pos.z,\n normal[0] * encode, normal[1] * encode, normal[2] * encode);\n}\n\n/**\n * Circles are represented by two triangles.\n *\n * Each corner has a pos that is the center of the circle and an extrusion\n * vector that is where it points.\n * @private\n */\nclass CircleBucket<Layer: CircleStyleLayer | HeatmapStyleLayer> implements Bucket {\n index: number;\n zoom: number;\n overscaling: number;\n layerIds: Array<string>;\n layers: Array<Layer>;\n stateDependentLayers: Array<Layer>;\n stateDependentLayerIds: Array<string>;\n\n layoutVertexArray: CircleLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n globeExtVertexArray: ?CircleGlobeExtArray;\n globeExtVertexBuffer: ?VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n hasPattern: boolean;\n programConfigurations: ProgramConfigurationSet<Layer>;\n segments: SegmentVector;\n uploaded: boolean;\n projection: ProjectionSpecification;\n\n constructor(options: BucketParameters<Layer>) {\n this.zoom = options.zoom;\n this.overscaling = options.overscaling;\n this.layers = options.layers;\n this.layerIds = this.layers.map(layer => layer.id);\n this.index = options.index;\n this.hasPattern = false;\n this.projection = options.projection;\n\n this.layoutVertexArray = new CircleLayoutArray();\n this.indexArray = new TriangleIndexArray();\n this.segments = new SegmentVector();\n this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n }\n\n populate(features: Array<IndexedFeature>, options: PopulateParameters, canonical: CanonicalTileID, tileTransform: TileTransform) {\n const styleLayer = this.layers[0];\n const bucketFeatures = [];\n let circleSortKey = null;\n\n // Heatmap layers are handled in this bucket and have no evaluated properties, so we check our access\n if (styleLayer.type === 'circle') {\n circleSortKey = ((styleLayer: any): CircleStyleLayer).layout.get('circle-sort-key');\n }\n\n for (const {feature, id, index, sourceLayerIndex} of features) {\n const needGeometry = this.layers[0]._featureFilter.needGeometry;\n const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n\n // $FlowFixMe[method-unbinding]\n if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) continue;\n\n const sortKey = circleSortKey ?\n circleSortKey.evaluate(evaluationFeature, {}, canonical) :\n undefined;\n\n const bucketFeature: BucketFeature = {\n id,\n properties: feature.properties,\n type: feature.type,\n sourceLayerIndex,\n index,\n geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature, canonical, tileTransform),\n patterns: {},\n sortKey\n };\n\n bucketFeatures.push(bucketFeature);\n\n }\n\n if (circleSortKey) {\n bucketFeatures.sort((a, b) => {\n // a.sortKey is always a number when in use\n return ((a.sortKey: any): number) - ((b.sortKey: any): number);\n });\n }\n\n let globeProjection: ?Projection = null;\n\n if (tileTransform.projection.name === 'globe') {\n // Extend vertex attributes if the globe projection is enabled\n this.globeExtVertexArray = new CircleGlobeExtArray();\n globeProjection = tileTransform.projection;\n }\n\n for (const bucketFeature of bucketFeatures) {\n const {geometry, index, sourceLayerIndex} = bucketFeature;\n const feature = features[index].feature;\n\n this.addFeature(bucketFeature, geometry, index, options.availableImages, canonical, globeProjection);\n options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);\n }\n }\n\n update(states: FeatureStates, vtLayer: IVectorTileLayer, availableImages: Array<string>, imagePositions: SpritePositions) {\n if (!this.stateDependentLayers.length) return;\n this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, availableImages, imagePositions);\n }\n\n isEmpty(): boolean {\n return this.layoutVertexArray.length === 0;\n }\n\n uploadPending(): boolean {\n return !this.uploaded || this.programConfigurations.needsUpload;\n }\n\n upload(context: Context) {\n if (!this.uploaded) {\n this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, circleAttributes.members);\n this.indexBuffer = context.createIndexBuffer(this.indexArray);\n\n if (this.globeExtVertexArray) {\n this.globeExtVertexBuffer = context.createVertexBuffer(this.globeExtVertexArray, circleGlobeAttributesExt.members);\n }\n }\n this.programConfigurations.upload(context);\n this.uploaded = true;\n }\n\n destroy() {\n if (!this.layoutVertexBuffer) return;\n this.layoutVertexBuffer.destroy();\n this.indexBuffer.destroy();\n this.programConfigurations.destroy();\n this.segments.destroy();\n if (this.globeExtVertexBuffer) {\n this.globeExtVertexBuffer.destroy();\n }\n }\n\n addFeature(feature: BucketFeature, geometry: Array<Array<Point>>, index: number, availableImages: Array<string>, canonical: CanonicalTileID, projection?: ?Projection) {\n for (const ring of geometry) {\n for (const point of ring) {\n const x = point.x;\n const y = point.y;\n\n // Do not include points that are outside the tile boundaries.\n if (x < 0 || x >= EXTENT || y < 0 || y >= EXTENT) continue;\n\n // this geometry will be of the Point type, and we'll derive\n // two triangles from it.\n //\n // ┌─────────┐\n // │ 3 2 │\n // │ │\n // │ 0 1 │\n // └─────────┘\n\n if (projection) {\n const projectedPoint = projection.projectTilePoint(x, y, canonical);\n const normal = projection.upVector(canonical, x, y);\n const array: any = this.globeExtVertexArray;\n\n addGlobeExtVertex(array, projectedPoint, normal);\n addGlobeExtVertex(array, projectedPoint, normal);\n addGlobeExtVertex(array, projectedPoint, normal);\n addGlobeExtVertex(array, projectedPoint, normal);\n }\n const segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray, feature.sortKey);\n const index = segment.vertexLength;\n\n addCircleVertex(this.layoutVertexArray, x, y, -1, -1);\n addCircleVertex(this.layoutVertexArray, x, y, 1, -1);\n addCircleVertex(this.layoutVertexArray, x, y, 1, 1);\n addCircleVertex(this.layoutVertexArray, x, y, -1, 1);\n\n this.indexArray.emplaceBack(index, index + 1, index + 2);\n this.indexArray.emplaceBack(index, index + 2, index + 3);\n\n segment.vertexLength += 4;\n segment.primitiveLength += 2;\n }\n }\n\n this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, {}, availableImages, canonical);\n }\n}\n\nregister(CircleBucket, 'CircleBucket', {omit: ['layers']});\n\nexport default CircleBucket;\n","// @flow\n\nimport {isCounterClockwise} from './util.js';\n\nimport Point from '@mapbox/point-geometry';\n\nexport {polygonIntersectsBufferedPoint, polygonIntersectsMultiPolygon, polygonIntersectsBufferedMultiLine, polygonIntersectsPolygon, distToSegmentSquared, polygonIntersectsBox, polygonContainsPoint};\n\ntype Line = $ReadOnlyArray<Point>;\ntype MultiLine = $ReadOnlyArray<Line>;\ntype Ring = $ReadOnlyArray<Point>;\ntype Polygon = $ReadOnlyArray<Point>;\ntype MultiPolygon = $ReadOnlyArray<Polygon>;\n\nfunction polygonIntersectsPolygon(polygonA: Polygon, polygonB: Polygon): boolean {\n for (let i = 0; i < polygonA.length; i++) {\n if (polygonContainsPoint(polygonB, polygonA[i])) return true;\n }\n\n for (let i = 0; i < polygonB.length; i++) {\n if (polygonContainsPoint(polygonA, polygonB[i])) return true;\n }\n\n if (lineIntersectsLine(polygonA, polygonB)) return true;\n\n return false;\n}\n\nfunction polygonIntersectsBufferedPoint(polygon: Polygon, point: Point, radius: number): boolean {\n if (polygonContainsPoint(polygon, point)) return true;\n if (pointIntersectsBufferedLine(point, polygon, radius)) return true;\n return false;\n}\n\nfunction polygonIntersectsMultiPolygon(polygon: Polygon, multiPolygon: MultiPolygon): boolean {\n\n if (polygon.length === 1) {\n return multiPolygonContainsPoint(multiPolygon, polygon[0]);\n }\n\n for (let m = 0; m < multiPolygon.length; m++) {\n const ring = multiPolygon[m];\n for (let n = 0; n < ring.length; n++) {\n if (polygonContainsPoint(polygon, ring[n])) return true;\n }\n }\n\n for (let i = 0; i < polygon.length; i++) {\n if (multiPolygonContainsPoint(multiPolygon, polygon[i])) return true;\n }\n\n for (let k = 0; k < multiPolygon.length; k++) {\n if (lineIntersectsLine(polygon, multiPolygon[k])) return true;\n }\n\n return false;\n}\n\nfunction polygonIntersectsBufferedMultiLine(polygon: Polygon, multiLine: MultiLine, radius: number): boolean {\n for (let i = 0; i < multiLine.length; i++) {\n const line = multiLine[i];\n\n if (polygon.length >= 3) {\n for (let k = 0; k < line.length; k++) {\n if (polygonContainsPoint(polygon, line[k])) return true;\n }\n }\n\n if (lineIntersectsBufferedLine(polygon, line, radius)) return true;\n }\n return false;\n}\n\nfunction lineIntersectsBufferedLine(lineA: Line, lineB: Line, radius: number) {\n\n if (lineA.length > 1) {\n if (lineIntersectsLine(lineA, lineB)) return true;\n\n // Check whether any point in either line is within radius of the other line\n for (let j = 0; j < lineB.length; j++) {\n if (pointIntersectsBufferedLine(lineB[j], lineA, radius)) return true;\n }\n }\n\n for (let k = 0; k < lineA.length; k++) {\n if (pointIntersectsBufferedLine(lineA[k], lineB, radius)) return true;\n }\n\n return false;\n}\n\nfunction lineIntersectsLine(lineA: Line, lineB: Line) {\n if (lineA.length === 0 || lineB.length === 0) return false;\n for (let i = 0; i < lineA.length - 1; i++) {\n const a0 = lineA[i];\n const a1 = lineA[i + 1];\n for (let j = 0; j < lineB.length - 1; j++) {\n const b0 = lineB[j];\n const b1 = lineB[j + 1];\n if (lineSegmentIntersectsLineSegment(a0, a1, b0, b1)) return true;\n }\n }\n return false;\n}\n\nfunction lineSegmentIntersectsLineSegment(a0: Point, a1: Point, b0: Point, b1: Point) {\n return isCounterClockwise(a0, b0, b1) !== isCounterClockwise(a1, b0, b1) &&\n isCounterClockwise(a0, a1, b0) !== isCounterClockwise(a0, a1, b1);\n}\n\nfunction pointIntersectsBufferedLine(p: Point, line: Line, radius: number) {\n const radiusSquared = radius * radius;\n\n if (line.length === 1) return p.distSqr(line[0]) < radiusSquared;\n\n for (let i = 1; i < line.length; i++) {\n // Find line segments that have a distance <= radius^2 to p\n // In that case, we treat the line as \"containing point p\".\n const v = line[i - 1], w = line[i];\n if (distToSegmentSquared(p, v, w) < radiusSquared) return true;\n }\n return false;\n}\n\n// Code from http://stackoverflow.com/a/1501725/331379.\nfunction distToSegmentSquared(p: Point, v: Point, w: Point): number {\n const l2 = v.distSqr(w);\n if (l2 === 0) return p.distSqr(v);\n const t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;\n if (t < 0) return p.distSqr(v);\n if (t > 1) return p.distSqr(w);\n return p.distSqr(w.sub(v)._mult(t)._add(v));\n}\n\n// point in polygon ray casting algorithm\nfunction multiPolygonContainsPoint(rings: MultiPolygon, p: Point) {\n let c = false,\n ring, p1, p2;\n\n for (let k = 0; k < rings.length; k++) {\n ring = rings[k];\n for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {\n p1 = ring[i];\n p2 = ring[j];\n if (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {\n c = !c;\n }\n }\n }\n return c;\n}\n\nfunction polygonContainsPoint(ring: Ring, p: Point): boolean {\n let c = false;\n for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {\n const p1 = ring[i];\n const p2 = ring[j];\n if (((p1.y > p.y) !== (p2.y > p.y)) && (p.x < (p2.x - p1.x) * (p.y - p1.y) / (p2.y - p1.y) + p1.x)) {\n c = !c;\n }\n }\n return c;\n}\n\nfunction polygonIntersectsBox(ring: Ring, boxX1: number, boxY1: number, boxX2: number, boxY2: number): boolean {\n for (const p of ring) {\n if (boxX1 <= p.x &&\n boxY1 <= p.y &&\n boxX2 >= p.x &&\n boxY2 >= p.y) return true;\n }\n\n const corners = [\n new Point(boxX1, boxY1),\n new Point(boxX1, boxY2),\n new Point(boxX2, boxY2),\n new Point(boxX2, boxY1)];\n\n if (ring.length > 2) {\n for (const corner of corners) {\n if (polygonContainsPoint(ring, corner)) return true;\n }\n }\n\n for (let i = 0; i < ring.length - 1; i++) {\n const p1 = ring[i];\n const p2 = ring[i + 1];\n if (edgeIntersectsBox(p1, p2, corners)) return true;\n }\n\n return false;\n}\n\nfunction edgeIntersectsBox(e1: Point, e2: Point, corners: Array<Point>) {\n const tl = corners[0];\n const br = corners[2];\n // the edge and box do not intersect in either the x or y dimensions\n if (((e1.x < tl.x) && (e2.x < tl.x)) ||\n ((e1.x > br.x) && (e2.x > br.x)) ||\n ((e1.y < tl.y) && (e2.y < tl.y)) ||\n ((e1.y > br.y) && (e2.y > br.y))) return false;\n\n // check if all corners of the box are on the same side of the edge\n const dir = isCounterClockwise(e1, e2, corners[0]);\n return dir !== isCounterClockwise(e1, e2, corners[1]) ||\n dir !== isCounterClockwise(e1, e2, corners[2]) ||\n dir !== isCounterClockwise(e1, e2, corners[3]);\n}\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport type {PossiblyEvaluatedPropertyValue} from './properties.js';\nimport type StyleLayer from '../style/style_layer.js';\nimport type CircleBucket from '../data/bucket/circle_bucket.js';\nimport type LineBucket from '../data/bucket/line_bucket.js';\n\nexport function getMaximumPaintValue(property: string, layer: StyleLayer, bucket: CircleBucket<*> | LineBucket): number {\n const value = ((layer.paint: any).get(property): PossiblyEvaluatedPropertyValue<any>).value;\n if (value.kind === 'constant') {\n return value.value;\n } else {\n return bucket.programConfigurations.get(layer.id).getMaxValue(property);\n }\n}\n\nexport function translateDistance(translate: [number, number]): number {\n return Math.sqrt(translate[0] * translate[0] + translate[1] * translate[1]);\n}\n\nexport function translate(queryGeometry: Array<Point>,\n translate: [number, number],\n translateAnchor: 'viewport' | 'map',\n bearing: number,\n pixelsToTileUnits: number): Array<Point> {\n if (!translate[0] && !translate[1]) {\n return queryGeometry;\n }\n const pt = Point.convert(translate)._mult(pixelsToTileUnits);\n\n if (translateAnchor === \"viewport\") {\n pt._rotate(-bearing);\n }\n\n const translated = [];\n for (let i = 0; i < queryGeometry.length; i++) {\n const point = queryGeometry[i];\n translated.push(point.sub(pt));\n }\n return translated;\n}\n\nexport function tilespaceTranslate(translate: [number, number],\n translateAnchor: 'viewport' | 'map',\n bearing: number,\n pixelsToTileUnits: number): Point {\n const pt = Point.convert(translate)._mult(pixelsToTileUnits);\n\n if (translateAnchor === \"viewport\") {\n pt._rotate(-bearing);\n }\n\n return pt;\n}\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest.js';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n ColorRampProperty\n} from '../properties.js';\n\nimport type Color from '../../style-spec/util/color.js';\n\nimport type Formatted from '../../style-spec/expression/types/formatted.js';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image.js';\n\nexport type LayoutProps = {|\n \"circle-sort-key\": DataDrivenProperty<number>,\n|};\n\nconst layout: Properties<LayoutProps> = new Properties({\n \"circle-sort-key\": new DataDrivenProperty(styleSpec[\"layout_circle\"][\"circle-sort-key\"]),\n});\n\nexport type PaintProps = {|\n \"circle-radius\": DataDrivenProperty<number>,\n \"circle-color\": DataDrivenProperty<Color>,\n \"circle-blur\": DataDrivenProperty<number>,\n \"circle-opacity\": DataDrivenProperty<number>,\n \"circle-translate\": DataConstantProperty<[number, number]>,\n \"circle-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"circle-pitch-scale\": DataConstantProperty<\"map\" | \"viewport\">,\n \"circle-pitch-alignment\": DataConstantProperty<\"map\" | \"viewport\">,\n \"circle-stroke-width\": DataDrivenProperty<number>,\n \"circle-stroke-color\": DataDrivenProperty<Color>,\n \"circle-stroke-opacity\": DataDrivenProperty<number>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"circle-radius\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-radius\"]),\n \"circle-color\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-color\"]),\n \"circle-blur\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-blur\"]),\n \"circle-opacity\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-opacity\"]),\n \"circle-translate\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-translate\"]),\n \"circle-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-translate-anchor\"]),\n \"circle-pitch-scale\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-pitch-scale\"]),\n \"circle-pitch-alignment\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-pitch-alignment\"]),\n \"circle-stroke-width\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-width\"]),\n \"circle-stroke-color\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-color\"]),\n \"circle-stroke-opacity\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-opacity\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint, layout }: $Exact<{\n paint: Properties<PaintProps>, layout: Properties<LayoutProps>\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer.js';\n\nimport CircleBucket from '../../data/bucket/circle_bucket.js';\nimport {polygonIntersectsBufferedPoint} from '../../util/intersection_tests.js';\nimport {getMaximumPaintValue, translateDistance, tilespaceTranslate} from '../query_utils.js';\nimport properties from './circle_style_layer_properties.js';\nimport {Transitionable, Transitioning, Layout, PossiblyEvaluated} from '../properties.js';\nimport {vec4, vec3} from 'gl-matrix';\nimport Point from '@mapbox/point-geometry';\nimport ProgramConfiguration from '../../data/program_configuration.js';\nimport {Ray} from '../../util/primitives.js';\nimport assert from 'assert';\nimport {latFromMercatorY, mercatorZfromAltitude} from '../../geo/mercator_coordinate.js';\nimport EXTENT from '../../data/extent.js';\n\nimport type {FeatureState} from '../../style-spec/expression/index.js';\nimport type Transform from '../../geo/transform.js';\nimport type {Bucket, BucketParameters} from '../../data/bucket.js';\nimport type {LayoutProps, PaintProps} from './circle_style_layer_properties.js';\nimport type {LayerSpecification} from '../../style-spec/types.js';\nimport type {TilespaceQueryGeometry} from '../query_geometry.js';\nimport type {DEMSampler} from '../../terrain/elevation.js';\nimport type {IVectorTileFeature} from '@mapbox/vector-tile';\n\nclass CircleStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout<LayoutProps>;\n layout: PossiblyEvaluated<LayoutProps>;\n\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n createBucket(parameters: BucketParameters<CircleStyleLayer>): CircleBucket<CircleStyleLayer> {\n return new CircleBucket(parameters);\n }\n\n // $FlowFixMe[method-unbinding]\n queryRadius(bucket: Bucket): number {\n const circleBucket: CircleBucket<CircleStyleLayer> = (bucket: any);\n return getMaximumPaintValue('circle-radius', this, circleBucket) +\n getMaximumPaintValue('circle-stroke-width', this, circleBucket) +\n translateDistance(this.paint.get('circle-translate'));\n }\n\n // $FlowFixMe[method-unbinding]\n queryIntersectsFeature(queryGeometry: TilespaceQueryGeometry,\n feature: IVectorTileFeature,\n featureState: FeatureState,\n geometry: Array<Array<Point>>,\n zoom: number,\n transform: Transform,\n pixelPosMatrix: Float32Array,\n elevationHelper: ?DEMSampler): boolean {\n\n const translation = tilespaceTranslate(\n this.paint.get('circle-translate'),\n this.paint.get('circle-translate-anchor'),\n transform.angle, queryGeometry.pixelToTileUnitsFactor);\n\n const size = this.paint.get('circle-radius').evaluate(feature, featureState) +\n this.paint.get('circle-stroke-width').evaluate(feature, featureState);\n\n return queryIntersectsCircle(queryGeometry, geometry, transform, pixelPosMatrix, elevationHelper,\n this.paint.get('circle-pitch-alignment') === 'map',\n this.paint.get('circle-pitch-scale') === 'map', translation, size);\n }\n\n getProgramIds(): Array<string> {\n return ['circle'];\n }\n\n getProgramConfiguration(zoom: number): ProgramConfiguration {\n return new ProgramConfiguration(this, zoom);\n }\n}\n\nexport function queryIntersectsCircle(queryGeometry: TilespaceQueryGeometry,\n geometry: Array<Array<Point>>,\n transform: Transform,\n pixelPosMatrix: Float32Array,\n elevationHelper: ?DEMSampler,\n alignWithMap: boolean,\n scaleWithMap: boolean,\n translation: Point,\n size: number): boolean {\n if (alignWithMap && queryGeometry.queryGeometry.isAboveHorizon) return false;\n\n // For pitch-alignment: map, compare feature geometry to query geometry in the plane of the tile\n // // Otherwise, compare geometry in the plane of the viewport\n // // A circle with fixed scaling relative to the viewport gets larger in tile space as it moves into the distance\n // // A circle with fixed scaling relative to the map gets smaller in viewport space as it moves into the distance\n if (alignWithMap) size *= queryGeometry.pixelToTileUnitsFactor;\n\n const tileId = queryGeometry.tileID.canonical;\n const elevationScale = transform.projection.upVectorScale(tileId, transform.center.lat, transform.worldSize).metersToTile;\n\n for (const ring of geometry) {\n for (const point of ring) {\n const translatedPoint = point.add(translation);\n const z = (elevationHelper && transform.elevation) ?\n transform.elevation.exaggeration() * elevationHelper.getElevationAt(translatedPoint.x, translatedPoint.y, true) :\n 0;\n\n // Reproject tile coordinate to the local coordinate space used by the projection\n const reproj = transform.projection.projectTilePoint(translatedPoint.x, translatedPoint.y, tileId);\n\n if (z > 0) {\n const dir = transform.projection.upVector(tileId, translatedPoint.x, translatedPoint.y);\n reproj.x += dir[0] * elevationScale * z;\n reproj.y += dir[1] * elevationScale * z;\n reproj.z += dir[2] * elevationScale * z;\n }\n\n const transformedPoint = alignWithMap ? translatedPoint : projectPoint(reproj.x, reproj.y, reproj.z, pixelPosMatrix);\n const transformedPolygon = alignWithMap ?\n queryGeometry.tilespaceRays.map((r) => intersectAtHeight(r, z)) :\n queryGeometry.queryGeometry.screenGeometry;\n\n const projectedCenter = vec4.transformMat4([], [reproj.x, reproj.y, reproj.z, 1], pixelPosMatrix);\n if (!scaleWithMap && alignWithMap) {\n size *= projectedCenter[3] / transform.cameraToCenterDistance;\n } else if (scaleWithMap && !alignWithMap) {\n size *= transform.cameraToCenterDistance / projectedCenter[3];\n }\n\n if (alignWithMap) {\n // Apply extra scaling to cover different pixelPerMeter ratios at different latitudes\n const lat = latFromMercatorY((point.y / EXTENT + tileId.y) / (1 << tileId.z));\n const scale = transform.projection.pixelsPerMeter(lat, 1) / mercatorZfromAltitude(1, lat);\n\n size /= scale;\n }\n\n if (polygonIntersectsBufferedPoint(transformedPolygon, transformedPoint, size)) return true;\n }\n }\n\n return false;\n}\n\nfunction projectPoint(x: number, y: number, z: number, pixelPosMatrix: Float32Array) {\n const point = vec4.transformMat4([], [x, y, z, 1], pixelPosMatrix);\n return new Point(point[0] / point[3], point[1] / point[3]);\n}\n\nconst origin = vec3.fromValues(0, 0, 0);\nconst up = vec3.fromValues(0, 0, 1);\n\nfunction intersectAtHeight(r: Ray, z: number): Point {\n const intersectionPt = vec3.create();\n origin[2] = z;\n const intersects = r.intersectsPlane(origin, up, intersectionPt);\n assert(intersects, 'tilespacePoint should always be below horizon, and since camera cannot have pitch >90, ray should always intersect');\n\n return new Point(intersectionPt[0], intersectionPt[1]);\n}\n\nexport default CircleStyleLayer;\n","// @flow\n\nimport CircleBucket from './circle_bucket.js';\n\nimport {register} from '../../util/web_worker_transfer.js';\n\nimport type HeatmapStyleLayer from '../../style/style_layer/heatmap_style_layer.js';\n\nclass HeatmapBucket extends CircleBucket<HeatmapStyleLayer> {\n // Needed for flow to accept omit: ['layers'] below, due to\n // https://github.com/facebook/flow/issues/4262\n layers: Array<HeatmapStyleLayer>;\n}\n\nregister(HeatmapBucket, 'HeatmapBucket', {omit: ['layers']});\n\nexport default HeatmapBucket;\n","// @flow\n\nimport assert from 'assert';\n\nimport {register} from './web_worker_transfer.js';\n\nexport type Size = interface {\n width: number,\n height: number,\n};\n\nexport interface SpritePosition {\n +tl: [number, number],\n +br: [number, number],\n +pixelRatio?: number\n}\nexport type SpritePositions = {[_: string]: SpritePosition};\n\ntype Point = {\n x: number,\n y: number\n};\n\nfunction createImage<T: AlphaImage | RGBAImage>(image: T, {width, height}: Size, channels: number, data?: Uint8Array | Uint8ClampedArray): T {\n if (!data) {\n data = new Uint8Array(width * height * channels);\n } else if (data instanceof Uint8ClampedArray) {\n data = new Uint8Array(data.buffer);\n } else if (data.length !== width * height * channels) {\n throw new RangeError('mismatched image size');\n }\n image.width = width;\n image.height = height;\n image.data = data;\n return image;\n}\n\nfunction resizeImage<T: AlphaImage | RGBAImage>(image: T, newImage: T, channels: number) {\n const {width, height} = newImage;\n if (width === image.width && height === image.height) {\n return;\n }\n\n copyImage(image, newImage, {x: 0, y: 0}, {x: 0, y: 0}, {\n width: Math.min(image.width, width),\n height: Math.min(image.height, height)\n }, channels);\n\n image.width = width;\n image.height = height;\n image.data = newImage.data;\n}\n\nfunction copyImage<T: RGBAImage | AlphaImage>(srcImg: T | ImageData, dstImg: T, srcPt: Point, dstPt: Point, size: Size, channels: number): T {\n if (size.width === 0 || size.height === 0) {\n return dstImg;\n }\n\n if (size.width > srcImg.width ||\n size.height > srcImg.height ||\n srcPt.x > srcImg.width - size.width ||\n srcPt.y > srcImg.height - size.height) {\n throw new RangeError('out of range source coordinates for image copy');\n }\n\n if (size.width > dstImg.width ||\n size.height > dstImg.height ||\n dstPt.x > dstImg.width - size.width ||\n dstPt.y > dstImg.height - size.height) {\n throw new RangeError('out of range destination coordinates for image copy');\n }\n\n const srcData = srcImg.data;\n const dstData = dstImg.data;\n\n assert(srcData !== dstData);\n\n for (let y = 0; y < size.height; y++) {\n const srcOffset = ((srcPt.y + y) * srcImg.width + srcPt.x) * channels;\n const dstOffset = ((dstPt.y + y) * dstImg.width + dstPt.x) * channels;\n for (let i = 0; i < size.width * channels; i++) {\n dstData[dstOffset + i] = srcData[srcOffset + i];\n }\n }\n return dstImg;\n}\n\nexport class AlphaImage {\n width: number;\n height: number;\n data: Uint8Array;\n\n constructor(size: Size, data?: Uint8Array | Uint8ClampedArray) {\n createImage(this, size, 1, data);\n }\n\n resize(size: Size) {\n resizeImage(this, new AlphaImage(size), 1);\n }\n\n clone(): AlphaImage {\n return new AlphaImage({width: this.width, height: this.height}, new Uint8Array(this.data));\n }\n\n static copy(srcImg: AlphaImage, dstImg: AlphaImage, srcPt: Point, dstPt: Point, size: Size) {\n copyImage(srcImg, dstImg, srcPt, dstPt, size, 1);\n }\n}\n\n// Not premultiplied, because ImageData is not premultiplied.\n// UNPACK_PREMULTIPLY_ALPHA_WEBGL must be used when uploading to a texture.\nexport class RGBAImage {\n width: number;\n height: number;\n\n // data must be a Uint8Array instead of Uint8ClampedArray because texImage2D does not\n // support Uint8ClampedArray in all browsers\n data: Uint8Array;\n\n constructor(size: Size, data?: Uint8Array | Uint8ClampedArray) {\n createImage(this, size, 4, data);\n }\n\n resize(size: Size) {\n resizeImage(this, new RGBAImage(size), 4);\n }\n\n replace(data: Uint8Array | Uint8ClampedArray, copy?: boolean) {\n if (copy) {\n this.data.set(data);\n } else if (data instanceof Uint8ClampedArray) {\n this.data = new Uint8Array(data.buffer);\n } else {\n this.data = data;\n }\n }\n\n clone(): RGBAImage {\n return new RGBAImage({width: this.width, height: this.height}, new Uint8Array(this.data));\n }\n\n static copy(srcImg: RGBAImage | ImageData, dstImg: RGBAImage, srcPt: Point, dstPt: Point, size: Size) {\n copyImage(srcImg, dstImg, srcPt, dstPt, size, 4);\n }\n}\n\nregister(AlphaImage, 'AlphaImage');\nregister(RGBAImage, 'RGBAImage');\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest.js';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n ColorRampProperty\n} from '../properties.js';\n\nimport type Color from '../../style-spec/util/color.js';\n\nimport type Formatted from '../../style-spec/expression/types/formatted.js';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image.js';\n\n\nexport type PaintProps = {|\n \"heatmap-radius\": DataDrivenProperty<number>,\n \"heatmap-weight\": DataDrivenProperty<number>,\n \"heatmap-intensity\": DataConstantProperty<number>,\n \"heatmap-color\": ColorRampProperty,\n \"heatmap-opacity\": DataConstantProperty<number>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"heatmap-radius\": new DataDrivenProperty(styleSpec[\"paint_heatmap\"][\"heatmap-radius\"]),\n \"heatmap-weight\": new DataDrivenProperty(styleSpec[\"paint_heatmap\"][\"heatmap-weight\"]),\n \"heatmap-intensity\": new DataConstantProperty(styleSpec[\"paint_heatmap\"][\"heatmap-intensity\"]),\n \"heatmap-color\": new ColorRampProperty(styleSpec[\"paint_heatmap\"][\"heatmap-color\"]),\n \"heatmap-opacity\": new DataConstantProperty(styleSpec[\"paint_heatmap\"][\"heatmap-opacity\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint }: $Exact<{\n paint: Properties<PaintProps>\n}>);\n","// @flow\n\nimport {RGBAImage} from './image.js';\nimport {isPowerOfTwo} from './util.js';\nimport assert from 'assert';\n\nimport type {StylePropertyExpression} from '../style-spec/expression/index.js';\n\nexport type ColorRampParams = {\n expression: StylePropertyExpression;\n evaluationKey: string;\n resolution?: number;\n image?: RGBAImage;\n clips?: Array<Object>;\n}\n\n/**\n * Given an expression that should evaluate to a color ramp,\n * return a RGBA image representing that ramp expression.\n *\n * @private\n */\nexport function renderColorRamp(params: ColorRampParams): RGBAImage {\n const evaluationGlobals = {};\n const width = params.resolution || 256;\n const height = params.clips ? params.clips.length : 1;\n const image = params.image || new RGBAImage({width, height});\n\n assert(isPowerOfTwo(width));\n\n const renderPixel = (stride: number, index: number, progress: number) => {\n evaluationGlobals[params.evaluationKey] = progress;\n const pxColor = params.expression.evaluate((evaluationGlobals: any));\n // the colors are being unpremultiplied because Color uses\n // premultiplied values, and the Texture class expects unpremultiplied ones\n image.data[stride + index + 0] = Math.floor(pxColor.r * 255 / pxColor.a);\n image.data[stride + index + 1] = Math.floor(pxColor.g * 255 / pxColor.a);\n image.data[stride + index + 2] = Math.floor(pxColor.b * 255 / pxColor.a);\n image.data[stride + index + 3] = Math.floor(pxColor.a * 255);\n };\n\n if (!params.clips) {\n for (let i = 0, j = 0; i < width; i++, j += 4) {\n const progress = i / (width - 1);\n\n renderPixel(0, j, progress);\n }\n } else {\n for (let clip = 0, stride = 0; clip < height; ++clip, stride += width * 4) {\n for (let i = 0, j = 0; i < width; i++, j += 4) {\n // Remap progress between clips\n const progress = i / (width - 1);\n const {start, end} = params.clips[clip];\n const evaluationProgress = start * (1 - progress) + end * progress;\n renderPixel(stride, j, evaluationProgress);\n }\n }\n }\n\n return image;\n}\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest.js';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n ColorRampProperty\n} from '../properties.js';\n\nimport type Color from '../../style-spec/util/color.js';\n\nimport type Formatted from '../../style-spec/expression/types/formatted.js';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image.js';\n\n\nexport type PaintProps = {|\n \"hillshade-illumination-direction\": DataConstantProperty<number>,\n \"hillshade-illumination-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"hillshade-exaggeration\": DataConstantProperty<number>,\n \"hillshade-shadow-color\": DataConstantProperty<Color>,\n \"hillshade-highlight-color\": DataConstantProperty<Color>,\n \"hillshade-accent-color\": DataConstantProperty<Color>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"hillshade-illumination-direction\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-illumination-direction\"]),\n \"hillshade-illumination-anchor\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-illumination-anchor\"]),\n \"hillshade-exaggeration\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-exaggeration\"]),\n \"hillshade-shadow-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-shadow-color\"]),\n \"hillshade-highlight-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-highlight-color\"]),\n \"hillshade-accent-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-accent-color\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint }: $Exact<{\n paint: Properties<PaintProps>\n}>);\n","// @flow\nimport {createLayout} from '../../util/struct_array.js';\n\nimport type {StructArrayLayout} from '../../util/struct_array.js';\n\nconst layout: StructArrayLayout = createLayout([\n {name: 'a_pos', components: 2, type: 'Int16'}\n], 4);\n\nexport default layout;\nexport const {members, size, alignment} = layout;\n","'use strict';\n\nmodule.exports = earcut;\nmodule.exports.default = earcut;\n\nfunction earcut(data, holeIndices, dim) {\n\n dim = dim || 2;\n\n var hasHoles = holeIndices && holeIndices.length,\n outerLen = hasHoles ? holeIndices[0] * dim : data.length,\n outerNode = linkedList(data, 0, outerLen, dim, true),\n triangles = [];\n\n if (!outerNode || outerNode.next === outerNode.prev) return triangles;\n\n var minX, minY, maxX, maxY, x, y, invSize;\n\n if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);\n\n // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox\n if (data.length > 80 * dim) {\n minX = maxX = data[0];\n minY = maxY = data[1];\n\n for (var i = dim; i < outerLen; i += dim) {\n x = data[i];\n y = data[i + 1];\n if (x < minX) minX = x;\n if (y < minY) minY = y;\n if (x > maxX) maxX = x;\n if (y > maxY) maxY = y;\n }\n\n // minX, minY and invSize are later used to transform coords into integers for z-order calculation\n invSize = Math.max(maxX - minX, maxY - minY);\n invSize = invSize !== 0 ? 32767 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);\n\n return triangles;\n}\n\n// create a circular doubly linked list from polygon points in the specified winding order\nfunction linkedList(data, start, end, dim, clockwise) {\n var i, last;\n\n if (clockwise === (signedArea(data, start, end, dim) > 0)) {\n for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);\n } else {\n for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);\n }\n\n if (last && equals(last, last.next)) {\n removeNode(last);\n last = last.next;\n }\n\n return last;\n}\n\n// eliminate colinear or duplicate points\nfunction filterPoints(start, end) {\n if (!start) return start;\n if (!end) end = start;\n\n var p = start,\n again;\n do {\n again = false;\n\n if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {\n removeNode(p);\n p = end = p.prev;\n if (p === p.next) break;\n again = true;\n\n } else {\n p = p.next;\n }\n } while (again || p !== end);\n\n return end;\n}\n\n// main ear slicing loop which triangulates a polygon (given as a linked list)\nfunction earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {\n if (!ear) return;\n\n // interlink polygon nodes in z-order\n if (!pass && invSize) indexCurve(ear, minX, minY, invSize);\n\n var stop = ear,\n prev, next;\n\n // iterate through ears, slicing them one by one\n while (ear.prev !== ear.next) {\n prev = ear.prev;\n next = ear.next;\n\n if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {\n // cut off the triangle\n triangles.push(prev.i / dim | 0);\n triangles.push(ear.i / dim | 0);\n triangles.push(next.i / dim | 0);\n\n removeNode(ear);\n\n // skipping the next vertex leads to less sliver triangles\n ear = next.next;\n stop = next.next;\n\n continue;\n }\n\n ear = next;\n\n // if we looped through the whole remaining polygon and can't find any more ears\n if (ear === stop) {\n // try filtering points and slicing again\n if (!pass) {\n earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);\n\n // if this didn't work, try curing all small self-intersections locally\n } else if (pass === 1) {\n ear = cureLocalIntersections(filterPoints(ear), triangles, dim);\n earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);\n\n // as a last resort, try splitting the remaining polygon into two\n } else if (pass === 2) {\n splitEarcut(ear, triangles, dim, minX, minY, invSize);\n }\n\n break;\n }\n }\n}\n\n// check whether a polygon node forms a valid ear with adjacent nodes\nfunction isEar(ear) {\n var a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n // now make sure we don't have other points inside the potential ear\n var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox; min & max are calculated like this for speed\n var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx),\n y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy),\n x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx),\n y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy);\n\n var p = c.next;\n while (p !== a) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&\n pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.next;\n }\n\n return true;\n}\n\nfunction isEarHashed(ear, minX, minY, invSize) {\n var a = ear.prev,\n b = ear,\n c = ear.next;\n\n if (area(a, b, c) >= 0) return false; // reflex, can't be an ear\n\n var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;\n\n // triangle bbox; min & max are calculated like this for speed\n var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx),\n y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy),\n x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx),\n y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy);\n\n // z-order range for the current triangle bbox;\n var minZ = zOrder(x0, y0, minX, minY, invSize),\n maxZ = zOrder(x1, y1, minX, minY, invSize);\n\n var p = ear.prevZ,\n n = ear.nextZ;\n\n // look for points inside the triangle in both directions\n while (p && p.z >= minZ && n && n.z <= maxZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n // look for remaining points in decreasing z-order\n while (p && p.z >= minZ) {\n if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&\n pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n }\n\n // look for remaining points in increasing z-order\n while (n && n.z <= maxZ) {\n if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&\n pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false;\n n = n.nextZ;\n }\n\n return true;\n}\n\n// go through all polygon nodes and cure small local self-intersections\nfunction cureLocalIntersections(start, triangles, dim) {\n var p = start;\n do {\n var a = p.prev,\n b = p.next.next;\n\n if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {\n\n triangles.push(a.i / dim | 0);\n triangles.push(p.i / dim | 0);\n triangles.push(b.i / dim | 0);\n\n // remove two nodes involved\n removeNode(p);\n removeNode(p.next);\n\n p = start = b;\n }\n p = p.next;\n } while (p !== start);\n\n return filterPoints(p);\n}\n\n// try splitting polygon into two and triangulate them independently\nfunction splitEarcut(start, triangles, dim, minX, minY, invSize) {\n // look for a valid diagonal that divides the polygon into two\n var a = start;\n do {\n var b = a.next.next;\n while (b !== a.prev) {\n if (a.i !== b.i && isValidDiagonal(a, b)) {\n // split the polygon in two by the diagonal\n var c = splitPolygon(a, b);\n\n // filter colinear points around the cuts\n a = filterPoints(a, a.next);\n c = filterPoints(c, c.next);\n\n // run earcut on each half\n earcutLinked(a, triangles, dim, minX, minY, invSize, 0);\n earcutLinked(c, triangles, dim, minX, minY, invSize, 0);\n return;\n }\n b = b.next;\n }\n a = a.next;\n } while (a !== start);\n}\n\n// link every hole into the outer loop, producing a single-ring polygon without holes\nfunction eliminateHoles(data, holeIndices, outerNode, dim) {\n var queue = [],\n i, len, start, end, list;\n\n for (i = 0, len = holeIndices.length; i < len; i++) {\n start = holeIndices[i] * dim;\n end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n list = linkedList(data, start, end, dim, false);\n if (list === list.next) list.steiner = true;\n queue.push(getLeftmost(list));\n }\n\n queue.sort(compareX);\n\n // process holes from left to right\n for (i = 0; i < queue.length; i++) {\n outerNode = eliminateHole(queue[i], outerNode);\n }\n\n return outerNode;\n}\n\nfunction compareX(a, b) {\n return a.x - b.x;\n}\n\n// find a bridge between vertices that connects hole with an outer ring and and link it\nfunction eliminateHole(hole, outerNode) {\n var bridge = findHoleBridge(hole, outerNode);\n if (!bridge) {\n return outerNode;\n }\n\n var bridgeReverse = splitPolygon(bridge, hole);\n\n // filter collinear points around the cuts\n filterPoints(bridgeReverse, bridgeReverse.next);\n return filterPoints(bridge, bridge.next);\n}\n\n// David Eberly's algorithm for finding a bridge between hole and outer polygon\nfunction findHoleBridge(hole, outerNode) {\n var p = outerNode,\n hx = hole.x,\n hy = hole.y,\n qx = -Infinity,\n m;\n\n // find a segment intersected by a ray from the hole's leftmost point to the left;\n // segment's endpoint with lesser x will be potential connection point\n do {\n if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {\n var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);\n if (x <= hx && x > qx) {\n qx = x;\n m = p.x < p.next.x ? p : p.next;\n if (x === hx) return m; // hole touches outer segment; pick leftmost endpoint\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n // look for points inside the triangle of hole point, segment intersection and endpoint;\n // if there are no points found, we have a valid connection;\n // otherwise choose the point of the minimum angle with the ray as connection point\n\n var stop = m,\n mx = m.x,\n my = m.y,\n tanMin = Infinity,\n tan;\n\n p = m;\n\n do {\n if (hx >= p.x && p.x >= mx && hx !== p.x &&\n pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {\n\n tan = Math.abs(hy - p.y) / (hx - p.x); // tangential\n\n if (locallyInside(p, hole) &&\n (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {\n m = p;\n tanMin = tan;\n }\n }\n\n p = p.next;\n } while (p !== stop);\n\n return m;\n}\n\n// whether sector in vertex m contains sector in vertex p in the same coordinates\nfunction sectorContainsSector(m, p) {\n return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;\n}\n\n// interlink polygon nodes in z-order\nfunction indexCurve(start, minX, minY, invSize) {\n var p = start;\n do {\n if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize);\n p.prevZ = p.prev;\n p.nextZ = p.next;\n p = p.next;\n } while (p !== start);\n\n p.prevZ.nextZ = null;\n p.prevZ = null;\n\n sortLinked(p);\n}\n\n// Simon Tatham's linked list merge sort algorithm\n// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html\nfunction sortLinked(list) {\n var i, p, q, e, tail, numMerges, pSize, qSize,\n inSize = 1;\n\n do {\n p = list;\n list = null;\n tail = null;\n numMerges = 0;\n\n while (p) {\n numMerges++;\n q = p;\n pSize = 0;\n for (i = 0; i < inSize; i++) {\n pSize++;\n q = q.nextZ;\n if (!q) break;\n }\n qSize = inSize;\n\n while (pSize > 0 || (qSize > 0 && q)) {\n\n if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {\n e = p;\n p = p.nextZ;\n pSize--;\n } else {\n e = q;\n q = q.nextZ;\n qSize--;\n }\n\n if (tail) tail.nextZ = e;\n else list = e;\n\n e.prevZ = tail;\n tail = e;\n }\n\n p = q;\n }\n\n tail.nextZ = null;\n inSize *= 2;\n\n } while (numMerges > 1);\n\n return list;\n}\n\n// z-order of a point given coords and inverse of the longer side of data bbox\nfunction zOrder(x, y, minX, minY, invSize) {\n // coords are transformed into non-negative 15-bit integer range\n x = (x - minX) * invSize | 0;\n y = (y - minY) * invSize | 0;\n\n x = (x | (x << 8)) & 0x00FF00FF;\n x = (x | (x << 4)) & 0x0F0F0F0F;\n x = (x | (x << 2)) & 0x33333333;\n x = (x | (x << 1)) & 0x55555555;\n\n y = (y | (y << 8)) & 0x00FF00FF;\n y = (y | (y << 4)) & 0x0F0F0F0F;\n y = (y | (y << 2)) & 0x33333333;\n y = (y | (y << 1)) & 0x55555555;\n\n return x | (y << 1);\n}\n\n// find the leftmost node of a polygon ring\nfunction getLeftmost(start) {\n var p = start,\n leftmost = start;\n do {\n if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) leftmost = p;\n p = p.next;\n } while (p !== start);\n\n return leftmost;\n}\n\n// check if a point lies within a convex triangle\nfunction pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {\n return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&\n (ax - px) * (by - py) >= (bx - px) * (ay - py) &&\n (bx - px) * (cy - py) >= (cx - px) * (by - py);\n}\n\n// check if a diagonal between two polygon nodes is valid (lies in polygon interior)\nfunction isValidDiagonal(a, b) {\n return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges\n (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible\n (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors\n equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case\n}\n\n// signed area of a triangle\nfunction area(p, q, r) {\n return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);\n}\n\n// check if two points are equal\nfunction equals(p1, p2) {\n return p1.x === p2.x && p1.y === p2.y;\n}\n\n// check if two segments intersect\nfunction intersects(p1, q1, p2, q2) {\n var o1 = sign(area(p1, q1, p2));\n var o2 = sign(area(p1, q1, q2));\n var o3 = sign(area(p2, q2, p1));\n var o4 = sign(area(p2, q2, q1));\n\n if (o1 !== o2 && o3 !== o4) return true; // general case\n\n if (o1 === 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and p2 are collinear and p2 lies on p1q1\n if (o2 === 0 && onSegment(p1, q2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on p1q1\n if (o3 === 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and p1 are collinear and p1 lies on p2q2\n if (o4 === 0 && onSegment(p2, q1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on p2q2\n\n return false;\n}\n\n// for collinear points p, q, r, check if point q lies on segment pr\nfunction onSegment(p, q, r) {\n return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);\n}\n\nfunction sign(num) {\n return num > 0 ? 1 : num < 0 ? -1 : 0;\n}\n\n// check if a polygon diagonal intersects any polygon segments\nfunction intersectsPolygon(a, b) {\n var p = a;\n do {\n if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&\n intersects(p, p.next, a, b)) return true;\n p = p.next;\n } while (p !== a);\n\n return false;\n}\n\n// check if a polygon diagonal is locally inside the polygon\nfunction locallyInside(a, b) {\n return area(a.prev, a, a.next) < 0 ?\n area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :\n area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;\n}\n\n// check if the middle point of a polygon diagonal is inside the polygon\nfunction middleInside(a, b) {\n var p = a,\n inside = false,\n px = (a.x + b.x) / 2,\n py = (a.y + b.y) / 2;\n do {\n if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&\n (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))\n inside = !inside;\n p = p.next;\n } while (p !== a);\n\n return inside;\n}\n\n// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;\n// if one belongs to the outer ring and another to a hole, it merges it into a single ring\nfunction splitPolygon(a, b) {\n var a2 = new Node(a.i, a.x, a.y),\n b2 = new Node(b.i, b.x, b.y),\n an = a.next,\n bp = b.prev;\n\n a.next = b;\n b.prev = a;\n\n a2.next = an;\n an.prev = a2;\n\n b2.next = a2;\n a2.prev = b2;\n\n bp.next = b2;\n b2.prev = bp;\n\n return b2;\n}\n\n// create a node and optionally link it with previous one (in a circular doubly linked list)\nfunction insertNode(i, x, y, last) {\n var p = new Node(i, x, y);\n\n if (!last) {\n p.prev = p;\n p.next = p;\n\n } else {\n p.next = last.next;\n p.prev = last;\n last.next.prev = p;\n last.next = p;\n }\n return p;\n}\n\nfunction removeNode(p) {\n p.next.prev = p.prev;\n p.prev.next = p.next;\n\n if (p.prevZ) p.prevZ.nextZ = p.nextZ;\n if (p.nextZ) p.nextZ.prevZ = p.prevZ;\n}\n\nfunction Node(i, x, y) {\n // vertex index in coordinates array\n this.i = i;\n\n // vertex coordinates\n this.x = x;\n this.y = y;\n\n // previous and next vertex nodes in a polygon ring\n this.prev = null;\n this.next = null;\n\n // z-order curve value\n this.z = 0;\n\n // previous and next nodes in z-order\n this.prevZ = null;\n this.nextZ = null;\n\n // indicates whether this is a steiner point\n this.steiner = false;\n}\n\n// return a percentage difference between the polygon area and its triangulation area;\n// used to verify correctness of triangulation\nearcut.deviation = function (data, holeIndices, dim, triangles) {\n var hasHoles = holeIndices && holeIndices.length;\n var outerLen = hasHoles ? holeIndices[0] * dim : data.length;\n\n var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));\n if (hasHoles) {\n for (var i = 0, len = holeIndices.length; i < len; i++) {\n var start = holeIndices[i] * dim;\n var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;\n polygonArea -= Math.abs(signedArea(data, start, end, dim));\n }\n }\n\n var trianglesArea = 0;\n for (i = 0; i < triangles.length; i += 3) {\n var a = triangles[i] * dim;\n var b = triangles[i + 1] * dim;\n var c = triangles[i + 2] * dim;\n trianglesArea += Math.abs(\n (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -\n (data[a] - data[b]) * (data[c + 1] - data[a + 1]));\n }\n\n return polygonArea === 0 && trianglesArea === 0 ? 0 :\n Math.abs((trianglesArea - polygonArea) / polygonArea);\n};\n\nfunction signedArea(data, start, end, dim) {\n var sum = 0;\n for (var i = start, j = end - dim; i < end; i += dim) {\n sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);\n j = i;\n }\n return sum;\n}\n\n// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts\nearcut.flatten = function (data) {\n var dim = data[0][0].length,\n result = {vertices: [], holes: [], dimensions: dim},\n holeIndex = 0;\n\n for (var i = 0; i < data.length; i++) {\n for (var j = 0; j < data[i].length; j++) {\n for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);\n }\n if (i > 0) {\n holeIndex += data[i - 1].length;\n result.holes.push(holeIndex);\n }\n }\n return result;\n};\n","\nexport default function quickselect(arr, k, left, right, compare) {\n quickselectStep(arr, k, left || 0, right || (arr.length - 1), compare || defaultCompare);\n}\n\nfunction quickselectStep(arr, k, left, right, compare) {\n\n while (right > left) {\n if (right - left > 600) {\n var n = right - left + 1;\n var m = k - left + 1;\n var z = Math.log(n);\n var s = 0.5 * Math.exp(2 * z / 3);\n var sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n var newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n var newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n quickselectStep(arr, k, newLeft, newRight, compare);\n }\n\n var t = arr[k];\n var i = left;\n var j = right;\n\n swap(arr, left, k);\n if (compare(arr[right], t) > 0) swap(arr, left, right);\n\n while (i < j) {\n swap(arr, i, j);\n i++;\n j--;\n while (compare(arr[i], t) < 0) i++;\n while (compare(arr[j], t) > 0) j--;\n }\n\n if (compare(arr[left], t) === 0) swap(arr, left, j);\n else {\n j++;\n swap(arr, j, right);\n }\n\n if (j <= k) left = j + 1;\n if (k <= j) right = j - 1;\n }\n}\n\nfunction swap(arr, i, j) {\n var tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n\nfunction defaultCompare(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","// @flow\n\nimport quickselect from 'quickselect';\n\nimport {calculateSignedArea} from './util.js';\n\nimport type Point from '@mapbox/point-geometry';\n\n// classifies an array of rings into polygons with outer rings and holes\nexport default function classifyRings(rings: Array<Array<Point>>, maxRings: number): Array<Array<Array<Point>>> {\n const len = rings.length;\n\n if (len <= 1) return [rings];\n\n const polygons = [];\n let polygon,\n ccw;\n\n for (let i = 0; i < len; i++) {\n const area = calculateSignedArea(rings[i]);\n if (area === 0) continue;\n\n (rings[i]: any).area = Math.abs(area);\n\n if (ccw === undefined) ccw = area < 0;\n\n if (ccw === area < 0) {\n if (polygon) polygons.push(polygon);\n polygon = [rings[i]];\n\n } else {\n (polygon: any).push(rings[i]);\n }\n }\n if (polygon) polygons.push(polygon);\n\n // Earcut performance degrades with the # of rings in a polygon. For this\n // reason, we limit strip out all but the `maxRings` largest rings.\n if (maxRings > 1) {\n for (let j = 0; j < polygons.length; j++) {\n if (polygons[j].length <= maxRings) continue;\n quickselect(polygons[j], maxRings, 1, polygons[j].length - 1, compareAreas);\n polygons[j] = polygons[j].slice(0, maxRings);\n }\n }\n\n return polygons;\n}\n\nfunction compareAreas(a: {area: number}, b: {area: number}) {\n return b.area - a.area;\n}\n","// @flow\nimport type FillStyleLayer from '../../style/style_layer/fill_style_layer.js';\nimport type FillExtrusionStyleLayer from '../../style/style_layer/fill_extrusion_style_layer.js';\nimport type LineStyleLayer from '../../style/style_layer/line_style_layer.js';\n\nimport type {\n BucketFeature,\n PopulateParameters\n} from '../bucket.js';\n\ntype PatternStyleLayers =\n Array<LineStyleLayer> |\n Array<FillStyleLayer> |\n Array<FillExtrusionStyleLayer>;\n\nexport function hasPattern(type: string, layers: PatternStyleLayers, options: PopulateParameters): boolean {\n const patterns = options.patternDependencies;\n let hasPattern = false;\n\n for (const layer of layers) {\n const patternProperty = layer.paint.get(`${type}-pattern`);\n if (!patternProperty.isConstant()) {\n hasPattern = true;\n }\n\n const constantPattern = patternProperty.constantOr(null);\n if (constantPattern) {\n hasPattern = true;\n patterns[constantPattern] = true;\n }\n }\n\n return hasPattern;\n}\n\nexport function addPatternDependencies(type: string, layers: PatternStyleLayers, patternFeature: BucketFeature, zoom: number, options: PopulateParameters): BucketFeature {\n const patterns = options.patternDependencies;\n for (const layer of layers) {\n const patternProperty = layer.paint.get(`${type}-pattern`);\n\n const patternPropertyValue = patternProperty.value;\n if (patternPropertyValue.kind !== \"constant\") {\n let pattern = patternPropertyValue.evaluate({zoom}, patternFeature, {}, options.availableImages);\n pattern = pattern && pattern.name ? pattern.name : pattern;\n\n // add to patternDependencies\n patterns[pattern] = true;\n\n // save for layout\n patternFeature.patterns[layer.id] = pattern;\n }\n }\n return patternFeature;\n}\n","// @flow\n\nimport {FillLayoutArray} from '../array_types.js';\n\nimport {members as layoutAttributes} from './fill_attributes.js';\nimport SegmentVector from '../segment.js';\nimport {ProgramConfigurationSet} from '../program_configuration.js';\nimport {LineIndexArray, TriangleIndexArray} from '../index_array_type.js';\nimport earcut from 'earcut';\nimport classifyRings from '../../util/classify_rings.js';\nimport assert from 'assert';\nconst EARCUT_MAX_RINGS = 500;\nimport {register} from '../../util/web_worker_transfer.js';\nimport {hasPattern, addPatternDependencies} from './pattern_bucket_features.js';\nimport loadGeometry from '../load_geometry.js';\nimport toEvaluationFeature from '../evaluation_feature.js';\nimport EvaluationParameters from '../../style/evaluation_parameters.js';\n\nimport type {CanonicalTileID} from '../../source/tile_id.js';\nimport type {\n Bucket,\n BucketParameters,\n BucketFeature,\n IndexedFeature,\n PopulateParameters\n} from '../bucket.js';\nimport type FillStyleLayer from '../../style/style_layer/fill_style_layer.js';\nimport type Context from '../../gl/context.js';\nimport type IndexBuffer from '../../gl/index_buffer.js';\nimport type VertexBuffer from '../../gl/vertex_buffer.js';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureStates} from '../../source/source_state.js';\nimport type {SpritePositions} from '../../util/image.js';\nimport type {ProjectionSpecification} from '../../style-spec/types.js';\nimport type {TileTransform} from '../../geo/projection/tile_transform.js';\nimport type {IVectorTileLayer} from '@mapbox/vector-tile';\n\nclass FillBucket implements Bucket {\n index: number;\n zoom: number;\n overscaling: number;\n layers: Array<FillStyleLayer>;\n layerIds: Array<string>;\n stateDependentLayers: Array<FillStyleLayer>;\n stateDependentLayerIds: Array<string>;\n patternFeatures: Array<BucketFeature>;\n\n layoutVertexArray: FillLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n indexArray2: LineIndexArray;\n indexBuffer2: IndexBuffer;\n\n hasPattern: boolean;\n programConfigurations: ProgramConfigurationSet<FillStyleLayer>;\n segments: SegmentVector;\n segments2: SegmentVector;\n uploaded: boolean;\n projection: ProjectionSpecification;\n\n constructor(options: BucketParameters<FillStyleLayer>) {\n this.zoom = options.zoom;\n this.overscaling = options.overscaling;\n this.layers = options.layers;\n this.layerIds = this.layers.map(layer => layer.id);\n this.index = options.index;\n this.hasPattern = false;\n this.patternFeatures = [];\n\n this.layoutVertexArray = new FillLayoutArray();\n this.indexArray = new TriangleIndexArray();\n this.indexArray2 = new LineIndexArray();\n this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n this.segments = new SegmentVector();\n this.segments2 = new SegmentVector();\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n this.projection = options.projection;\n }\n\n populate(features: Array<IndexedFeature>, options: PopulateParameters, canonical: CanonicalTileID, tileTransform: TileTransform) {\n this.hasPattern = hasPattern('fill', this.layers, options);\n const fillSortKey = this.layers[0].layout.get('fill-sort-key');\n const bucketFeatures = [];\n\n for (const {feature, id, index, sourceLayerIndex} of features) {\n const needGeometry = this.layers[0]._featureFilter.needGeometry;\n const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n\n // $FlowFixMe[method-unbinding]\n if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) continue;\n\n const sortKey = fillSortKey ?\n fillSortKey.evaluate(evaluationFeature, {}, canonical, options.availableImages) :\n undefined;\n\n const bucketFeature: BucketFeature = {\n id,\n properties: feature.properties,\n type: feature.type,\n sourceLayerIndex,\n index,\n geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature, canonical, tileTransform),\n patterns: {},\n sortKey\n };\n\n bucketFeatures.push(bucketFeature);\n }\n\n if (fillSortKey) {\n bucketFeatures.sort((a, b) => {\n // a.sortKey is always a number when in use\n return ((a.sortKey: any): number) - ((b.sortKey: any): number);\n });\n }\n\n for (const bucketFeature of bucketFeatures) {\n const {geometry, index, sourceLayerIndex} = bucketFeature;\n\n if (this.hasPattern) {\n const patternFeature = addPatternDependencies('fill', this.layers, bucketFeature, this.zoom, options);\n // pattern features are added only once the pattern is loaded into the image atlas\n // so are stored during populate until later updated with positions by tile worker in addFeatures\n this.patternFeatures.push(patternFeature);\n } else {\n this.addFeature(bucketFeature, geometry, index, canonical, {}, options.availableImages);\n }\n\n const feature = features[index].feature;\n options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);\n }\n }\n\n update(states: FeatureStates, vtLayer: IVectorTileLayer, availableImages: Array<string>, imagePositions: SpritePositions) {\n if (!this.stateDependentLayers.length) return;\n this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, availableImages, imagePositions);\n }\n\n addFeatures(options: PopulateParameters, canonical: CanonicalTileID, imagePositions: SpritePositions, availableImages: Array<string>, _: TileTransform) {\n for (const feature of this.patternFeatures) {\n this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions, availableImages);\n }\n }\n\n isEmpty(): boolean {\n return this.layoutVertexArray.length === 0;\n }\n\n uploadPending(): boolean {\n return !this.uploaded || this.programConfigurations.needsUpload;\n }\n upload(context: Context) {\n if (!this.uploaded) {\n this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);\n this.indexBuffer = context.createIndexBuffer(this.indexArray);\n this.indexBuffer2 = context.createIndexBuffer(this.indexArray2);\n }\n this.programConfigurations.upload(context);\n this.uploaded = true;\n }\n\n destroy() {\n if (!this.layoutVertexBuffer) return;\n this.layoutVertexBuffer.destroy();\n this.indexBuffer.destroy();\n this.indexBuffer2.destroy();\n this.programConfigurations.destroy();\n this.segments.destroy();\n this.segments2.destroy();\n }\n\n addFeature(feature: BucketFeature, geometry: Array<Array<Point>>, index: number, canonical: CanonicalTileID, imagePositions: SpritePositions, availableImages: Array<string> = []) {\n for (const polygon of classifyRings(geometry, EARCUT_MAX_RINGS)) {\n let numVertices = 0;\n for (const ring of polygon) {\n numVertices += ring.length;\n }\n\n const triangleSegment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray);\n const triangleIndex = triangleSegment.vertexLength;\n\n const flattened = [];\n const holeIndices = [];\n\n for (const ring of polygon) {\n if (ring.length === 0) {\n continue;\n }\n\n if (ring !== polygon[0]) {\n holeIndices.push(flattened.length / 2);\n }\n\n const lineSegment = this.segments2.prepareSegment(ring.length, this.layoutVertexArray, this.indexArray2);\n const lineIndex = lineSegment.vertexLength;\n\n this.layoutVertexArray.emplaceBack(ring[0].x, ring[0].y);\n this.indexArray2.emplaceBack(lineIndex + ring.length - 1, lineIndex);\n flattened.push(ring[0].x);\n flattened.push(ring[0].y);\n\n for (let i = 1; i < ring.length; i++) {\n this.layoutVertexArray.emplaceBack(ring[i].x, ring[i].y);\n this.indexArray2.emplaceBack(lineIndex + i - 1, lineIndex + i);\n flattened.push(ring[i].x);\n flattened.push(ring[i].y);\n }\n\n lineSegment.vertexLength += ring.length;\n lineSegment.primitiveLength += ring.length;\n }\n\n const indices = earcut(flattened, holeIndices);\n assert(indices.length % 3 === 0);\n\n for (let i = 0; i < indices.length; i += 3) {\n this.indexArray.emplaceBack(\n triangleIndex + indices[i],\n triangleIndex + indices[i + 1],\n triangleIndex + indices[i + 2]);\n }\n\n triangleSegment.vertexLength += numVertices;\n triangleSegment.primitiveLength += indices.length / 3;\n }\n this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, availableImages, canonical);\n }\n}\n\nregister(FillBucket, 'FillBucket', {omit: ['layers', 'patternFeatures']});\n\nexport default FillBucket;\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest.js';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n ColorRampProperty\n} from '../properties.js';\n\nimport type Color from '../../style-spec/util/color.js';\n\nimport type Formatted from '../../style-spec/expression/types/formatted.js';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image.js';\n\nexport type LayoutProps = {|\n \"fill-sort-key\": DataDrivenProperty<number>,\n|};\n\nconst layout: Properties<LayoutProps> = new Properties({\n \"fill-sort-key\": new DataDrivenProperty(styleSpec[\"layout_fill\"][\"fill-sort-key\"]),\n});\n\nexport type PaintProps = {|\n \"fill-antialias\": DataConstantProperty<boolean>,\n \"fill-opacity\": DataDrivenProperty<number>,\n \"fill-color\": DataDrivenProperty<Color>,\n \"fill-outline-color\": DataDrivenProperty<Color>,\n \"fill-translate\": DataConstantProperty<[number, number]>,\n \"fill-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"fill-pattern\": DataDrivenProperty<?ResolvedImage>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"fill-antialias\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-antialias\"]),\n \"fill-opacity\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-opacity\"]),\n \"fill-color\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-color\"]),\n \"fill-outline-color\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-outline-color\"]),\n \"fill-translate\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-translate\"]),\n \"fill-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-translate-anchor\"]),\n \"fill-pattern\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-pattern\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint, layout }: $Exact<{\n paint: Properties<PaintProps>, layout: Properties<LayoutProps>\n}>);\n","// @flow\nimport {createLayout} from '../../util/struct_array.js';\n\nimport type {StructArrayLayout} from '../../util/struct_array.js';\n\nexport const fillExtrusionAttributes: StructArrayLayout = createLayout([\n {name: 'a_pos_normal_ed', components: 4, type: 'Int16'}\n]);\n\nexport const centroidAttributes: StructArrayLayout = createLayout([\n {name: 'a_centroid_pos', components: 2, type: 'Uint16'}\n]);\n\nexport const fillExtrusionAttributesExt: StructArrayLayout = createLayout([\n {name: 'a_pos_3', components: 3, type: 'Int16'},\n {name: 'a_pos_normal_3', components: 3, type: 'Int16'}\n]);\n\nexport const {members, size, alignment} = fillExtrusionAttributes;\n","'use strict';\n\nvar Point = require('@mapbox/point-geometry');\n\nmodule.exports = VectorTileFeature;\n\nfunction VectorTileFeature(pbf, end, extent, keys, values) {\n // Public\n this.properties = {};\n this.extent = extent;\n this.type = 0;\n\n // Private\n this._pbf = pbf;\n this._geometry = -1;\n this._keys = keys;\n this._values = values;\n\n pbf.readFields(readFeature, this, end);\n}\n\nfunction readFeature(tag, feature, pbf) {\n if (tag == 1) feature.id = pbf.readVarint();\n else if (tag == 2) readTag(pbf, feature);\n else if (tag == 3) feature.type = pbf.readVarint();\n else if (tag == 4) feature._geometry = pbf.pos;\n}\n\nfunction readTag(pbf, feature) {\n var end = pbf.readVarint() + pbf.pos;\n\n while (pbf.pos < end) {\n var key = feature._keys[pbf.readVarint()],\n value = feature._values[pbf.readVarint()];\n feature.properties[key] = value;\n }\n}\n\nVectorTileFeature.types = ['Unknown', 'Point', 'LineString', 'Polygon'];\n\nVectorTileFeature.prototype.loadGeometry = function() {\n var pbf = this._pbf;\n pbf.pos = this._geometry;\n\n var end = pbf.readVarint() + pbf.pos,\n cmd = 1,\n length = 0,\n x = 0,\n y = 0,\n lines = [],\n line;\n\n while (pbf.pos < end) {\n if (length <= 0) {\n var cmdLen = pbf.readVarint();\n cmd = cmdLen & 0x7;\n length = cmdLen >> 3;\n }\n\n length--;\n\n if (cmd === 1 || cmd === 2) {\n x += pbf.readSVarint();\n y += pbf.readSVarint();\n\n if (cmd === 1) { // moveTo\n if (line) lines.push(line);\n line = [];\n }\n\n line.push(new Point(x, y));\n\n } else if (cmd === 7) {\n\n // Workaround for https://github.com/mapbox/mapnik-vector-tile/issues/90\n if (line) {\n line.push(line[0].clone()); // closePolygon\n }\n\n } else {\n throw new Error('unknown command ' + cmd);\n }\n }\n\n if (line) lines.push(line);\n\n return lines;\n};\n\nVectorTileFeature.prototype.bbox = function() {\n var pbf = this._pbf;\n pbf.pos = this._geometry;\n\n var end = pbf.readVarint() + pbf.pos,\n cmd = 1,\n length = 0,\n x = 0,\n y = 0,\n x1 = Infinity,\n x2 = -Infinity,\n y1 = Infinity,\n y2 = -Infinity;\n\n while (pbf.pos < end) {\n if (length <= 0) {\n var cmdLen = pbf.readVarint();\n cmd = cmdLen & 0x7;\n length = cmdLen >> 3;\n }\n\n length--;\n\n if (cmd === 1 || cmd === 2) {\n x += pbf.readSVarint();\n y += pbf.readSVarint();\n if (x < x1) x1 = x;\n if (x > x2) x2 = x;\n if (y < y1) y1 = y;\n if (y > y2) y2 = y;\n\n } else if (cmd !== 7) {\n throw new Error('unknown command ' + cmd);\n }\n }\n\n return [x1, y1, x2, y2];\n};\n\nVectorTileFeature.prototype.toGeoJSON = function(x, y, z) {\n var size = this.extent * Math.pow(2, z),\n x0 = this.extent * x,\n y0 = this.extent * y,\n coords = this.loadGeometry(),\n type = VectorTileFeature.types[this.type],\n i, j;\n\n function project(line) {\n for (var j = 0; j < line.length; j++) {\n var p = line[j], y2 = 180 - (p.y + y0) * 360 / size;\n line[j] = [\n (p.x + x0) * 360 / size - 180,\n 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90\n ];\n }\n }\n\n switch (this.type) {\n case 1:\n var points = [];\n for (i = 0; i < coords.length; i++) {\n points[i] = coords[i][0];\n }\n coords = points;\n project(coords);\n break;\n\n case 2:\n for (i = 0; i < coords.length; i++) {\n project(coords[i]);\n }\n break;\n\n case 3:\n coords = classifyRings(coords);\n for (i = 0; i < coords.length; i++) {\n for (j = 0; j < coords[i].length; j++) {\n project(coords[i][j]);\n }\n }\n break;\n }\n\n if (coords.length === 1) {\n coords = coords[0];\n } else {\n type = 'Multi' + type;\n }\n\n var result = {\n type: \"Feature\",\n geometry: {\n type: type,\n coordinates: coords\n },\n properties: this.properties\n };\n\n if ('id' in this) {\n result.id = this.id;\n }\n\n return result;\n};\n\n// classifies an array of rings into polygons with outer rings and holes\n\nfunction classifyRings(rings) {\n var len = rings.length;\n\n if (len <= 1) return [rings];\n\n var polygons = [],\n polygon,\n ccw;\n\n for (var i = 0; i < len; i++) {\n var area = signedArea(rings[i]);\n if (area === 0) continue;\n\n if (ccw === undefined) ccw = area < 0;\n\n if (ccw === area < 0) {\n if (polygon) polygons.push(polygon);\n polygon = [rings[i]];\n\n } else {\n polygon.push(rings[i]);\n }\n }\n if (polygon) polygons.push(polygon);\n\n return polygons;\n}\n\nfunction signedArea(ring) {\n var sum = 0;\n for (var i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) {\n p1 = ring[i];\n p2 = ring[j];\n sum += (p2.x - p1.x) * (p1.y + p2.y);\n }\n return sum;\n}\n","'use strict';\n\nvar VectorTileFeature = require('./vectortilefeature.js');\n\nmodule.exports = VectorTileLayer;\n\nfunction VectorTileLayer(pbf, end) {\n // Public\n this.version = 1;\n this.name = null;\n this.extent = 4096;\n this.length = 0;\n\n // Private\n this._pbf = pbf;\n this._keys = [];\n this._values = [];\n this._features = [];\n\n pbf.readFields(readLayer, this, end);\n\n this.length = this._features.length;\n}\n\nfunction readLayer(tag, layer, pbf) {\n if (tag === 15) layer.version = pbf.readVarint();\n else if (tag === 1) layer.name = pbf.readString();\n else if (tag === 5) layer.extent = pbf.readVarint();\n else if (tag === 2) layer._features.push(pbf.pos);\n else if (tag === 3) layer._keys.push(pbf.readString());\n else if (tag === 4) layer._values.push(readValueMessage(pbf));\n}\n\nfunction readValueMessage(pbf) {\n var value = null,\n end = pbf.readVarint() + pbf.pos;\n\n while (pbf.pos < end) {\n var tag = pbf.readVarint() >> 3;\n\n value = tag === 1 ? pbf.readString() :\n tag === 2 ? pbf.readFloat() :\n tag === 3 ? pbf.readDouble() :\n tag === 4 ? pbf.readVarint64() :\n tag === 5 ? pbf.readVarint() :\n tag === 6 ? pbf.readSVarint() :\n tag === 7 ? pbf.readBoolean() : null;\n }\n\n return value;\n}\n\n// return feature `i` from this layer as a `VectorTileFeature`\nVectorTileLayer.prototype.feature = function(i) {\n if (i < 0 || i >= this._features.length) throw new Error('feature index out of bounds');\n\n this._pbf.pos = this._features[i];\n\n var end = this._pbf.readVarint() + this._pbf.pos;\n return new VectorTileFeature(this._pbf, end, this.extent, this._keys, this._values);\n};\n","'use strict';\n\nvar VectorTileLayer = require('./vectortilelayer');\n\nmodule.exports = VectorTile;\n\nfunction VectorTile(pbf, end) {\n this.layers = pbf.readFields(readTile, {}, end);\n}\n\nfunction readTile(tag, layers, pbf) {\n if (tag === 3) {\n var layer = new VectorTileLayer(pbf, pbf.readVarint() + pbf.pos);\n if (layer.length) layers[layer.name] = layer;\n }\n}\n\n","module.exports.VectorTile = require('./lib/vectortile.js');\nmodule.exports.VectorTileFeature = require('./lib/vectortilefeature.js');\nmodule.exports.VectorTileLayer = require('./lib/vectortilelayer.js');\n","// @flow\n\nimport assert from 'assert';\nimport Point from '@mapbox/point-geometry';\n\nexport type ClippedPolygon = {\n polygon: Array<Array<Point>>,\n bounds: [Point, Point]\n};\n\ntype PolygonArray = Array<Array<Array<Point>>>;\n\nfunction clipPolygon(polygons: PolygonArray, clipAxis1: number, clipAxis2: number, axis: number): PolygonArray {\n const intersectX = (ring: Array<Point>, ax: number, ay: number, bx: number, by: number, x: number) => {\n ring.push(new Point(x, ay + (by - ay) * ((x - ax) / (bx - ax))));\n };\n const intersectY = (ring: Array<Point>, ax: number, ay: number, bx: number, by: number, y: number) => {\n ring.push(new Point(ax + (bx - ax) * ((y - ay) / (by - ay)), y));\n };\n\n const polygonsClipped = [];\n const intersect = axis === 0 ? intersectX : intersectY;\n for (const polygon of polygons) {\n const polygonClipped = [];\n for (const ring of polygon) {\n if (ring.length <= 2) {\n continue;\n }\n\n const clipped = [];\n for (let i = 0; i < ring.length - 1; i++) {\n const ax = ring[i].x;\n const ay = ring[i].y;\n const bx = ring[i + 1].x;\n const by = ring[i + 1].y;\n const a = axis === 0 ? ax : ay;\n const b = axis === 0 ? bx : by;\n if (a < clipAxis1) {\n if (b > clipAxis1) {\n intersect(clipped, ax, ay, bx, by, clipAxis1);\n }\n } else if (a > clipAxis2) {\n if (b < clipAxis2) {\n intersect(clipped, ax, ay, bx, by, clipAxis2);\n }\n } else {\n clipped.push(ring[i]);\n }\n if (b < clipAxis1 && a >= clipAxis1) {\n intersect(clipped, ax, ay, bx, by, clipAxis1);\n }\n if (b > clipAxis2 && a <= clipAxis2) {\n intersect(clipped, ax, ay, bx, by, clipAxis2);\n }\n }\n\n let last = ring[ring.length - 1];\n const a = axis === 0 ? last.x : last.y;\n if (a >= clipAxis1 && a <= clipAxis2) {\n clipped.push(last);\n }\n if (clipped.length) {\n last = clipped[clipped.length - 1];\n if (clipped[0].x !== last.x || clipped[0].y !== last.y) {\n clipped.push(clipped[0]);\n }\n polygonClipped.push(clipped);\n }\n }\n if (polygonClipped.length) {\n polygonsClipped.push(polygonClipped);\n }\n }\n\n return polygonsClipped;\n}\n\nexport function subdividePolygons(polygons: PolygonArray, bounds: [Point, Point], gridSizeX: number, gridSizeY: number, padding: number = 0.0, splitFn: Function): Array<ClippedPolygon> {\n const outPolygons = [];\n\n if (!polygons.length || !gridSizeX || !gridSizeY) {\n return outPolygons;\n }\n\n const addResult = (clipped: PolygonArray, bounds: [Point, Point]) => {\n for (const polygon of clipped) {\n outPolygons.push({polygon, bounds});\n }\n };\n\n const hSplits = Math.ceil(Math.log2(gridSizeX));\n const vSplits = Math.ceil(Math.log2(gridSizeY));\n\n const initialSplits = hSplits - vSplits;\n\n const splits = [];\n for (let i = 0; i < Math.abs(initialSplits); i++) {\n splits.push(initialSplits > 0 ? 0 : 1);\n }\n\n for (let i = 0; i < Math.min(hSplits, vSplits); i++) {\n splits.push(0); // x\n splits.push(1); // y\n }\n\n let split = polygons;\n\n split = clipPolygon(split, bounds[0].y - padding, bounds[1].y + padding, 1);\n split = clipPolygon(split, bounds[0].x - padding, bounds[1].x + padding, 0);\n\n if (!split.length) {\n return outPolygons;\n }\n\n const stack = [];\n if (splits.length) {\n stack.push({polygons: split, bounds, depth: 0});\n } else {\n addResult(split, bounds);\n }\n\n while (stack.length) {\n const frame = stack.pop();\n\n assert(frame.polygons.length > 0);\n\n const depth = frame.depth;\n const axis = splits[depth];\n\n const bboxMin = frame.bounds[0];\n const bboxMax = frame.bounds[1];\n\n const splitMin = axis === 0 ? bboxMin.x : bboxMin.y;\n const splitMax = axis === 0 ? bboxMax.x : bboxMax.y;\n\n const splitMid = splitFn ? splitFn(axis, splitMin, splitMax) : 0.5 * (splitMin + splitMax);\n\n const lclip = clipPolygon(frame.polygons, splitMin - padding, splitMid + padding, axis);\n const rclip = clipPolygon(frame.polygons, splitMid - padding, splitMax + padding, axis);\n\n if (lclip.length) {\n const bbMaxX = axis === 0 ? splitMid : bboxMax.x;\n const bbMaxY = axis === 1 ? splitMid : bboxMax.y;\n\n const bbMax = new Point(bbMaxX, bbMaxY);\n\n const lclipBounds = [bboxMin, bbMax];\n\n if (splits.length > depth + 1) {\n stack.push({polygons: lclip, bounds: lclipBounds, depth: depth + 1});\n } else {\n addResult(lclip, lclipBounds);\n }\n }\n\n if (rclip.length) {\n const bbMinX = axis === 0 ? splitMid : bboxMin.x;\n const bbMinY = axis === 1 ? splitMid : bboxMin.y;\n\n const bbMin = new Point(bbMinX, bbMinY);\n\n const rclipBounds = [bbMin, bboxMax];\n\n if (splits.length > depth + 1) {\n stack.push({polygons: rclip, bounds: rclipBounds, depth: depth + 1});\n } else {\n addResult(rclip, rclipBounds);\n }\n }\n }\n\n return outPolygons;\n}\n","// @flow\n\nimport {FillExtrusionLayoutArray, FillExtrusionExtArray, FillExtrusionCentroidArray} from '../array_types.js';\n\nimport {members as layoutAttributes, centroidAttributes, fillExtrusionAttributesExt} from './fill_extrusion_attributes.js';\nimport SegmentVector from '../segment.js';\nimport {ProgramConfigurationSet} from '../program_configuration.js';\nimport {TriangleIndexArray} from '../index_array_type.js';\nimport EXTENT from '../extent.js';\nimport earcut from 'earcut';\nimport {VectorTileFeature} from '@mapbox/vector-tile';\nconst vectorTileFeatureTypes = VectorTileFeature.types;\nimport classifyRings from '../../util/classify_rings.js';\nimport assert from 'assert';\nconst EARCUT_MAX_RINGS = 500;\nimport {register} from '../../util/web_worker_transfer.js';\nimport {hasPattern, addPatternDependencies} from './pattern_bucket_features.js';\nimport loadGeometry from '../load_geometry.js';\nimport toEvaluationFeature from '../evaluation_feature.js';\nimport EvaluationParameters from '../../style/evaluation_parameters.js';\nimport Point from '@mapbox/point-geometry';\nimport {number as interpolate} from '../../style-spec/util/interpolate.js';\nimport {lngFromMercatorX, latFromMercatorY, mercatorYfromLat} from '../../geo/mercator_coordinate.js';\nimport {subdividePolygons} from '../../util/polygon_clipping.js';\nimport type {ClippedPolygon} from '../../util/polygon_clipping.js';\nimport type {Vec3} from 'gl-matrix';\nimport type {CanonicalTileID} from '../../source/tile_id.js';\nimport type {\n Bucket,\n BucketParameters,\n BucketFeature,\n IndexedFeature,\n PopulateParameters\n} from '../bucket.js';\nimport {earthRadius} from '../../geo/lng_lat.js';\n\nimport type FillExtrusionStyleLayer from '../../style/style_layer/fill_extrusion_style_layer.js';\nimport type Context from '../../gl/context.js';\nimport type IndexBuffer from '../../gl/index_buffer.js';\nimport type VertexBuffer from '../../gl/vertex_buffer.js';\nimport type {FeatureStates} from '../../source/source_state.js';\nimport type {SpritePositions} from '../../util/image.js';\nimport type {ProjectionSpecification} from '../../style-spec/types.js';\nimport type {TileTransform} from '../../geo/projection/tile_transform.js';\nimport type {IVectorTileLayer} from '@mapbox/vector-tile';\n\nconst FACTOR = Math.pow(2, 13);\n\n// Also declared in _prelude_terrain.vertex.glsl\n// Used to scale most likely elevation values to fit well in an uint16\n// (Elevation of Dead Sea + ELEVATION_OFFSET) * ELEVATION_SCALE is roughly 0\n// (Height of mt everest + ELEVATION_OFFSET) * ELEVATION_SCALE is roughly 64k\nexport const ELEVATION_SCALE = 7.0;\nexport const ELEVATION_OFFSET = 450;\n\nfunction addVertex(vertexArray: FillExtrusionLayoutArray, x: number, y: number, nxRatio: number, nySign: number, normalUp: number, top: number, e: number) {\n vertexArray.emplaceBack(\n // a_pos_normal_ed:\n // Encode top and side/up normal using the least significant bits\n (x << 1) + top,\n (y << 1) + normalUp,\n // dxdy is signed, encode quadrant info using the least significant bit\n (Math.floor(nxRatio * FACTOR) << 1) + nySign,\n // edgedistance (used for wrapping patterns around extrusion sides)\n Math.round(e)\n );\n}\n\nfunction addGlobeExtVertex(vertexArray: FillExtrusionExtArray, pos: {x: number, y: number, z: number}, normal: Vec3) {\n const encode = 1 << 14;\n vertexArray.emplaceBack(\n pos.x, pos.y, pos.z,\n normal[0] * encode, normal[1] * encode, normal[2] * encode);\n}\n\nexport class PartMetadata {\n acc: Point;\n min: Point;\n max: Point;\n polyCount: Array<{edges: number, top: number}>;\n currentPolyCount: {edges: number, top: number};\n borders: Array<[number, number]>; // Array<[min, max]>\n vertexArrayOffset: number;\n\n constructor() {\n this.acc = new Point(0, 0);\n this.polyCount = [];\n }\n\n startRing(p: Point) {\n this.currentPolyCount = {edges: 0, top: 0};\n this.polyCount.push(this.currentPolyCount);\n if (this.min) return;\n this.min = new Point(p.x, p.y);\n this.max = new Point(p.x, p.y);\n }\n\n append(p: Point, prev: Point) {\n this.currentPolyCount.edges++;\n\n this.acc._add(p);\n const min = this.min, max = this.max;\n if (p.x < min.x) {\n min.x = p.x;\n } else if (p.x > max.x) {\n max.x = p.x;\n }\n if (p.y < min.y) {\n min.y = p.y;\n } else if (p.y > max.y) {\n max.y = p.y;\n }\n if (((p.x === 0 || p.x === EXTENT) && p.x === prev.x) !== ((p.y === 0 || p.y === EXTENT) && p.y === prev.y)) {\n // Custom defined geojson buildings are cut on borders. Points are\n // repeated when edge cuts tile corner (reason for using xor).\n this.processBorderOverlap(p, prev);\n }\n // check border intersection\n if ((prev.x < 0) !== (p.x < 0)) {\n this.addBorderIntersection(0, interpolate(prev.y, p.y, (0 - prev.x) / (p.x - prev.x)));\n }\n if ((prev.x > EXTENT) !== (p.x > EXTENT)) {\n this.addBorderIntersection(1, interpolate(prev.y, p.y, (EXTENT - prev.x) / (p.x - prev.x)));\n }\n if ((prev.y < 0) !== (p.y < 0)) {\n this.addBorderIntersection(2, interpolate(prev.x, p.x, (0 - prev.y) / (p.y - prev.y)));\n }\n if ((prev.y > EXTENT) !== (p.y > EXTENT)) {\n this.addBorderIntersection(3, interpolate(prev.x, p.x, (EXTENT - prev.y) / (p.y - prev.y)));\n }\n }\n\n addBorderIntersection(index: 0 | 1 | 2 | 3, i: number) {\n if (!this.borders) {\n this.borders = [\n [Number.MAX_VALUE, -Number.MAX_VALUE],\n [Number.MAX_VALUE, -Number.MAX_VALUE],\n [Number.MAX_VALUE, -Number.MAX_VALUE],\n [Number.MAX_VALUE, -Number.MAX_VALUE]\n ];\n }\n const b = this.borders[index];\n if (i < b[0]) b[0] = i;\n if (i > b[1]) b[1] = i;\n }\n\n processBorderOverlap(p: Point, prev: Point) {\n if (p.x === prev.x) {\n if (p.y === prev.y) return; // custom defined geojson could have points repeated.\n const index = p.x === 0 ? 0 : 1;\n this.addBorderIntersection(index, prev.y);\n this.addBorderIntersection(index, p.y);\n } else {\n assert(p.y === prev.y);\n const index = p.y === 0 ? 2 : 3;\n this.addBorderIntersection(index, prev.x);\n this.addBorderIntersection(index, p.x);\n }\n }\n\n centroid(): Point {\n const count = this.polyCount.reduce((acc, p) => acc + p.edges, 0);\n return count !== 0 ? this.acc.div(count)._round() : new Point(0, 0);\n }\n\n span(): Point {\n return new Point(this.max.x - this.min.x, this.max.y - this.min.y);\n }\n\n intersectsCount(): number {\n return this.borders.reduce((acc, p) => acc + +(p[0] !== Number.MAX_VALUE), 0);\n }\n}\n\nclass FillExtrusionBucket implements Bucket {\n index: number;\n zoom: number;\n canonical: CanonicalTileID;\n overscaling: number;\n enableTerrain: boolean;\n layers: Array<FillExtrusionStyleLayer>;\n layerIds: Array<string>;\n stateDependentLayers: Array<FillExtrusionStyleLayer>;\n stateDependentLayerIds: Array<string>;\n\n layoutVertexArray: FillExtrusionLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n\n centroidVertexArray: FillExtrusionCentroidArray;\n centroidVertexBuffer: VertexBuffer;\n\n layoutVertexExtArray: ?FillExtrusionExtArray;\n layoutVertexExtBuffer: ?VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n hasPattern: boolean;\n edgeRadius: number;\n programConfigurations: ProgramConfigurationSet<FillExtrusionStyleLayer>;\n segments: SegmentVector;\n uploaded: boolean;\n features: Array<BucketFeature>;\n\n featuresOnBorder: Array<PartMetadata>;\n // borders / borderDoneWithNeighborZ: 0 - left, 1, right, 2 - top, 3 - bottom\n borders: Array<Array<number>>; // For each side, indices into featuresOnBorder array.\n borderDoneWithNeighborZ: Array<number>;\n needsCentroidUpdate: boolean;\n tileToMeter: number; // cache conversion.\n projection: ProjectionSpecification;\n\n constructor(options: BucketParameters<FillExtrusionStyleLayer>) {\n this.zoom = options.zoom;\n this.canonical = options.canonical;\n this.overscaling = options.overscaling;\n this.layers = options.layers;\n this.layerIds = this.layers.map(layer => layer.id);\n this.index = options.index;\n this.hasPattern = false;\n this.edgeRadius = 0;\n this.projection = options.projection;\n\n this.layoutVertexArray = new FillExtrusionLayoutArray();\n this.centroidVertexArray = new FillExtrusionCentroidArray();\n this.indexArray = new TriangleIndexArray();\n this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n this.segments = new SegmentVector();\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n this.enableTerrain = options.enableTerrain;\n }\n\n populate(features: Array<IndexedFeature>, options: PopulateParameters, canonical: CanonicalTileID, tileTransform: TileTransform) {\n this.features = [];\n this.hasPattern = hasPattern('fill-extrusion', this.layers, options);\n this.featuresOnBorder = [];\n this.borders = [[], [], [], []];\n this.borderDoneWithNeighborZ = [-1, -1, -1, -1];\n this.tileToMeter = tileToMeter(canonical);\n this.edgeRadius = this.layers[0].layout.get('fill-extrusion-edge-radius') / this.tileToMeter;\n\n for (const {feature, id, index, sourceLayerIndex} of features) {\n const needGeometry = this.layers[0]._featureFilter.needGeometry;\n const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n\n // $FlowFixMe[method-unbinding]\n if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) continue;\n\n const bucketFeature: BucketFeature = {\n id,\n sourceLayerIndex,\n index,\n geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature, canonical, tileTransform),\n properties: feature.properties,\n type: feature.type,\n patterns: {}\n };\n\n const vertexArrayOffset = this.layoutVertexArray.length;\n if (this.hasPattern) {\n this.features.push(addPatternDependencies('fill-extrusion', this.layers, bucketFeature, this.zoom, options));\n } else {\n this.addFeature(bucketFeature, bucketFeature.geometry, index, canonical, {}, options.availableImages, tileTransform);\n }\n\n options.featureIndex.insert(feature, bucketFeature.geometry, index, sourceLayerIndex, this.index, vertexArrayOffset);\n }\n this.sortBorders();\n }\n\n addFeatures(options: PopulateParameters, canonical: CanonicalTileID, imagePositions: SpritePositions, availableImages: Array<string>, tileTransform: TileTransform) {\n for (const feature of this.features) {\n const {geometry} = feature;\n this.addFeature(feature, geometry, feature.index, canonical, imagePositions, availableImages, tileTransform);\n }\n this.sortBorders();\n }\n\n update(states: FeatureStates, vtLayer: IVectorTileLayer, availableImages: Array<string>, imagePositions: SpritePositions) {\n if (!this.stateDependentLayers.length) return;\n this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, availableImages, imagePositions);\n }\n\n isEmpty(): boolean {\n return this.layoutVertexArray.length === 0;\n }\n\n uploadPending(): boolean {\n return !this.uploaded || this.programConfigurations.needsUpload;\n }\n\n upload(context: Context) {\n if (!this.uploaded) {\n this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);\n this.indexBuffer = context.createIndexBuffer(this.indexArray);\n\n if (this.layoutVertexExtArray) {\n this.layoutVertexExtBuffer = context.createVertexBuffer(this.layoutVertexExtArray, fillExtrusionAttributesExt.members, true);\n }\n }\n this.programConfigurations.upload(context);\n this.uploaded = true;\n }\n\n uploadCentroid(context: Context) {\n if (this.centroidVertexArray.length === 0) return;\n if (!this.centroidVertexBuffer) {\n this.centroidVertexBuffer = context.createVertexBuffer(this.centroidVertexArray, centroidAttributes.members, true);\n } else if (this.needsCentroidUpdate) {\n this.centroidVertexBuffer.updateData(this.centroidVertexArray);\n }\n this.needsCentroidUpdate = false;\n }\n\n destroy() {\n if (!this.layoutVertexBuffer) return;\n this.layoutVertexBuffer.destroy();\n if (this.centroidVertexBuffer) {\n this.centroidVertexBuffer.destroy();\n }\n if (this.layoutVertexExtBuffer) {\n this.layoutVertexExtBuffer.destroy();\n }\n this.indexBuffer.destroy();\n this.programConfigurations.destroy();\n this.segments.destroy();\n }\n\n addFeature(feature: BucketFeature, geometry: Array<Array<Point>>, index: number, canonical: CanonicalTileID, imagePositions: SpritePositions, availableImages: Array<string>, tileTransform: TileTransform) {\n const tileBounds = [new Point(0, 0), new Point(EXTENT, EXTENT)];\n const projection = tileTransform.projection;\n const isGlobe = projection.name === 'globe';\n const metadata = this.enableTerrain && !isGlobe ? new PartMetadata() : null;\n const isPolygon = vectorTileFeatureTypes[feature.type] === 'Polygon';\n\n if (isGlobe && !this.layoutVertexExtArray) {\n this.layoutVertexExtArray = new FillExtrusionExtArray();\n }\n\n const polygons = classifyRings(geometry, EARCUT_MAX_RINGS);\n\n for (let i = polygons.length - 1; i >= 0; i--) {\n const polygon = polygons[i];\n if (polygon.length === 0 || isEntirelyOutside(polygon[0])) {\n polygons.splice(i, 1);\n }\n }\n\n let clippedPolygons: ClippedPolygon[];\n if (isGlobe) {\n // Perform tesselation for polygons of tiles in order to support long planar\n // triangles on the curved surface of the globe. This is done for all polygons\n // regardless of their size in order guarantee identical results on all sides of\n // tile boundaries.\n //\n // The globe is subdivided into a 32x16 grid. The number of subdivisions done\n // for a tile depends on the zoom level. For example tile with z=0 requires 2⁴\n // subdivisions, tile with z=1 2³ etc. The subdivision is done in polar coordinates\n // instead of tile coordinates.\n clippedPolygons = resampleFillExtrusionPolygonsForGlobe(polygons, tileBounds, canonical);\n } else {\n clippedPolygons = [];\n for (const polygon of polygons) {\n clippedPolygons.push({polygon, bounds: tileBounds});\n }\n }\n\n const edgeRadius = isPolygon ? this.edgeRadius : 0;\n\n for (const {polygon, bounds} of clippedPolygons) {\n // Only triangulate and draw the area of the feature if it is a polygon\n // Other feature types (e.g. LineString) do not have area, so triangulation is pointless / undefined\n let topIndex = 0;\n let numVertices = 0;\n for (const ring of polygon) {\n // make sure the ring closes\n if (isPolygon && !ring[0].equals(ring[ring.length - 1])) ring.push(ring[0]);\n numVertices += (isPolygon ? (ring.length - 1) : ring.length);\n }\n // We use \"(isPolygon ? 5 : 4) * numVertices\" as an estimate to ensure whether additional segments are needed or not (see SegmentVector.MAX_VERTEX_ARRAY_LENGTH).\n const segment = this.segments.prepareSegment((isPolygon ? 5 : 4) * numVertices, this.layoutVertexArray, this.indexArray);\n if (isPolygon) {\n const flattened = [];\n const holeIndices = [];\n topIndex = segment.vertexLength;\n\n // First we offset (inset) the top vertices (i.e the vertices that make up the roof).\n for (const ring of polygon) {\n if (ring.length && ring !== polygon[0]) {\n holeIndices.push(flattened.length / 2);\n }\n\n // The following vectors are used to avoid duplicate normal calculations when going over the vertices.\n let na, nb;\n {\n const p0 = ring[0];\n const p1 = ring[1];\n na = p1.sub(p0)._perp()._unit();\n }\n for (let i = 1; i < ring.length; i++) {\n const p1 = ring[i];\n const p2 = ring[i === ring.length - 1 ? 1 : i + 1];\n\n let {x, y} = p1;\n if (edgeRadius) {\n nb = p2.sub(p1)._perp()._unit();\n const nm = na.add(nb)._unit();\n\n const cosHalfAngle = na.x * nm.x + na.y * nm.y;\n const offset = edgeRadius * Math.min(4, 1 / cosHalfAngle);\n\n x += offset * nm.x;\n y += offset * nm.y;\n\n na = nb;\n }\n\n addVertex(this.layoutVertexArray, x, y, 0, 0, 1, 1, 0);\n segment.vertexLength++;\n\n // triangulate as if vertices were not offset to ensure correct triangulation\n flattened.push(p1.x, p1.y);\n\n if (isGlobe) {\n const array: any = this.layoutVertexExtArray;\n const projectedP = projection.projectTilePoint(x, y, canonical);\n const n = projection.upVector(canonical, x, y);\n addGlobeExtVertex(array, projectedP, n);\n }\n }\n }\n\n const indices = earcut(flattened, holeIndices);\n assert(indices.length % 3 === 0);\n\n for (let j = 0; j < indices.length; j += 3) {\n // clockwise winding order.\n this.indexArray.emplaceBack(\n topIndex + indices[j],\n topIndex + indices[j + 2],\n topIndex + indices[j + 1]);\n segment.primitiveLength++;\n }\n }\n\n for (const ring of polygon) {\n if (metadata && ring.length) metadata.startRing(ring[0]);\n let isPrevCornerConcave = ring.length > 4 && isAOConcaveAngle(ring[ring.length - 2], ring[0], ring[1]);\n let offsetPrev = edgeRadius ? getRoundedEdgeOffset(ring[ring.length - 2], ring[0], ring[1], edgeRadius) : 0;\n\n let kFirst;\n\n // The following vectors are used to avoid duplicate normal calculations when going over the vertices.\n let na, nb;\n {\n const p0 = ring[0];\n const p1 = ring[1];\n na = p1.sub(p0)._perp()._unit();\n }\n let cap = true;\n for (let i = 1, edgeDistance = 0; i < ring.length; i++) {\n let p0 = ring[i - 1];\n let p1 = ring[i];\n const p2 = ring[i === ring.length - 1 ? 1 : i + 1];\n\n if (metadata && isPolygon) metadata.currentPolyCount.top++;\n if (isEdgeOutsideBounds(p1, p0, bounds)) {\n if (edgeRadius) {\n na = p2.sub(p1)._perp()._unit();\n cap = !cap;\n }\n continue;\n }\n if (metadata) metadata.append(p1, p0);\n\n const d = p1.sub(p0)._perp();\n // Given that nz === 0, encode nx / (abs(nx) + abs(ny)) and signs.\n // This information is sufficient to reconstruct normal vector in vertex shader.\n const nxRatio = d.x / (Math.abs(d.x) + Math.abs(d.y));\n const nySign = d.y > 0 ? 1 : 0;\n\n const dist = p0.dist(p1);\n if (edgeDistance + dist > 32768) edgeDistance = 0;\n\n // Next offset the vertices along the edges and create a chamfer space between them:\n // So if we have the following (where 'x' denotes a vertex)\n // x──────x\n // | |\n // | |\n // | |\n // | |\n // x──────x\n // we end up with:\n // x────x\n // x x\n // | |\n // | |\n // x x\n // x────x\n // (drawing isn't exact but hopefully gets the point across).\n\n if (edgeRadius) {\n nb = p2.sub(p1)._perp()._unit();\n\n const cosHalfAngle = getCosHalfAngle(na, nb);\n let offsetNext = _getRoundedEdgeOffset(p0, p1, p2, cosHalfAngle, edgeRadius);\n\n if (isNaN(offsetNext)) offsetNext = 0;\n const nEdge = p1.sub(p0)._unit();\n p0 = p0.add(nEdge.mult(offsetPrev))._round();\n p1 = p1.add(nEdge.mult(-offsetNext))._round();\n offsetPrev = offsetNext;\n\n na = nb;\n }\n\n const k = segment.vertexLength;\n\n const isConcaveCorner = ring.length > 4 && isAOConcaveAngle(p0, p1, p2);\n let encodedEdgeDistance = encodeAOToEdgeDistance(edgeDistance, isPrevCornerConcave, cap);\n\n addVertex(this.layoutVertexArray, p0.x, p0.y, nxRatio, nySign, 0, 0, encodedEdgeDistance);\n addVertex(this.layoutVertexArray, p0.x, p0.y, nxRatio, nySign, 0, 1, encodedEdgeDistance);\n\n edgeDistance += dist;\n encodedEdgeDistance = encodeAOToEdgeDistance(edgeDistance, isConcaveCorner, !cap);\n isPrevCornerConcave = isConcaveCorner;\n\n addVertex(this.layoutVertexArray, p1.x, p1.y, nxRatio, nySign, 0, 0, encodedEdgeDistance);\n addVertex(this.layoutVertexArray, p1.x, p1.y, nxRatio, nySign, 0, 1, encodedEdgeDistance);\n\n segment.vertexLength += 4;\n\n // ┌──────┐\n // │ 1 3 │ clockwise winding order.\n // │ │ Triangle 1: 0 => 1 => 2\n // │ 0 2 │ Triangle 2: 1 => 3 => 2\n // └──────┘\n this.indexArray.emplaceBack(k + 0, k + 1, k + 2);\n this.indexArray.emplaceBack(k + 1, k + 3, k + 2);\n segment.primitiveLength += 2;\n\n if (edgeRadius) {\n // Note that in the previous for-loop we start from index 1 to add the top vertices which explains the next line.\n const t0 = topIndex + (i === 1 ? ring.length - 2 : i - 2);\n const t1 = i === 1 ? topIndex : t0 + 1;\n\n // top chamfer along the side (i.e. the space between the wall and the roof).\n this.indexArray.emplaceBack(k + 1, t0, k + 3);\n this.indexArray.emplaceBack(t0, t1, k + 3);\n segment.primitiveLength += 2;\n\n if (kFirst === undefined) {\n kFirst = k;\n }\n\n // Make sure to fill in the gap in the corner only when both corresponding edges are in tile bounds.\n if (!isEdgeOutsideBounds(p2, ring[i], bounds)) {\n const l = i === ring.length - 1 ? kFirst : segment.vertexLength;\n\n // vertical side chamfer i.e. the space between consecutive walls.\n this.indexArray.emplaceBack(k + 2, k + 3, l);\n this.indexArray.emplaceBack(k + 3, l + 1, l);\n\n // top corner where the top(roof) and two sides(walls) meet.\n this.indexArray.emplaceBack(k + 3, t1, l + 1);\n\n segment.primitiveLength += 3;\n }\n cap = !cap;\n }\n\n if (isGlobe) {\n const array: any = this.layoutVertexExtArray;\n\n const projectedP0 = projection.projectTilePoint(p0.x, p0.y, canonical);\n const projectedP1 = projection.projectTilePoint(p1.x, p1.y, canonical);\n\n const n0 = projection.upVector(canonical, p0.x, p0.y);\n const n1 = projection.upVector(canonical, p1.x, p1.y);\n\n addGlobeExtVertex(array, projectedP0, n0);\n addGlobeExtVertex(array, projectedP0, n0);\n addGlobeExtVertex(array, projectedP1, n1);\n addGlobeExtVertex(array, projectedP1, n1);\n }\n }\n if (isPolygon) topIndex += (ring.length - 1);\n }\n }\n\n assert(!isGlobe || (this.layoutVertexExtArray && this.layoutVertexExtArray.length === this.layoutVertexArray.length));\n\n if (metadata && metadata.polyCount.length > 0) {\n // When building is split between tiles, don't handle flat roofs here.\n if (metadata.borders) {\n // Store to the bucket. Flat roofs are handled in flatRoofsUpdate,\n // after joining parts that lay in different buckets.\n metadata.vertexArrayOffset = this.centroidVertexArray.length;\n const borders = metadata.borders;\n const index = this.featuresOnBorder.push(metadata) - 1;\n for (let i = 0; i < 4; i++) {\n if (borders[i][0] !== Number.MAX_VALUE) { this.borders[i].push(index); }\n }\n }\n this.encodeCentroid(metadata.borders ? undefined : metadata.centroid(), metadata);\n assert(!this.centroidVertexArray.length || this.centroidVertexArray.length === this.layoutVertexArray.length);\n }\n\n this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, availableImages, canonical);\n }\n\n sortBorders() {\n for (let i = 0; i < 4; i++) {\n // Sort by border intersection area minimums, ascending.\n this.borders[i].sort((a, b) => this.featuresOnBorder[a].borders[i][0] - this.featuresOnBorder[b].borders[i][0]);\n }\n }\n\n encodeCentroid(c: ?Point, metadata: PartMetadata, append: boolean = true) {\n let x, y;\n // Encoded centroid x and y:\n // x y\n // ---------------------------------------------\n // 0 0 Default, no flat roof.\n // 0 1 Hide, used to hide parts of buildings on border while expecting the other side to get loaded\n // >0 0 Elevation encoded to uint16 word\n // >0 >0 Encoded centroid position and x & y span\n if (c) {\n if (c.y !== 0) {\n const span = metadata.span()._mult(this.tileToMeter);\n x = (Math.max(c.x, 1) << 3) + Math.min(7, Math.round(span.x / 10));\n y = (Math.max(c.y, 1) << 3) + Math.min(7, Math.round(span.y / 10));\n } else { // encode height:\n x = Math.ceil((c.x + ELEVATION_OFFSET) * ELEVATION_SCALE);\n y = 0;\n }\n } else {\n // Use the impossible situation (building that has width and doesn't cross border cannot have centroid\n // at border) to encode unprocessed border building: it is initially (append === true) hidden until\n // computing centroid for joined building parts in rendering thread (flatRoofsUpdate). If it intersects more than\n // two borders, flat roof approach is not applied.\n x = 0;\n y = +append; // Hide (1) initially when creating - visibility is changed in draw_fill_extrusion as soon as neighbor tile gets loaded.\n }\n\n assert(append || metadata.vertexArrayOffset !== undefined);\n let offset = append ? this.centroidVertexArray.length : metadata.vertexArrayOffset;\n for (const polyInfo of metadata.polyCount) {\n if (append) {\n this.centroidVertexArray.resize(this.centroidVertexArray.length + polyInfo.edges * 4 + polyInfo.top);\n }\n for (let i = 0; i < polyInfo.top; i++) {\n this.centroidVertexArray.emplace(offset++, x, y);\n }\n for (let i = 0; i < polyInfo.edges * 2; i++) {\n this.centroidVertexArray.emplace(offset++, 0, y);\n this.centroidVertexArray.emplace(offset++, x, y);\n }\n }\n }\n}\n\nfunction getCosHalfAngle(na: Point, nb: Point) {\n const nm = na.add(nb)._unit();\n const cosHalfAngle = na.x * nm.x + na.y * nm.y;\n return cosHalfAngle;\n}\n\nfunction getRoundedEdgeOffset(p0: Point, p1: Point, p2: Point, edgeRadius: number) {\n const na = p1.sub(p0)._perp()._unit();\n const nb = p2.sub(p1)._perp()._unit();\n const cosHalfAngle = getCosHalfAngle(na, nb);\n return _getRoundedEdgeOffset(p0, p1, p2, cosHalfAngle, edgeRadius);\n}\n\nfunction _getRoundedEdgeOffset(p0: Point, p1: Point, p2: Point, cosHalfAngle: number, edgeRadius: number) {\n const sinHalfAngle = Math.sqrt(1 - cosHalfAngle * cosHalfAngle);\n return Math.min(p0.dist(p1) / 3, p1.dist(p2) / 3, edgeRadius * sinHalfAngle / cosHalfAngle);\n}\n\nregister(FillExtrusionBucket, 'FillExtrusionBucket', {omit: ['layers', 'features']});\nregister(PartMetadata, 'PartMetadata');\n\nexport default FillExtrusionBucket;\n\n// Edges that are outside tile bounds are defined in tile across the border.\n// Rendering them twice often results with Z-fighting.\n// In case of globe and axis aligned bounds, it is also useful to\n// discard edges that have the both endpoints outside the same bound.\nfunction isEdgeOutsideBounds(p1: Point, p2: Point, bounds: [Point, Point]) {\n return (p1.x < bounds[0].x && p2.x < bounds[0].x) ||\n (p1.x > bounds[1].x && p2.x > bounds[1].x) ||\n (p1.y < bounds[0].y && p2.y < bounds[0].y) ||\n (p1.y > bounds[1].y && p2.y > bounds[1].y);\n}\n\nfunction isEntirelyOutside(ring: Array<Point>) {\n // Discard rings with corners on border if all other vertices are outside: they get defined\n // also in the tile across the border. Eventual zero area rings at border are discarded by classifyRings\n // and there is no need to handle that case here.\n return ring.every(p => p.x <= 0) ||\n ring.every(p => p.x >= EXTENT) ||\n ring.every(p => p.y <= 0) ||\n ring.every(p => p.y >= EXTENT);\n}\n\nfunction tileToMeter(canonical: CanonicalTileID) {\n const circumferenceAtEquator = 40075017;\n const mercatorY = canonical.y / (1 << canonical.z);\n const exp = Math.exp(Math.PI * (1 - 2 * mercatorY));\n // simplify cos(2 * atan(e) - PI/2) from mercator_coordinate.js, remove trigonometrics.\n return circumferenceAtEquator * 2 * exp / (exp * exp + 1) / EXTENT / (1 << canonical.z);\n}\n\nfunction isAOConcaveAngle(p2: Point, p1: Point, p3: Point) {\n if (p2.x < 0 || p2.x >= EXTENT || p1.x < 0 || p1.x >= EXTENT || p3.x < 0 || p3.x >= EXTENT) {\n return false; // angles are not processed for edges that extend over tile borders\n }\n const a = p3.sub(p1);\n const an = a.perp();\n const b = p2.sub(p1);\n const ab = a.x * b.x + a.y * b.y;\n const cosAB = ab / Math.sqrt(((a.x * a.x + a.y * a.y) * (b.x * b.x + b.y * b.y)));\n const dotProductWithNormal = an.x * b.x + an.y * b.y;\n\n // Heuristics: don't shade concave angles above 150° (arccos(-0.866)).\n return cosAB > -0.866 && dotProductWithNormal < 0;\n}\n\nfunction encodeAOToEdgeDistance(edgeDistance: number, isConcaveCorner: boolean, edgeStart: boolean) {\n // Encode concavity and edge start/end using the least significant bits.\n // Second least significant bit 1 encodes concavity.\n // The least significant bit 1 marks the edge start, 0 for edge end.\n const encodedEdgeDistance = isConcaveCorner ? (edgeDistance | 2) : (edgeDistance & ~2);\n return edgeStart ? (encodedEdgeDistance | 1) : (encodedEdgeDistance & ~1);\n}\n\nexport function fillExtrusionHeightLift(): number {\n // A rectangle covering globe is subdivided into a grid of 32 cells\n // This information can be used to deduce a minimum lift value so that\n // fill extrusions with 0 height will never go below the ground.\n const angle = Math.PI / 32.0;\n const tanAngle = Math.tan(angle);\n const r = earthRadius;\n return r * Math.sqrt(1.0 + 2.0 * tanAngle * tanAngle) - r;\n}\n\n// Resamples fill extrusion polygons by subdividing them into 32x16 cells in mercator space.\n// The idea is to allow reprojection of large continuous planar shapes on the surface of the globe\nexport function resampleFillExtrusionPolygonsForGlobe(polygons: Point[][][], tileBounds: [Point, Point], tileID: CanonicalTileID): ClippedPolygon[] {\n const cellCount = 360.0 / 32.0;\n const tiles = 1 << tileID.z;\n const leftLng = lngFromMercatorX(tileID.x / tiles);\n const rightLng = lngFromMercatorX((tileID.x + 1) / tiles);\n const topLat = latFromMercatorY(tileID.y / tiles);\n const bottomLat = latFromMercatorY((tileID.y + 1) / tiles);\n const cellCountOnXAxis = Math.ceil((rightLng - leftLng) / cellCount);\n const cellCountOnYAxis = Math.ceil((topLat - bottomLat) / cellCount);\n\n const splitFn = (axis: number, min: number, max: number) => {\n if (axis === 0) {\n return 0.5 * (min + max);\n } else {\n const maxLat = latFromMercatorY((tileID.y + min / EXTENT) / tiles);\n const minLat = latFromMercatorY((tileID.y + max / EXTENT) / tiles);\n const midLat = 0.5 * (minLat + maxLat);\n return (mercatorYfromLat(midLat) * tiles - tileID.y) * EXTENT;\n }\n };\n\n return subdividePolygons(polygons, tileBounds, cellCountOnXAxis, cellCountOnYAxis, 1.0, splitFn);\n}\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest.js';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n ColorRampProperty\n} from '../properties.js';\n\nimport type Color from '../../style-spec/util/color.js';\n\nimport type Formatted from '../../style-spec/expression/types/formatted.js';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image.js';\n\nexport type LayoutProps = {|\n \"fill-extrusion-edge-radius\": DataConstantProperty<number>,\n|};\n\nconst layout: Properties<LayoutProps> = new Properties({\n \"fill-extrusion-edge-radius\": new DataConstantProperty(styleSpec[\"layout_fill-extrusion\"][\"fill-extrusion-edge-radius\"]),\n});\n\nexport type PaintProps = {|\n \"fill-extrusion-opacity\": DataConstantProperty<number>,\n \"fill-extrusion-color\": DataDrivenProperty<Color>,\n \"fill-extrusion-translate\": DataConstantProperty<[number, number]>,\n \"fill-extrusion-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"fill-extrusion-pattern\": DataDrivenProperty<?ResolvedImage>,\n \"fill-extrusion-height\": DataDrivenProperty<number>,\n \"fill-extrusion-base\": DataDrivenProperty<number>,\n \"fill-extrusion-vertical-gradient\": DataConstantProperty<boolean>,\n \"fill-extrusion-ambient-occlusion-intensity\": DataConstantProperty<number>,\n \"fill-extrusion-ambient-occlusion-radius\": DataConstantProperty<number>,\n \"fill-extrusion-rounded-roof\": DataConstantProperty<boolean>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"fill-extrusion-opacity\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-opacity\"]),\n \"fill-extrusion-color\": new DataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-color\"]),\n \"fill-extrusion-translate\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-translate\"]),\n \"fill-extrusion-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-translate-anchor\"]),\n \"fill-extrusion-pattern\": new DataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-pattern\"]),\n \"fill-extrusion-height\": new DataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-height\"]),\n \"fill-extrusion-base\": new DataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-base\"]),\n \"fill-extrusion-vertical-gradient\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-vertical-gradient\"]),\n \"fill-extrusion-ambient-occlusion-intensity\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-ambient-occlusion-intensity\"]),\n \"fill-extrusion-ambient-occlusion-radius\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-ambient-occlusion-radius\"]),\n \"fill-extrusion-rounded-roof\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-rounded-roof\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint, layout }: $Exact<{\n paint: Properties<PaintProps>, layout: Properties<LayoutProps>\n}>);\n","export { getURL, getTileBBox, getMercCoords };\n\n\n/**\n * getURL\n *\n * @param {String} baseUrl Base url of the WMS server\n * @param {String} layer Layer name\n * @param {Number} x Tile coordinate x\n * @param {Number} y Tile coordinate y\n * @param {Number} z Tile zoom\n * @param {Object} [options]\n * @param {String} [options.format='image/png']\n * @param {String} [options.service='WMS']\n * @param {String} [options.version='1.1.1']\n * @param {String} [options.request='GetMap']\n * @param {String} [options.srs='EPSG:3857']\n * @param {Number} [options.width='256']\n * @param {Number} [options.height='256']\n * @returns {String} url\n * @example\n * var baseUrl = 'http://geodata.state.nj.us/imagerywms/Natural2015';\n * var layer = 'Natural2015';\n * var url = whoots.getURL(baseUrl, layer, 154308, 197167, 19);\n */\nfunction getURL(baseUrl, layer, x, y, z, options) {\n options = options || {};\n\n var url = baseUrl + '?' + [\n 'bbox=' + getTileBBox(x, y, z),\n 'format=' + (options.format || 'image/png'),\n 'service=' + (options.service || 'WMS'),\n 'version=' + (options.version || '1.1.1'),\n 'request=' + (options.request || 'GetMap'),\n 'srs=' + (options.srs || 'EPSG:3857'),\n 'width=' + (options.width || 256),\n 'height=' + (options.height || 256),\n 'layers=' + layer\n ].join('&');\n\n return url;\n}\n\n\n/**\n * getTileBBox\n *\n * @param {Number} x Tile coordinate x\n * @param {Number} y Tile coordinate y\n * @param {Number} z Tile zoom\n * @returns {String} String of the bounding box\n */\nfunction getTileBBox(x, y, z) {\n // for Google/OSM tile scheme we need to alter the y\n y = (Math.pow(2, z) - y - 1);\n\n var min = getMercCoords(x * 256, y * 256, z),\n max = getMercCoords((x + 1) * 256, (y + 1) * 256, z);\n\n return min[0] + ',' + min[1] + ',' + max[0] + ',' + max[1];\n}\n\n\n/**\n * getMercCoords\n *\n * @param {Number} x Pixel coordinate x\n * @param {Number} y Pixel coordinate y\n * @param {Number} z Tile zoom\n * @returns {Array} [x, y]\n */\nfunction getMercCoords(x, y, z) {\n var resolution = (2 * Math.PI * 6378137 / 256) / Math.pow(2, z),\n merc_x = (x * resolution - 2 * Math.PI * 6378137 / 2.0),\n merc_y = (y * resolution - 2 * Math.PI * 6378137 / 2.0);\n\n return [merc_x, merc_y];\n}\n","// @flow\n\nimport {getTileBBox} from '@mapbox/whoots-js';\nimport assert from 'assert';\nimport {register} from '../util/web_worker_transfer.js';\n\nexport class CanonicalTileID {\n z: number;\n x: number;\n y: number;\n key: number;\n\n constructor(z: number, x: number, y: number) {\n assert(z >= 0 && z <= 25);\n assert(x >= 0 && x < Math.pow(2, z));\n assert(y >= 0 && y < Math.pow(2, z));\n this.z = z;\n this.x = x;\n this.y = y;\n this.key = calculateKey(0, z, z, x, y);\n }\n\n equals(id: CanonicalTileID): boolean {\n return this.z === id.z && this.x === id.x && this.y === id.y;\n }\n\n // given a list of urls, choose a url template and return a tile URL\n url(urls: Array<string>, scheme: ?string): string {\n const bbox = getTileBBox(this.x, this.y, this.z);\n const quadkey = getQuadkey(this.z, this.x, this.y);\n\n return urls[(this.x + this.y) % urls.length]\n .replace('{prefix}', (this.x % 16).toString(16) + (this.y % 16).toString(16))\n .replace(/{z}/g, String(this.z))\n .replace(/{x}/g, String(this.x))\n .replace(/{y}/g, String(scheme === 'tms' ? (Math.pow(2, this.z) - this.y - 1) : this.y))\n .replace('{quadkey}', quadkey)\n .replace('{bbox-epsg-3857}', bbox);\n }\n\n toString(): string {\n return `${this.z}/${this.x}/${this.y}`;\n }\n}\n\nexport class UnwrappedTileID {\n wrap: number;\n canonical: CanonicalTileID;\n key: number;\n\n constructor(wrap: number, canonical: CanonicalTileID) {\n this.wrap = wrap;\n this.canonical = canonical;\n this.key = calculateKey(wrap, canonical.z, canonical.z, canonical.x, canonical.y);\n }\n}\n\nexport class OverscaledTileID {\n overscaledZ: number;\n wrap: number;\n canonical: CanonicalTileID;\n key: number;\n projMatrix: Float32Array;\n\n constructor(overscaledZ: number, wrap: number, z: number, x: number, y: number) {\n assert(overscaledZ >= z);\n this.overscaledZ = overscaledZ;\n this.wrap = wrap;\n this.canonical = new CanonicalTileID(z, +x, +y);\n this.key = wrap === 0 && overscaledZ === z ? this.canonical.key : calculateKey(wrap, overscaledZ, z, x, y);\n }\n\n equals(id: OverscaledTileID): boolean {\n return this.overscaledZ === id.overscaledZ && this.wrap === id.wrap && this.canonical.equals(id.canonical);\n }\n\n scaledTo(targetZ: number): OverscaledTileID {\n assert(targetZ <= this.overscaledZ);\n const zDifference = this.canonical.z - targetZ;\n if (targetZ > this.canonical.z) {\n return new OverscaledTileID(targetZ, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y);\n } else {\n return new OverscaledTileID(targetZ, this.wrap, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);\n }\n }\n\n /*\n * calculateScaledKey is an optimization:\n * when withWrap == true, implements the same as this.scaledTo(z).key,\n * when withWrap == false, implements the same as this.scaledTo(z).wrapped().key.\n */\n calculateScaledKey(targetZ: number, withWrap: boolean = true): number {\n if (this.overscaledZ === targetZ && withWrap) return this.key;\n if (targetZ > this.canonical.z) {\n return calculateKey(this.wrap * +withWrap, targetZ, this.canonical.z, this.canonical.x, this.canonical.y);\n } else {\n const zDifference = this.canonical.z - targetZ;\n return calculateKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);\n }\n }\n\n isChildOf(parent: OverscaledTileID): boolean {\n if (parent.wrap !== this.wrap) {\n // We can't be a child if we're in a different world copy\n return false;\n }\n const zDifference = this.canonical.z - parent.canonical.z;\n // We're first testing for z == 0, to avoid a 32 bit shift, which is undefined.\n return parent.overscaledZ === 0 || (\n parent.overscaledZ < this.overscaledZ &&\n parent.canonical.x === (this.canonical.x >> zDifference) &&\n parent.canonical.y === (this.canonical.y >> zDifference));\n }\n\n children(sourceMaxZoom: number): Array<OverscaledTileID> {\n if (this.overscaledZ >= sourceMaxZoom) {\n // return a single tile coord representing a an overscaled tile\n return [new OverscaledTileID(this.overscaledZ + 1, this.wrap, this.canonical.z, this.canonical.x, this.canonical.y)];\n }\n\n const z = this.canonical.z + 1;\n const x = this.canonical.x * 2;\n const y = this.canonical.y * 2;\n return [\n new OverscaledTileID(z, this.wrap, z, x, y),\n new OverscaledTileID(z, this.wrap, z, x + 1, y),\n new OverscaledTileID(z, this.wrap, z, x, y + 1),\n new OverscaledTileID(z, this.wrap, z, x + 1, y + 1)\n ];\n }\n\n isLessThan(rhs: OverscaledTileID): boolean {\n if (this.wrap < rhs.wrap) return true;\n if (this.wrap > rhs.wrap) return false;\n\n if (this.overscaledZ < rhs.overscaledZ) return true;\n if (this.overscaledZ > rhs.overscaledZ) return false;\n\n if (this.canonical.x < rhs.canonical.x) return true;\n if (this.canonical.x > rhs.canonical.x) return false;\n\n if (this.canonical.y < rhs.canonical.y) return true;\n return false;\n }\n\n wrapped(): OverscaledTileID {\n return new OverscaledTileID(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y);\n }\n\n unwrapTo(wrap: number): OverscaledTileID {\n return new OverscaledTileID(this.overscaledZ, wrap, this.canonical.z, this.canonical.x, this.canonical.y);\n }\n\n overscaleFactor(): number {\n return Math.pow(2, this.overscaledZ - this.canonical.z);\n }\n\n toUnwrapped(): UnwrappedTileID {\n return new UnwrappedTileID(this.wrap, this.canonical);\n }\n\n toString(): string {\n return `${this.overscaledZ}/${this.canonical.x}/${this.canonical.y}`;\n }\n}\n\nfunction calculateKey(wrap: number, overscaledZ: number, z: number, x: number, y: number): number {\n // only use 22 bits for x & y so that the key fits into MAX_SAFE_INTEGER\n const dim = 1 << Math.min(z, 22);\n let xy = dim * (y % dim) + (x % dim);\n\n // zigzag-encode wrap if we have the room for it\n if (wrap && z < 22) {\n const bitsAvailable = 2 * (22 - z);\n xy += dim * dim * ((wrap < 0 ? -2 * wrap - 1 : 2 * wrap) % (1 << bitsAvailable));\n }\n\n // encode z into 5 bits (24 max) and overscaledZ into 4 bits (10 max)\n const key = ((xy * 32) + z) * 16 + (overscaledZ - z);\n assert(key >= 0 && key <= Number.MAX_SAFE_INTEGER);\n\n return key;\n}\n\nfunction getQuadkey(z: number, x: number, y: number) {\n let quadkey = '', mask;\n for (let i = z; i > 0; i--) {\n mask = 1 << (i - 1);\n quadkey += ((x & mask ? 1 : 0) + (y & mask ? 2 : 0));\n }\n return quadkey;\n}\n\nregister(CanonicalTileID, 'CanonicalTileID');\nregister(OverscaledTileID, 'OverscaledTileID', {omit: ['projMatrix']});\n","// @flow\n\nimport StyleLayer from '../style_layer.js';\nimport FillExtrusionBucket, {ELEVATION_SCALE, ELEVATION_OFFSET, fillExtrusionHeightLift, resampleFillExtrusionPolygonsForGlobe} from '../../data/bucket/fill_extrusion_bucket.js';\nimport {polygonIntersectsPolygon, polygonIntersectsMultiPolygon} from '../../util/intersection_tests.js';\nimport {translateDistance, tilespaceTranslate} from '../query_utils.js';\nimport properties from './fill_extrusion_style_layer_properties.js';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties.js';\nimport Point from '@mapbox/point-geometry';\nimport ProgramConfiguration from '../../data/program_configuration.js';\nimport {vec3, vec4} from 'gl-matrix';\nimport EXTENT from '../../data/extent.js';\nimport {CanonicalTileID} from '../../source/tile_id.js';\n\nimport type {FeatureState} from '../../style-spec/expression/index.js';\nimport type {BucketParameters} from '../../data/bucket.js';\nimport type {PaintProps, LayoutProps} from './fill_extrusion_style_layer_properties.js';\nimport type Transform from '../../geo/transform.js';\nimport type {LayerSpecification} from '../../style-spec/types.js';\nimport type {TilespaceQueryGeometry} from '../query_geometry.js';\nimport type {DEMSampler} from '../../terrain/elevation.js';\nimport type {Vec2, Vec4} from 'gl-matrix';\nimport type {IVectorTileFeature} from '@mapbox/vector-tile';\n\nclass Point3D extends Point {\n z: number;\n\n constructor(x: number, y: number, z: number) {\n super(x, y);\n this.z = z;\n }\n}\n\nclass FillExtrusionStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n layout: PossiblyEvaluated<LayoutProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n createBucket(parameters: BucketParameters<FillExtrusionStyleLayer>): FillExtrusionBucket {\n return new FillExtrusionBucket(parameters);\n }\n\n // $FlowFixMe[method-unbinding]\n queryRadius(): number {\n return translateDistance(this.paint.get('fill-extrusion-translate'));\n }\n\n is3D(): boolean {\n return true;\n }\n\n getProgramIds(): string[] {\n const patternProperty = this.paint.get('fill-extrusion-pattern');\n const image = patternProperty.constantOr((1: any));\n return [image ? 'fillExtrusionPattern' : 'fillExtrusion'];\n }\n\n getProgramConfiguration(zoom: number): ProgramConfiguration {\n return new ProgramConfiguration(this, zoom);\n }\n\n // $FlowFixMe[method-unbinding]\n queryIntersectsFeature(queryGeometry: TilespaceQueryGeometry,\n feature: IVectorTileFeature,\n featureState: FeatureState,\n geometry: Array<Array<Point>>,\n zoom: number,\n transform: Transform,\n pixelPosMatrix: Float32Array,\n elevationHelper: ?DEMSampler,\n layoutVertexArrayOffset: number): boolean | number {\n\n const translation = tilespaceTranslate(this.paint.get('fill-extrusion-translate'),\n this.paint.get('fill-extrusion-translate-anchor'),\n transform.angle,\n queryGeometry.pixelToTileUnitsFactor);\n const height = this.paint.get('fill-extrusion-height').evaluate(feature, featureState);\n const base = this.paint.get('fill-extrusion-base').evaluate(feature, featureState);\n\n const centroid = [0, 0];\n const terrainVisible = elevationHelper && transform.elevation;\n const exaggeration = transform.elevation ? transform.elevation.exaggeration() : 1;\n const bucket = queryGeometry.tile.getBucket(this);\n if (terrainVisible && bucket instanceof FillExtrusionBucket) {\n const centroidVertexArray = bucket.centroidVertexArray;\n\n // See FillExtrusionBucket#encodeCentroid(), centroid is inserted at vertexOffset + 1\n const centroidOffset = layoutVertexArrayOffset + 1;\n if (centroidOffset < centroidVertexArray.length) {\n centroid[0] = centroidVertexArray.geta_centroid_pos0(centroidOffset);\n centroid[1] = centroidVertexArray.geta_centroid_pos1(centroidOffset);\n }\n }\n\n // Early exit if fill extrusion is still hidden while waiting for backfill\n const isHidden = centroid[0] === 0 && centroid[1] === 1;\n if (isHidden) return false;\n\n if (transform.projection.name === 'globe') {\n // Fill extrusion geometry has to be resampled so that large planar polygons\n // can be rendered on the curved surface\n const bounds = [new Point(0, 0), new Point(EXTENT, EXTENT)];\n const resampledGeometry = resampleFillExtrusionPolygonsForGlobe([geometry], bounds, queryGeometry.tileID.canonical);\n geometry = resampledGeometry.map(clipped => clipped.polygon).flat();\n }\n\n const demSampler = terrainVisible ? elevationHelper : null;\n const [projectedBase, projectedTop] = projectExtrusion(transform, geometry, base, height, translation, pixelPosMatrix, demSampler, centroid, exaggeration, transform.center.lat, queryGeometry.tileID.canonical);\n\n const screenQuery = queryGeometry.queryGeometry;\n const projectedQueryGeometry = screenQuery.isPointQuery() ? screenQuery.screenBounds : screenQuery.screenGeometry;\n return checkIntersection(projectedBase, projectedTop, projectedQueryGeometry);\n }\n}\n\nfunction dot(a: Point, b: Point) {\n return a.x * b.x + a.y * b.y;\n}\n\nexport function getIntersectionDistance(projectedQueryGeometry: Array<Point>, projectedFace: Array<Point3D>): number {\n\n if (projectedQueryGeometry.length === 1) {\n // For point queries calculate the z at which the point intersects the face\n // using barycentric coordinates.\n\n // Find the barycentric coordinates of the projected point within the first\n // triangle of the face, using only the xy plane. It doesn't matter if the\n // point is outside the first triangle because all the triangles in the face\n // are in the same plane.\n //\n // Check whether points are coincident and use other points if they are.\n let i = 0;\n const a = projectedFace[i++];\n let b;\n while (!b || a.equals(b)) {\n b = projectedFace[i++];\n if (!b) return Infinity;\n }\n\n // Loop until point `c` is not colinear with points `a` and `b`.\n for (; i < projectedFace.length; i++) {\n const c = projectedFace[i];\n\n const p = projectedQueryGeometry[0];\n\n const ab = b.sub(a);\n const ac = c.sub(a);\n const ap = p.sub(a);\n\n const dotABAB = dot(ab, ab);\n const dotABAC = dot(ab, ac);\n const dotACAC = dot(ac, ac);\n const dotAPAB = dot(ap, ab);\n const dotAPAC = dot(ap, ac);\n const denom = dotABAB * dotACAC - dotABAC * dotABAC;\n\n const v = (dotACAC * dotAPAB - dotABAC * dotAPAC) / denom;\n const w = (dotABAB * dotAPAC - dotABAC * dotAPAB) / denom;\n const u = 1 - v - w;\n\n // Use the barycentric weighting along with the original triangle z coordinates to get the point of intersection.\n const distance = a.z * u + b.z * v + c.z * w;\n\n if (isFinite(distance)) return distance;\n }\n\n return Infinity;\n\n } else {\n // The counts as closest is less clear when the query is a box. This\n // returns the distance to the nearest point on the face, whether it is\n // within the query or not. It could be more correct to return the\n // distance to the closest point within the query box but this would be\n // more complicated and expensive to calculate with little benefit.\n let closestDistance = Infinity;\n for (const p of projectedFace) {\n closestDistance = Math.min(closestDistance, p.z);\n }\n return closestDistance;\n }\n}\n\nfunction checkIntersection(projectedBase: Array<Array<Point3D>>, projectedTop: Array<Array<Point3D>>, projectedQueryGeometry: Array<Point>) {\n let closestDistance = Infinity;\n\n if (polygonIntersectsMultiPolygon(projectedQueryGeometry, projectedTop)) {\n closestDistance = getIntersectionDistance(projectedQueryGeometry, projectedTop[0]);\n }\n\n for (let r = 0; r < projectedTop.length; r++) {\n const ringTop = projectedTop[r];\n const ringBase = projectedBase[r];\n for (let p = 0; p < ringTop.length - 1; p++) {\n const topA = ringTop[p];\n const topB = ringTop[p + 1];\n const baseA = ringBase[p];\n const baseB = ringBase[p + 1];\n const face = [topA, topB, baseB, baseA, topA];\n if (polygonIntersectsPolygon(projectedQueryGeometry, face)) {\n closestDistance = Math.min(closestDistance, getIntersectionDistance(projectedQueryGeometry, face));\n }\n }\n }\n\n return closestDistance === Infinity ? false : closestDistance;\n}\n\nfunction projectExtrusion(tr: Transform, geometry: Array<Array<Point>>, zBase: number, zTop: number, translation: Point, m: Float32Array, demSampler: ?DEMSampler, centroid: Vec2, exaggeration: number, lat: number, tileID: CanonicalTileID) {\n if (tr.projection.name === 'globe') {\n return projectExtrusionGlobe(tr, geometry, zBase, zTop, translation, m, demSampler, centroid, exaggeration, lat, tileID);\n } else {\n if (demSampler) {\n return projectExtrusion3D(geometry, zBase, zTop, translation, m, demSampler, centroid, exaggeration, lat);\n } else {\n return projectExtrusion2D(geometry, zBase, zTop, translation, m);\n }\n }\n}\n\nfunction projectExtrusionGlobe(tr: Transform, geometry: Array<Array<Point>>, zBase: number, zTop: number, translation: Point, m: Float32Array, demSampler: ?DEMSampler, centroid: Vec2, exaggeration: number, lat: number, tileID: CanonicalTileID) {\n const projectedBase = [];\n const projectedTop = [];\n const elevationScale = tr.projection.upVectorScale(tileID, tr.center.lat, tr.worldSize).metersToTile;\n const basePoint = [0, 0, 0, 1];\n const topPoint = [0, 0, 0, 1];\n\n const setPoint = (point: Array<number>, x: number, y: number, z: number) => {\n point[0] = x;\n point[1] = y;\n point[2] = z;\n point[3] = 1;\n };\n\n // Fixed \"lift\" value is added to height so that 0-height fill extrusions wont clip with globe's surface\n const lift = fillExtrusionHeightLift();\n\n if (zBase > 0) {\n zBase += lift;\n }\n zTop += lift;\n\n for (const r of geometry) {\n const ringBase = [];\n const ringTop = [];\n for (const p of r) {\n const x = p.x + translation.x;\n const y = p.y + translation.y;\n\n // Reproject tile coordinate into ecef and apply elevation to correct direction\n const reproj = tr.projection.projectTilePoint(x, y, tileID);\n const dir = tr.projection.upVector(tileID, p.x, p.y);\n\n let zBasePoint = zBase;\n let zTopPoint = zTop;\n\n if (demSampler) {\n const offset = getTerrainHeightOffset(x, y, zBase, zTop, demSampler, centroid, exaggeration, lat);\n\n zBasePoint += offset.base;\n zTopPoint += offset.top;\n }\n\n if (zBase !== 0) {\n setPoint(\n basePoint,\n reproj.x + dir[0] * elevationScale * zBasePoint,\n reproj.y + dir[1] * elevationScale * zBasePoint,\n reproj.z + dir[2] * elevationScale * zBasePoint);\n } else {\n setPoint(basePoint, reproj.x, reproj.y, reproj.z);\n }\n\n setPoint(\n topPoint,\n reproj.x + dir[0] * elevationScale * zTopPoint,\n reproj.y + dir[1] * elevationScale * zTopPoint,\n reproj.z + dir[2] * elevationScale * zTopPoint);\n\n vec3.transformMat4(basePoint, basePoint, m);\n vec3.transformMat4(topPoint, topPoint, m);\n\n ringBase.push(new Point3D(basePoint[0], basePoint[1], basePoint[2]));\n ringTop.push(new Point3D(topPoint[0], topPoint[1], topPoint[2]));\n }\n projectedBase.push(ringBase);\n projectedTop.push(ringTop);\n }\n\n return [projectedBase, projectedTop];\n}\n\n/*\n * Project the geometry using matrix `m`. This is essentially doing\n * `vec4.transformMat4([], [p.x, p.y, z, 1], m)` but the multiplication\n * is inlined so that parts of the projection that are the same across\n * different points can only be done once. This produced a measurable\n * performance improvement.\n */\nfunction projectExtrusion2D(geometry: Array<Array<Point>>, zBase: number, zTop: number, translation: Point, m: Float32Array) {\n const projectedBase = [];\n const projectedTop = [];\n\n const baseXZ = m[8] * zBase;\n const baseYZ = m[9] * zBase;\n const baseZZ = m[10] * zBase;\n const baseWZ = m[11] * zBase;\n const topXZ = m[8] * zTop;\n const topYZ = m[9] * zTop;\n const topZZ = m[10] * zTop;\n const topWZ = m[11] * zTop;\n\n for (const r of geometry) {\n const ringBase = [];\n const ringTop = [];\n for (const p of r) {\n const x = p.x + translation.x;\n const y = p.y + translation.y;\n\n const sX = m[0] * x + m[4] * y + m[12];\n const sY = m[1] * x + m[5] * y + m[13];\n const sZ = m[2] * x + m[6] * y + m[14];\n const sW = m[3] * x + m[7] * y + m[15];\n\n const baseX = sX + baseXZ;\n const baseY = sY + baseYZ;\n const baseZ = sZ + baseZZ;\n const baseW = Math.max(sW + baseWZ, 0.00001);\n\n const topX = sX + topXZ;\n const topY = sY + topYZ;\n const topZ = sZ + topZZ;\n const topW = Math.max(sW + topWZ, 0.00001);\n\n ringBase.push(new Point3D(baseX / baseW, baseY / baseW, baseZ / baseW));\n ringTop.push(new Point3D(topX / topW, topY / topW, topZ / topW));\n }\n projectedBase.push(ringBase);\n projectedTop.push(ringTop);\n }\n return [projectedBase, projectedTop];\n}\n\n/*\n * Projects a fill extrusion vertices to screen while accounting for terrain.\n * This and its dependent functions are ported directly from `fill_extrusion.vertex.glsl`\n * with a few co-ordinate space differences.\n *\n * - Matrix `m` projects to screen-pixel space instead of to gl-coordinates (NDC)\n * - Texture querying is performed in texture pixel coordinates instead of normalized uv coordinates.\n * - Height offset calculation for fill-extrusion-base is offset with -1 instead of -5 to prevent underground picking.\n */\nfunction projectExtrusion3D(geometry: Array<Array<Point>>, zBase: number, zTop: number, translation: Point, m: Float32Array, demSampler: DEMSampler, centroid: Vec2, exaggeration: number, lat: number) {\n const projectedBase = [];\n const projectedTop = [];\n const v = [0, 0, 0, 1];\n\n for (const r of geometry) {\n const ringBase = [];\n const ringTop = [];\n for (const p of r) {\n const x = p.x + translation.x;\n const y = p.y + translation.y;\n const heightOffset = getTerrainHeightOffset(x, y, zBase, zTop, demSampler, centroid, exaggeration, lat);\n\n v[0] = x;\n v[1] = y;\n v[2] = heightOffset.base;\n v[3] = 1;\n vec4.transformMat4(v, v, m);\n v[3] = Math.max(v[3], 0.00001);\n const base = new Point3D(v[0] / v[3], v[1] / v[3], v[2] / v[3]);\n\n v[0] = x;\n v[1] = y;\n v[2] = heightOffset.top;\n v[3] = 1;\n vec4.transformMat4(v, v, m);\n v[3] = Math.max(v[3], 0.00001);\n const top = new Point3D(v[0] / v[3], v[1] / v[3], v[2] / v[3]);\n\n ringBase.push(base);\n ringTop.push(top);\n }\n projectedBase.push(ringBase);\n projectedTop.push(ringTop);\n }\n return [projectedBase, projectedTop];\n}\n\nfunction getTerrainHeightOffset(x: number, y: number, zBase: number, zTop: number, demSampler: DEMSampler, centroid: Vec2, exaggeration: number, lat: number): { base: number, top: number} {\n const ele = exaggeration * demSampler.getElevationAt(x, y, true, true);\n const flatRoof = centroid[0] !== 0;\n const centroidElevation = flatRoof ? centroid[1] === 0 ? exaggeration * elevationFromUint16(centroid[0]) : exaggeration * flatElevation(demSampler, centroid, lat) : ele;\n return {\n base: ele + (zBase === 0) ? -1 : zBase, // Use -1 instead of -5 in shader to prevent picking underground\n top: flatRoof ? Math.max(centroidElevation + zTop, ele + zBase + 2) : ele + zTop\n };\n}\n\n// Elevation is encoded into unit16 in fill_extrusion_bucket.js FillExtrusionBucket#encodeCentroid\nfunction elevationFromUint16(n: number): number {\n return n / ELEVATION_SCALE - ELEVATION_OFFSET;\n}\n\n// Equivalent GPU side function is in _prelude_terrain.vertex.glsl\nfunction flatElevation(demSampler: DEMSampler, centroid: Vec2, lat: number): number {\n // Span and pos are packed two 16 bit uint16 values in fill_extrusion_bucket.js FillExtrusionBucket#encodeCentroid\n // pos is encoded by << by 3 bits thus dividing by 8 performs equivalent of right shifting it back.\n const posX = Math.floor(centroid[0] / 8);\n const posY = Math.floor(centroid[1] / 8);\n\n // Span is stored in the lower three bits in multiples of 10\n const spanX = 10 * (centroid[0] - posX * 8);\n const spanY = 10 * (centroid[1] - posY * 8);\n\n // Get height at centroid\n const z = demSampler.getElevationAt(posX, posY, true, true);\n const meterToDEM = demSampler.getMeterToDEM(lat);\n\n const wX = Math.floor(0.5 * (spanX * meterToDEM - 1));\n const wY = Math.floor(0.5 * (spanY * meterToDEM - 1));\n\n const posPx = demSampler.tileCoordToPixel(posX, posY);\n\n const offsetX = 2 * wX + 1;\n const offsetY = 2 * wY + 1;\n const corners = fourSample(demSampler, posPx.x - wX, posPx.y - wY, offsetX, offsetY);\n\n const diffX = Math.abs(corners[0] - corners[1]);\n const diffY = Math.abs(corners[2] - corners[3]);\n const diffZ = Math.abs(corners[0] - corners[2]);\n const diffW = Math.abs(corners[1] - corners[3]);\n\n const diffSumX = diffX + diffY;\n const diffSumY = diffZ + diffW;\n\n const slopeX = Math.min(0.25, meterToDEM * 0.5 * diffSumX / offsetX);\n const slopeY = Math.min(0.25, meterToDEM * 0.5 * diffSumY / offsetY);\n\n return z + Math.max(slopeX * spanX, slopeY * spanY);\n}\n\nfunction fourSample(demSampler: DEMSampler, posX: number, posY: number, offsetX: number, offsetY: number): Vec4 {\n return [\n demSampler.getElevationAtPixel(posX, posY, true),\n demSampler.getElevationAtPixel(posX + offsetY, posY, true),\n demSampler.getElevationAtPixel(posX, posY + offsetY, true),\n demSampler.getElevationAtPixel(posX + offsetX, posY + offsetY, true)\n ];\n}\n\nexport default FillExtrusionStyleLayer;\n","// @flow\nimport {createLayout} from '../../util/struct_array.js';\n\nimport type {StructArrayLayout} from '../../util/struct_array.js';\n\nconst lineLayoutAttributes: StructArrayLayout = createLayout([\n {name: 'a_pos_normal', components: 2, type: 'Int16'},\n {name: 'a_data', components: 4, type: 'Uint8'},\n {name: 'a_linesofar', components: 1, type: 'Float32'}\n], 4);\n\nexport default lineLayoutAttributes;\nexport const {members, size, alignment} = lineLayoutAttributes;\n","// @flow\nimport {createLayout} from '../../util/struct_array.js';\n\nimport type {StructArrayLayout} from '../../util/struct_array.js';\n\nconst lineLayoutAttributesExt: StructArrayLayout = createLayout([\n {name: 'a_packed', components: 4, type: 'Float32'}\n]);\n\nexport default lineLayoutAttributesExt;\nexport const {members, size, alignment} = lineLayoutAttributesExt;\n","// @flow\n\nimport {LineLayoutArray, LineExtLayoutArray} from '../array_types.js';\n\nimport {members as layoutAttributes} from './line_attributes.js';\nimport {members as layoutAttributesExt} from './line_attributes_ext.js';\nimport SegmentVector from '../segment.js';\nimport {ProgramConfigurationSet} from '../program_configuration.js';\nimport {TriangleIndexArray} from '../index_array_type.js';\nimport EXTENT from '../extent.js';\nimport {VectorTileFeature} from '@mapbox/vector-tile';\nconst vectorTileFeatureTypes = VectorTileFeature.types;\nimport {register} from '../../util/web_worker_transfer.js';\nimport {hasPattern, addPatternDependencies} from './pattern_bucket_features.js';\nimport loadGeometry from '../load_geometry.js';\nimport toEvaluationFeature from '../evaluation_feature.js';\nimport EvaluationParameters from '../../style/evaluation_parameters.js';\nimport type {ProjectionSpecification} from '../../style-spec/types.js';\nimport type {CanonicalTileID} from '../../source/tile_id.js';\nimport type {\n Bucket,\n BucketParameters,\n BucketFeature,\n IndexedFeature,\n PopulateParameters\n} from '../bucket.js';\nimport type LineStyleLayer from '../../style/style_layer/line_style_layer.js';\nimport type Point from '@mapbox/point-geometry';\nimport type {Segment} from '../segment.js';\nimport type {RGBAImage, SpritePositions} from '../../util/image.js';\nimport type Context from '../../gl/context.js';\nimport type Texture from '../../render/texture.js';\nimport type IndexBuffer from '../../gl/index_buffer.js';\nimport type VertexBuffer from '../../gl/vertex_buffer.js';\nimport type {FeatureStates} from '../../source/source_state.js';\nimport type LineAtlas from '../../render/line_atlas.js';\nimport type {TileTransform} from '../../geo/projection/tile_transform.js';\nimport type {IVectorTileLayer} from '@mapbox/vector-tile';\n\n// NOTE ON EXTRUDE SCALE:\n// scale the extrusion vector so that the normal length is this value.\n// contains the \"texture\" normals (-1..1). this is distinct from the extrude\n// normals for line joins, because the x-value remains 0 for the texture\n// normal array, while the extrude normal actually moves the vertex to create\n// the acute/bevelled line join.\nconst EXTRUDE_SCALE = 63;\n\n/*\n * Sharp corners cause dashed lines to tilt because the distance along the line\n * is the same at both the inner and outer corners. To improve the appearance of\n * dashed lines we add extra points near sharp corners so that a smaller part\n * of the line is tilted.\n *\n * COS_HALF_SHARP_CORNER controls how sharp a corner has to be for us to add an\n * extra vertex. The default is 75 degrees.\n *\n * The newly created vertices are placed SHARP_CORNER_OFFSET pixels from the corner.\n */\nconst COS_HALF_SHARP_CORNER = Math.cos(75 / 2 * (Math.PI / 180));\nconst SHARP_CORNER_OFFSET = 15;\n\n// Angle per triangle for approximating round line joins.\nconst DEG_PER_TRIANGLE = 20;\n\ntype LineClips = {\n start: number;\n end: number;\n}\n\ntype GradientTexture = {\n texture: Texture;\n gradient: ?RGBAImage;\n version: number;\n}\n\n/**\n * @private\n */\nclass LineBucket implements Bucket {\n distance: number;\n totalDistance: number;\n maxLineLength: number;\n scaledDistance: number;\n lineSoFar: number;\n lineClips: ?LineClips;\n\n e1: number;\n e2: number;\n\n index: number;\n zoom: number;\n overscaling: number;\n layers: Array<LineStyleLayer>;\n layerIds: Array<string>;\n gradients: {[string]: GradientTexture};\n stateDependentLayers: Array<any>;\n stateDependentLayerIds: Array<string>;\n patternFeatures: Array<BucketFeature>;\n lineClipsArray: Array<LineClips>;\n\n layoutVertexArray: LineLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n layoutVertexArray2: LineExtLayoutArray;\n layoutVertexBuffer2: VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n hasPattern: boolean;\n programConfigurations: ProgramConfigurationSet<LineStyleLayer>;\n segments: SegmentVector;\n uploaded: boolean;\n projection: ProjectionSpecification;\n\n constructor(options: BucketParameters<LineStyleLayer>) {\n this.zoom = options.zoom;\n this.overscaling = options.overscaling;\n this.layers = options.layers;\n this.layerIds = this.layers.map(layer => layer.id);\n this.index = options.index;\n this.projection = options.projection;\n this.hasPattern = false;\n this.patternFeatures = [];\n this.lineClipsArray = [];\n this.gradients = {};\n this.layers.forEach(layer => {\n this.gradients[layer.id] = {};\n });\n\n this.layoutVertexArray = new LineLayoutArray();\n this.layoutVertexArray2 = new LineExtLayoutArray();\n this.indexArray = new TriangleIndexArray();\n this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n this.segments = new SegmentVector();\n this.maxLineLength = 0;\n\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n }\n\n populate(features: Array<IndexedFeature>, options: PopulateParameters, canonical: CanonicalTileID, tileTransform: TileTransform) {\n this.hasPattern = hasPattern('line', this.layers, options);\n const lineSortKey = this.layers[0].layout.get('line-sort-key');\n const bucketFeatures = [];\n\n for (const {feature, id, index, sourceLayerIndex} of features) {\n const needGeometry = this.layers[0]._featureFilter.needGeometry;\n const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n\n // $FlowFixMe[method-unbinding]\n if (!this.layers[0]._featureFilter.filter(new EvaluationParameters(this.zoom), evaluationFeature, canonical)) continue;\n\n const sortKey = lineSortKey ?\n lineSortKey.evaluate(evaluationFeature, {}, canonical) :\n undefined;\n\n const bucketFeature: BucketFeature = {\n id,\n properties: feature.properties,\n type: feature.type,\n sourceLayerIndex,\n index,\n geometry: needGeometry ? evaluationFeature.geometry : loadGeometry(feature, canonical, tileTransform),\n patterns: {},\n sortKey\n };\n\n bucketFeatures.push(bucketFeature);\n }\n\n if (lineSortKey) {\n bucketFeatures.sort((a, b) => {\n // a.sortKey is always a number when in use\n return ((a.sortKey: any): number) - ((b.sortKey: any): number);\n });\n }\n\n const {lineAtlas, featureIndex} = options;\n const hasFeatureDashes = this.addConstantDashes(lineAtlas);\n\n for (const bucketFeature of bucketFeatures) {\n const {geometry, index, sourceLayerIndex} = bucketFeature;\n\n if (hasFeatureDashes) {\n this.addFeatureDashes(bucketFeature, lineAtlas);\n }\n\n if (this.hasPattern) {\n const patternBucketFeature = addPatternDependencies('line', this.layers, bucketFeature, this.zoom, options);\n // pattern features are added only once the pattern is loaded into the image atlas\n // so are stored during populate until later updated with positions by tile worker in addFeatures\n this.patternFeatures.push(patternBucketFeature);\n\n } else {\n this.addFeature(bucketFeature, geometry, index, canonical, lineAtlas.positions, options.availableImages);\n }\n\n const feature = features[index].feature;\n featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);\n }\n }\n\n addConstantDashes(lineAtlas: LineAtlas): boolean {\n let hasFeatureDashes = false;\n\n for (const layer of this.layers) {\n const dashPropertyValue = layer.paint.get('line-dasharray').value;\n const capPropertyValue = layer.layout.get('line-cap').value;\n\n if (dashPropertyValue.kind !== 'constant' || capPropertyValue.kind !== 'constant') {\n hasFeatureDashes = true;\n\n } else {\n const constCap = capPropertyValue.value;\n const constDash = dashPropertyValue.value;\n if (!constDash) continue;\n lineAtlas.addDash(constDash, constCap);\n }\n }\n\n return hasFeatureDashes;\n }\n\n addFeatureDashes(feature: BucketFeature, lineAtlas: LineAtlas) {\n\n const zoom = this.zoom;\n\n for (const layer of this.layers) {\n const dashPropertyValue = layer.paint.get('line-dasharray').value;\n const capPropertyValue = layer.layout.get('line-cap').value;\n\n if (dashPropertyValue.kind === 'constant' && capPropertyValue.kind === 'constant') continue;\n\n let dashArray, cap;\n\n if (dashPropertyValue.kind === 'constant') {\n dashArray = dashPropertyValue.value;\n if (!dashArray) continue;\n\n } else {\n dashArray = dashPropertyValue.evaluate({zoom}, feature);\n }\n\n if (capPropertyValue.kind === 'constant') {\n cap = capPropertyValue.value;\n\n } else {\n cap = capPropertyValue.evaluate({zoom}, feature);\n }\n\n lineAtlas.addDash(dashArray, cap);\n\n // save positions for paint array\n feature.patterns[layer.id] = lineAtlas.getKey(dashArray, cap);\n }\n\n }\n\n update(states: FeatureStates, vtLayer: IVectorTileLayer, availableImages: Array<string>, imagePositions: SpritePositions) {\n if (!this.stateDependentLayers.length) return;\n this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, availableImages, imagePositions);\n }\n\n addFeatures(options: PopulateParameters, canonical: CanonicalTileID, imagePositions: SpritePositions, availableImages: Array<string>, _: TileTransform) {\n for (const feature of this.patternFeatures) {\n this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions, availableImages);\n }\n }\n\n isEmpty(): boolean {\n return this.layoutVertexArray.length === 0;\n }\n\n uploadPending(): boolean {\n return !this.uploaded || this.programConfigurations.needsUpload;\n }\n\n upload(context: Context) {\n if (!this.uploaded) {\n if (this.layoutVertexArray2.length !== 0) {\n this.layoutVertexBuffer2 = context.createVertexBuffer(this.layoutVertexArray2, layoutAttributesExt);\n }\n this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, layoutAttributes);\n this.indexBuffer = context.createIndexBuffer(this.indexArray);\n }\n this.programConfigurations.upload(context);\n this.uploaded = true;\n }\n\n destroy() {\n if (!this.layoutVertexBuffer) return;\n this.layoutVertexBuffer.destroy();\n this.indexBuffer.destroy();\n this.programConfigurations.destroy();\n this.segments.destroy();\n }\n\n lineFeatureClips(feature: BucketFeature): ?LineClips {\n if (!!feature.properties && feature.properties.hasOwnProperty('mapbox_clip_start') && feature.properties.hasOwnProperty('mapbox_clip_end')) {\n const start = +feature.properties['mapbox_clip_start'];\n const end = +feature.properties['mapbox_clip_end'];\n return {start, end};\n }\n }\n\n addFeature(feature: BucketFeature, geometry: Array<Array<Point>>, index: number, canonical: CanonicalTileID, imagePositions: SpritePositions, availableImages: Array<string>) {\n const layout = this.layers[0].layout;\n const join = layout.get('line-join').evaluate(feature, {});\n const cap = layout.get('line-cap').evaluate(feature, {});\n const miterLimit = layout.get('line-miter-limit');\n const roundLimit = layout.get('line-round-limit');\n this.lineClips = this.lineFeatureClips(feature);\n\n for (const line of geometry) {\n this.addLine(line, feature, join, cap, miterLimit, roundLimit);\n }\n\n this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, availableImages, canonical);\n }\n\n addLine(vertices: Array<Point>, feature: BucketFeature, join: string, cap: string, miterLimit: number, roundLimit: number) {\n this.distance = 0;\n this.scaledDistance = 0;\n this.totalDistance = 0;\n this.lineSoFar = 0;\n\n if (this.lineClips) {\n this.lineClipsArray.push(this.lineClips);\n // Calculate the total distance, in tile units, of this tiled line feature\n for (let i = 0; i < vertices.length - 1; i++) {\n this.totalDistance += vertices[i].dist(vertices[i + 1]);\n }\n this.updateScaledDistance();\n this.maxLineLength = Math.max(this.maxLineLength, this.totalDistance);\n }\n\n const isPolygon = vectorTileFeatureTypes[feature.type] === 'Polygon';\n\n // If the line has duplicate vertices at the ends, adjust start/length to remove them.\n let len = vertices.length;\n while (len >= 2 && vertices[len - 1].equals(vertices[len - 2])) {\n len--;\n }\n let first = 0;\n while (first < len - 1 && vertices[first].equals(vertices[first + 1])) {\n first++;\n }\n\n // Ignore invalid geometry.\n if (len < (isPolygon ? 3 : 2)) return;\n\n if (join === 'bevel') miterLimit = 1.05;\n\n const sharpCornerOffset = this.overscaling <= 16 ?\n SHARP_CORNER_OFFSET * EXTENT / (512 * this.overscaling) :\n 0;\n\n // we could be more precise, but it would only save a negligible amount of space\n const segment = this.segments.prepareSegment(len * 10, this.layoutVertexArray, this.indexArray);\n\n let currentVertex;\n let prevVertex = ((undefined: any): Point);\n let nextVertex = ((undefined: any): Point);\n let prevNormal = ((undefined: any): Point);\n let nextNormal = ((undefined: any): Point);\n\n // the last two vertices added\n this.e1 = this.e2 = -1;\n\n if (isPolygon) {\n currentVertex = vertices[len - 2];\n nextNormal = vertices[first].sub(currentVertex)._unit()._perp();\n }\n\n for (let i = first; i < len; i++) {\n\n nextVertex = i === len - 1 ?\n (isPolygon ? vertices[first + 1] : (undefined: any)) : // if it's a polygon, treat the last vertex like the first\n vertices[i + 1]; // just the next vertex\n\n // if two consecutive vertices exist, skip the current one\n if (nextVertex && vertices[i].equals(nextVertex)) continue;\n\n if (nextNormal) prevNormal = nextNormal;\n if (currentVertex) prevVertex = currentVertex;\n\n currentVertex = vertices[i];\n\n // Calculate the normal towards the next vertex in this line. In case\n // there is no next vertex, pretend that the line is continuing straight,\n // meaning that we are just using the previous normal.\n nextNormal = nextVertex ? nextVertex.sub(currentVertex)._unit()._perp() : prevNormal;\n\n // If we still don't have a previous normal, this is the beginning of a\n // non-closed line, so we're doing a straight \"join\".\n prevNormal = prevNormal || nextNormal;\n\n // Determine the normal of the join extrusion. It is the angle bisector\n // of the segments between the previous line and the next line.\n // In the case of 180° angles, the prev and next normals cancel each other out:\n // prevNormal + nextNormal = (0, 0), its magnitude is 0, so the unit vector would be\n // undefined. In that case, we're keeping the joinNormal at (0, 0), so that the cosHalfAngle\n // below will also become 0 and miterLength will become Infinity.\n let joinNormal = prevNormal.add(nextNormal);\n if (joinNormal.x !== 0 || joinNormal.y !== 0) {\n joinNormal._unit();\n }\n /* joinNormal prevNormal\n * ↖ ↑\n * .________. prevVertex\n * |\n * nextNormal ← | currentVertex\n * |\n * nextVertex !\n *\n */\n\n // calculate cosines of the angle (and its half) using dot product\n const cosAngle = prevNormal.x * nextNormal.x + prevNormal.y * nextNormal.y;\n const cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y;\n\n // Calculate the length of the miter (the ratio of the miter to the width)\n // as the inverse of cosine of the angle between next and join normals\n const miterLength = cosHalfAngle !== 0 ? 1 / cosHalfAngle : Infinity;\n\n // approximate angle from cosine\n const approxAngle = 2 * Math.sqrt(2 - 2 * cosHalfAngle);\n\n const isSharpCorner = cosHalfAngle < COS_HALF_SHARP_CORNER && prevVertex && nextVertex;\n const lineTurnsLeft = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0;\n\n if (isSharpCorner && i > first) {\n const prevSegmentLength = currentVertex.dist(prevVertex);\n if (prevSegmentLength > 2 * sharpCornerOffset) {\n const newPrevVertex = currentVertex.sub(currentVertex.sub(prevVertex)._mult(sharpCornerOffset / prevSegmentLength)._round());\n this.updateDistance(prevVertex, newPrevVertex);\n this.addCurrentVertex(newPrevVertex, prevNormal, 0, 0, segment);\n prevVertex = newPrevVertex;\n }\n }\n\n // The join if a middle vertex, otherwise the cap.\n const middleVertex = prevVertex && nextVertex;\n let currentJoin = middleVertex ? join : isPolygon ? 'butt' : cap;\n\n if (middleVertex && currentJoin === 'round') {\n if (miterLength < roundLimit) {\n currentJoin = 'miter';\n } else if (miterLength <= 2) {\n currentJoin = 'fakeround';\n }\n }\n\n if (currentJoin === 'miter' && miterLength > miterLimit) {\n currentJoin = 'bevel';\n }\n\n if (currentJoin === 'bevel') {\n // The maximum extrude length is 128 / 63 = 2 times the width of the line\n // so if miterLength >= 2 we need to draw a different type of bevel here.\n if (miterLength > 2) currentJoin = 'flipbevel';\n\n // If the miterLength is really small and the line bevel wouldn't be visible,\n // just draw a miter join to save a triangle.\n if (miterLength < miterLimit) currentJoin = 'miter';\n }\n\n // Calculate how far along the line the currentVertex is\n if (prevVertex) this.updateDistance(prevVertex, currentVertex);\n\n if (currentJoin === 'miter') {\n\n joinNormal._mult(miterLength);\n this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment);\n\n } else if (currentJoin === 'flipbevel') {\n // miter is too big, flip the direction to make a beveled join\n\n if (miterLength > 100) {\n // Almost parallel lines\n joinNormal = nextNormal.mult(-1);\n\n } else {\n const bevelLength = miterLength * prevNormal.add(nextNormal).mag() / prevNormal.sub(nextNormal).mag();\n joinNormal._perp()._mult(bevelLength * (lineTurnsLeft ? -1 : 1));\n }\n this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment);\n this.addCurrentVertex(currentVertex, joinNormal.mult(-1), 0, 0, segment);\n\n } else if (currentJoin === 'bevel' || currentJoin === 'fakeround') {\n const offset = -Math.sqrt(miterLength * miterLength - 1);\n const offsetA = lineTurnsLeft ? offset : 0;\n const offsetB = lineTurnsLeft ? 0 : offset;\n\n // Close previous segment with a bevel\n if (prevVertex) {\n this.addCurrentVertex(currentVertex, prevNormal, offsetA, offsetB, segment);\n }\n\n if (currentJoin === 'fakeround') {\n // The join angle is sharp enough that a round join would be visible.\n // Bevel joins fill the gap between segments with a single pie slice triangle.\n // Create a round join by adding multiple pie slices. The join isn't actually round, but\n // it looks like it is at the sizes we render lines at.\n\n // pick the number of triangles for approximating round join by based on the angle between normals\n const n = Math.round((approxAngle * 180 / Math.PI) / DEG_PER_TRIANGLE);\n\n for (let m = 1; m < n; m++) {\n let t = m / n;\n if (t !== 0.5) {\n // approximate spherical interpolation https://observablehq.com/@mourner/approximating-geometric-slerp\n const t2 = t - 0.5;\n const A = 1.0904 + cosAngle * (-3.2452 + cosAngle * (3.55645 - cosAngle * 1.43519));\n const B = 0.848013 + cosAngle * (-1.06021 + cosAngle * 0.215638);\n t = t + t * t2 * (t - 1) * (A * t2 * t2 + B);\n }\n const extrude = nextNormal.sub(prevNormal)._mult(t)._add(prevNormal)._unit()._mult(lineTurnsLeft ? -1 : 1);\n this.addHalfVertex(currentVertex, extrude.x, extrude.y, false, lineTurnsLeft, 0, segment);\n }\n }\n\n if (nextVertex) {\n // Start next segment\n this.addCurrentVertex(currentVertex, nextNormal, -offsetA, -offsetB, segment);\n }\n\n } else if (currentJoin === 'butt') {\n this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); // butt cap\n\n } else if (currentJoin === 'square') {\n const offset = prevVertex ? 1 : -1; // closing or starting square cap\n\n if (!prevVertex) {\n this.addCurrentVertex(currentVertex, joinNormal, offset, offset, segment);\n }\n\n // make the cap it's own quad to avoid the cap affecting the line distance\n this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment);\n\n if (prevVertex) {\n this.addCurrentVertex(currentVertex, joinNormal, offset, offset, segment);\n }\n\n } else if (currentJoin === 'round') {\n\n if (prevVertex) {\n // Close previous segment with butt\n this.addCurrentVertex(currentVertex, prevNormal, 0, 0, segment);\n\n // Add round cap or linejoin at end of segment\n this.addCurrentVertex(currentVertex, prevNormal, 1, 1, segment, true);\n }\n if (nextVertex) {\n // Add round cap before first segment\n this.addCurrentVertex(currentVertex, nextNormal, -1, -1, segment, true);\n\n // Start next segment with a butt\n this.addCurrentVertex(currentVertex, nextNormal, 0, 0, segment);\n }\n }\n\n if (isSharpCorner && i < len - 1) {\n const nextSegmentLength = currentVertex.dist(nextVertex);\n if (nextSegmentLength > 2 * sharpCornerOffset) {\n const newCurrentVertex = currentVertex.add(nextVertex.sub(currentVertex)._mult(sharpCornerOffset / nextSegmentLength)._round());\n this.updateDistance(currentVertex, newCurrentVertex);\n this.addCurrentVertex(newCurrentVertex, nextNormal, 0, 0, segment);\n currentVertex = newCurrentVertex;\n }\n }\n }\n }\n\n /**\n * Add two vertices to the buffers.\n *\n * @param p the line vertex to add buffer vertices for\n * @param normal vertex normal\n * @param endLeft extrude to shift the left vertex along the line\n * @param endRight extrude to shift the left vertex along the line\n * @param segment the segment object to add the vertex to\n * @param round whether this is a round cap\n * @private\n */\n addCurrentVertex(p: Point, normal: Point, endLeft: number, endRight: number, segment: Segment, round: boolean = false) {\n // left and right extrude vectors, perpendicularly shifted by endLeft/endRight\n const leftX = normal.x + normal.y * endLeft;\n const leftY = normal.y - normal.x * endLeft;\n const rightX = -normal.x + normal.y * endRight;\n const rightY = -normal.y - normal.x * endRight;\n\n this.addHalfVertex(p, leftX, leftY, round, false, endLeft, segment);\n this.addHalfVertex(p, rightX, rightY, round, true, -endRight, segment);\n }\n\n addHalfVertex({x, y}: Point, extrudeX: number, extrudeY: number, round: boolean, up: boolean, dir: number, segment: Segment) {\n this.layoutVertexArray.emplaceBack(\n // a_pos_normal\n // Encode round/up the least significant bits\n (x << 1) + (round ? 1 : 0),\n (y << 1) + (up ? 1 : 0),\n // a_data\n // add 128 to store a byte in an unsigned byte\n Math.round(EXTRUDE_SCALE * extrudeX) + 128,\n Math.round(EXTRUDE_SCALE * extrudeY) + 128,\n ((dir === 0 ? 0 : (dir < 0 ? -1 : 1)) + 1),\n 0, // unused\n // a_linesofar\n this.lineSoFar);\n\n // Constructs a second vertex buffer with higher precision line progress\n if (this.lineClips) {\n this.layoutVertexArray2.emplaceBack(this.scaledDistance, this.lineClipsArray.length, this.lineClips.start, this.lineClips.end);\n }\n\n const e = segment.vertexLength++;\n if (this.e1 >= 0 && this.e2 >= 0) {\n this.indexArray.emplaceBack(this.e1, this.e2, e);\n segment.primitiveLength++;\n }\n if (up) {\n this.e2 = e;\n } else {\n this.e1 = e;\n }\n }\n\n updateScaledDistance() {\n // Knowing the ratio of the full linestring covered by this tiled feature, as well\n // as the total distance (in tile units) of this tiled feature, and the distance\n // (in tile units) of the current vertex, we can determine the relative distance\n // of this vertex along the full linestring feature.\n if (this.lineClips) {\n const featureShare = this.lineClips.end - this.lineClips.start;\n const totalFeatureLength = this.totalDistance / featureShare;\n this.scaledDistance = this.distance / this.totalDistance;\n this.lineSoFar = totalFeatureLength * this.lineClips.start + this.distance;\n } else {\n this.lineSoFar = this.distance;\n }\n }\n\n updateDistance(prev: Point, next: Point) {\n this.distance += prev.dist(next);\n this.updateScaledDistance();\n }\n}\n\nregister(LineBucket, 'LineBucket', {omit: ['layers', 'patternFeatures']});\n\nexport default LineBucket;\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest.js';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n ColorRampProperty\n} from '../properties.js';\n\nimport type Color from '../../style-spec/util/color.js';\n\nimport type Formatted from '../../style-spec/expression/types/formatted.js';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image.js';\n\nexport type LayoutProps = {|\n \"line-cap\": DataDrivenProperty<\"butt\" | \"round\" | \"square\">,\n \"line-join\": DataDrivenProperty<\"bevel\" | \"round\" | \"miter\">,\n \"line-miter-limit\": DataConstantProperty<number>,\n \"line-round-limit\": DataConstantProperty<number>,\n \"line-sort-key\": DataDrivenProperty<number>,\n|};\n\nconst layout: Properties<LayoutProps> = new Properties({\n \"line-cap\": new DataDrivenProperty(styleSpec[\"layout_line\"][\"line-cap\"]),\n \"line-join\": new DataDrivenProperty(styleSpec[\"layout_line\"][\"line-join\"]),\n \"line-miter-limit\": new DataConstantProperty(styleSpec[\"layout_line\"][\"line-miter-limit\"]),\n \"line-round-limit\": new DataConstantProperty(styleSpec[\"layout_line\"][\"line-round-limit\"]),\n \"line-sort-key\": new DataDrivenProperty(styleSpec[\"layout_line\"][\"line-sort-key\"]),\n});\n\nexport type PaintProps = {|\n \"line-opacity\": DataDrivenProperty<number>,\n \"line-color\": DataDrivenProperty<Color>,\n \"line-translate\": DataConstantProperty<[number, number]>,\n \"line-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"line-width\": DataDrivenProperty<number>,\n \"line-gap-width\": DataDrivenProperty<number>,\n \"line-offset\": DataDrivenProperty<number>,\n \"line-blur\": DataDrivenProperty<number>,\n \"line-dasharray\": DataDrivenProperty<?Array<number>>,\n \"line-pattern\": DataDrivenProperty<?ResolvedImage>,\n \"line-gradient\": ColorRampProperty,\n \"line-trim-offset\": DataConstantProperty<[number, number]>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"line-opacity\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-opacity\"]),\n \"line-color\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-color\"]),\n \"line-translate\": new DataConstantProperty(styleSpec[\"paint_line\"][\"line-translate\"]),\n \"line-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_line\"][\"line-translate-anchor\"]),\n \"line-width\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-width\"]),\n \"line-gap-width\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-gap-width\"]),\n \"line-offset\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-offset\"]),\n \"line-blur\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-blur\"]),\n \"line-dasharray\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-dasharray\"]),\n \"line-pattern\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-pattern\"]),\n \"line-gradient\": new ColorRampProperty(styleSpec[\"paint_line\"][\"line-gradient\"]),\n \"line-trim-offset\": new DataConstantProperty(styleSpec[\"paint_line\"][\"line-trim-offset\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint, layout }: $Exact<{\n paint: Properties<PaintProps>, layout: Properties<LayoutProps>\n}>);\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport StyleLayer from '../style_layer.js';\nimport LineBucket from '../../data/bucket/line_bucket.js';\nimport {polygonIntersectsBufferedMultiLine} from '../../util/intersection_tests.js';\nimport {getMaximumPaintValue, translateDistance, translate} from '../query_utils.js';\nimport properties from './line_style_layer_properties.js';\nimport {extend} from '../../util/util.js';\nimport EvaluationParameters from '../evaluation_parameters.js';\nimport {Transitionable, Transitioning, Layout, PossiblyEvaluated, DataDrivenProperty} from '../properties.js';\nimport ProgramConfiguration from '../../data/program_configuration.js';\n\nimport Step from '../../style-spec/expression/definitions/step.js';\nimport type {PossiblyEvaluatedValue, PropertyValue, PossiblyEvaluatedPropertyValue} from '../properties.js';\nimport type {Feature, FeatureState, ZoomConstantExpression, StylePropertyExpression} from '../../style-spec/expression/index.js';\nimport type {Bucket, BucketParameters} from '../../data/bucket.js';\nimport type {LayoutProps, PaintProps} from './line_style_layer_properties.js';\nimport type Transform from '../../geo/transform.js';\nimport type {LayerSpecification} from '../../style-spec/types.js';\nimport type {TilespaceQueryGeometry} from '../query_geometry.js';\nimport type {IVectorTileFeature} from '@mapbox/vector-tile';\n\nclass LineFloorwidthProperty extends DataDrivenProperty<number> {\n useIntegerZoom: ?boolean;\n\n possiblyEvaluate(value: PropertyValue<number, PossiblyEvaluatedPropertyValue<number>>, parameters: EvaluationParameters): PossiblyEvaluatedPropertyValue<number> {\n parameters = new EvaluationParameters(Math.floor(parameters.zoom), {\n now: parameters.now,\n fadeDuration: parameters.fadeDuration,\n transition: parameters.transition\n });\n return super.possiblyEvaluate(value, parameters);\n }\n\n evaluate(value: PossiblyEvaluatedValue<number>, globals: EvaluationParameters, feature: Feature, featureState: FeatureState): number {\n globals = extend({}, globals, {zoom: Math.floor(globals.zoom)});\n return super.evaluate(value, globals, feature, featureState);\n }\n}\n\nconst lineFloorwidthProperty = new LineFloorwidthProperty(properties.paint.properties['line-width'].specification);\nlineFloorwidthProperty.useIntegerZoom = true;\n\nclass LineStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout<LayoutProps>;\n layout: PossiblyEvaluated<LayoutProps>;\n\n gradientVersion: number;\n stepInterpolant: boolean;\n\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n this.gradientVersion = 0;\n }\n\n _handleSpecialPaintPropertyUpdate(name: string) {\n if (name === 'line-gradient') {\n const expression: ZoomConstantExpression<'source'> = ((this._transitionablePaint._values['line-gradient'].value.expression): any);\n this.stepInterpolant = expression._styleExpression && expression._styleExpression.expression instanceof Step;\n this.gradientVersion = (this.gradientVersion + 1) % Number.MAX_SAFE_INTEGER;\n }\n }\n\n gradientExpression(): StylePropertyExpression {\n return this._transitionablePaint._values['line-gradient'].value.expression;\n }\n\n widthExpression(): StylePropertyExpression {\n return this._transitionablePaint._values['line-width'].value.expression;\n }\n\n recalculate(parameters: EvaluationParameters, availableImages: Array<string>) {\n super.recalculate(parameters, availableImages);\n\n (this.paint._values: any)['line-floorwidth'] =\n lineFloorwidthProperty.possiblyEvaluate(this._transitioningPaint._values['line-width'].value, parameters);\n }\n\n createBucket(parameters: BucketParameters<LineStyleLayer>): LineBucket {\n return new LineBucket(parameters);\n }\n\n getProgramIds(): string[] {\n const patternProperty = this.paint.get('line-pattern');\n const image = patternProperty.constantOr((1: any));\n const programId = image ? 'linePattern' : 'line';\n return [programId];\n }\n\n getProgramConfiguration(zoom: number): ProgramConfiguration {\n return new ProgramConfiguration(this, zoom);\n }\n\n // $FlowFixMe[method-unbinding]\n queryRadius(bucket: Bucket): number {\n const lineBucket: LineBucket = (bucket: any);\n const width = getLineWidth(\n getMaximumPaintValue('line-width', this, lineBucket),\n getMaximumPaintValue('line-gap-width', this, lineBucket));\n const offset = getMaximumPaintValue('line-offset', this, lineBucket);\n return width / 2 + Math.abs(offset) + translateDistance(this.paint.get('line-translate'));\n }\n\n // $FlowFixMe[method-unbinding]\n queryIntersectsFeature(queryGeometry: TilespaceQueryGeometry,\n feature: IVectorTileFeature,\n featureState: FeatureState,\n geometry: Array<Array<Point>>,\n zoom: number,\n transform: Transform): boolean {\n if (queryGeometry.queryGeometry.isAboveHorizon) return false;\n\n const translatedPolygon = translate(queryGeometry.tilespaceGeometry,\n this.paint.get('line-translate'),\n this.paint.get('line-translate-anchor'),\n transform.angle, queryGeometry.pixelToTileUnitsFactor);\n const halfWidth = queryGeometry.pixelToTileUnitsFactor / 2 * getLineWidth(\n this.paint.get('line-width').evaluate(feature, featureState),\n this.paint.get('line-gap-width').evaluate(feature, featureState));\n const lineOffset = this.paint.get('line-offset').evaluate(feature, featureState);\n if (lineOffset) {\n geometry = offsetLine(geometry, lineOffset * queryGeometry.pixelToTileUnitsFactor);\n }\n\n return polygonIntersectsBufferedMultiLine(translatedPolygon, geometry, halfWidth);\n }\n\n isTileClipped(): boolean {\n return true;\n }\n}\n\nexport default LineStyleLayer;\n\nfunction getLineWidth(lineWidth: number, lineGapWidth: number) {\n if (lineGapWidth > 0) {\n return lineGapWidth + 2 * lineWidth;\n } else {\n return lineWidth;\n }\n}\n\nfunction offsetLine(rings: Array<Array<Point>>, offset: number) {\n const newRings = [];\n const zero = new Point(0, 0);\n for (let k = 0; k < rings.length; k++) {\n const ring = rings[k];\n const newRing = [];\n for (let i = 0; i < ring.length; i++) {\n const a = ring[i - 1];\n const b = ring[i];\n const c = ring[i + 1];\n const aToB = i === 0 ? zero : b.sub(a)._unit()._perp();\n const bToC = i === ring.length - 1 ? zero : c.sub(b)._unit()._perp();\n const extrude = aToB._add(bToC)._unit();\n\n const cosHalfAngle = extrude.x * bToC.x + extrude.y * bToC.y;\n extrude._mult(1 / cosHalfAngle);\n\n newRing.push(extrude._mult(offset)._add(b));\n }\n newRings.push(newRing);\n }\n return newRings;\n}\n","// @flow\nimport {createLayout} from '../../util/struct_array.js';\n\nimport type {StructArrayLayout} from '../../util/struct_array.js';\n\nexport const symbolLayoutAttributes: StructArrayLayout = createLayout([\n {name: 'a_pos_offset', components: 4, type: 'Int16'},\n {name: 'a_tex_size', components: 4, type: 'Uint16'},\n {name: 'a_pixeloffset', components: 4, type: 'Int16'}\n], 4);\n\nexport const symbolGlobeExtAttributes: StructArrayLayout = createLayout([\n {name: 'a_globe_anchor', components: 3, type: 'Int16'},\n {name: 'a_globe_normal', components: 3, type: 'Float32'},\n], 4);\n\nexport const dynamicLayoutAttributes: StructArrayLayout = createLayout([\n {name: 'a_projected_pos', components: 4, type: 'Float32'}\n], 4);\n\nexport const placementOpacityAttributes: StructArrayLayout = createLayout([\n {name: 'a_fade_opacity', components: 1, type: 'Uint32'}\n], 4);\n\nexport const collisionVertexAttributes: StructArrayLayout = createLayout([\n {name: 'a_placed', components: 2, type: 'Uint8'},\n {name: 'a_shift', components: 2, type: 'Float32'},\n]);\n\nexport const collisionVertexAttributesExt: StructArrayLayout = createLayout([\n {name: 'a_size_scale', components: 1, type: 'Float32'},\n {name: 'a_padding', components: 2, type: 'Float32'},\n]);\n\nexport const collisionBox: StructArrayLayout = createLayout([\n // the box is centered around the anchor point\n {type: 'Int16', name: 'projectedAnchorX'},\n {type: 'Int16', name: 'projectedAnchorY'},\n {type: 'Int16', name: 'projectedAnchorZ'},\n\n {type: 'Int16', name: 'tileAnchorX'},\n {type: 'Int16', name: 'tileAnchorY'},\n\n // distances to the edges from the anchor\n {type: 'Float32', name: 'x1'},\n {type: 'Float32', name: 'y1'},\n {type: 'Float32', name: 'x2'},\n {type: 'Float32', name: 'y2'},\n\n {type: 'Int16', name: 'padding'},\n\n // the index of the feature in the original vectortile\n {type: 'Uint32', name: 'featureIndex'},\n // the source layer the feature appears in\n {type: 'Uint16', name: 'sourceLayerIndex'},\n // the bucket the feature appears in\n {type: 'Uint16', name: 'bucketIndex'},\n]);\n\nexport const collisionBoxLayout: StructArrayLayout = createLayout([ // used to render collision boxes for debugging purposes\n {name: 'a_pos', components: 3, type: 'Int16'},\n {name: 'a_anchor_pos', components: 2, type: 'Int16'},\n {name: 'a_extrude', components: 2, type: 'Int16'}\n], 4);\n\nexport const collisionCircleLayout: StructArrayLayout = createLayout([ // used to render collision circles for debugging purposes\n {name: 'a_pos_2f', components: 2, type: 'Float32'},\n {name: 'a_radius', components: 1, type: 'Float32'},\n {name: 'a_flags', components: 2, type: 'Int16'}\n], 4);\n\nexport const quadTriangle: StructArrayLayout = createLayout([\n {name: 'triangle', components: 3, type: 'Uint16'},\n]);\n\nexport const placement: StructArrayLayout = createLayout([\n {type: 'Int16', name: 'projectedAnchorX'},\n {type: 'Int16', name: 'projectedAnchorY'},\n {type: 'Int16', name: 'projectedAnchorZ'},\n {type: 'Float32', name: 'tileAnchorX'},\n {type: 'Float32', name: 'tileAnchorY'},\n {type: 'Uint16', name: 'glyphStartIndex'},\n {type: 'Uint16', name: 'numGlyphs'},\n {type: 'Uint32', name: 'vertexStartIndex'},\n {type: 'Uint32', name: 'lineStartIndex'},\n {type: 'Uint32', name: 'lineLength'},\n {type: 'Uint16', name: 'segment'},\n {type: 'Uint16', name: 'lowerSize'},\n {type: 'Uint16', name: 'upperSize'},\n {type: 'Float32', name: 'lineOffsetX'},\n {type: 'Float32', name: 'lineOffsetY'},\n {type: 'Uint8', name: 'writingMode'},\n {type: 'Uint8', name: 'placedOrientation'},\n {type: 'Uint8', name: 'hidden'},\n {type: 'Uint32', name: 'crossTileID'},\n {type: 'Int16', name: 'associatedIconIndex'},\n {type: 'Uint8', name: 'flipState'}\n]);\n\nexport const symbolInstance: StructArrayLayout = createLayout([\n {type: 'Int16', name: 'projectedAnchorX'},\n {type: 'Int16', name: 'projectedAnchorY'},\n {type: 'Int16', name: 'projectedAnchorZ'},\n {type: 'Float32', name: 'tileAnchorX'},\n {type: 'Float32', name: 'tileAnchorY'},\n {type: 'Int16', name: 'rightJustifiedTextSymbolIndex'},\n {type: 'Int16', name: 'centerJustifiedTextSymbolIndex'},\n {type: 'Int16', name: 'leftJustifiedTextSymbolIndex'},\n {type: 'Int16', name: 'verticalPlacedTextSymbolIndex'},\n {type: 'Int16', name: 'placedIconSymbolIndex'},\n {type: 'Int16', name: 'verticalPlacedIconSymbolIndex'},\n {type: 'Uint16', name: 'key'},\n {type: 'Uint16', name: 'textBoxStartIndex'},\n {type: 'Uint16', name: 'textBoxEndIndex'},\n {type: 'Uint16', name: 'verticalTextBoxStartIndex'},\n {type: 'Uint16', name: 'verticalTextBoxEndIndex'},\n {type: 'Uint16', name: 'iconBoxStartIndex'},\n {type: 'Uint16', name: 'iconBoxEndIndex'},\n {type: 'Uint16', name: 'verticalIconBoxStartIndex'},\n {type: 'Uint16', name: 'verticalIconBoxEndIndex'},\n {type: 'Uint16', name: 'featureIndex'},\n {type: 'Uint16', name: 'numHorizontalGlyphVertices'},\n {type: 'Uint16', name: 'numVerticalGlyphVertices'},\n {type: 'Uint16', name: 'numIconVertices'},\n {type: 'Uint16', name: 'numVerticalIconVertices'},\n {type: 'Uint16', name: 'useRuntimeCollisionCircles'},\n {type: 'Uint32', name: 'crossTileID'},\n {type: 'Float32', components: 2, name: 'textOffset'},\n {type: 'Float32', name: 'collisionCircleDiameter'},\n]);\n\nexport const glyphOffset: StructArrayLayout = createLayout([\n {type: 'Float32', name: 'offsetX'}\n]);\n\nexport const lineVertex: StructArrayLayout = createLayout([\n {type: 'Int16', name: 'x'},\n {type: 'Int16', name: 'y'}\n]);\n","// @flow\n// ONE_EM constant used to go between \"em\" units used in style spec and \"points\" used internally for layout\n\nexport default 24;\n","// @flow\n\nimport {number as interpolate} from '../style-spec/util/interpolate.js';\nimport Interpolate from '../style-spec/expression/definitions/interpolate.js';\nimport {clamp} from '../util/util.js';\nimport EvaluationParameters from '../style/evaluation_parameters.js';\n\nimport type {PropertyValue, PossiblyEvaluatedPropertyValue} from '../style/properties.js';\nimport type {InterpolationType} from '../style-spec/expression/definitions/interpolate.js';\n\nconst SIZE_PACK_FACTOR = 128;\n\nexport {getSizeData, evaluateSizeForFeature, evaluateSizeForZoom, SIZE_PACK_FACTOR};\n\nexport type SizeData = {\n kind: 'constant',\n layoutSize: number\n} | {\n kind: 'source'\n} | {\n kind: 'camera',\n minZoom: number,\n maxZoom: number,\n minSize: number,\n maxSize: number,\n interpolationType: ?InterpolationType\n} | {\n kind: 'composite',\n minZoom: number,\n maxZoom: number,\n interpolationType: ?InterpolationType\n};\n\nexport type InterpolatedSize = {|\n uSize: number,\n uSizeT: number\n|};\n\n// For {text,icon}-size, get the bucket-level data that will be needed by\n// the painter to set symbol-size-related uniforms\nfunction getSizeData(tileZoom: number, value: PropertyValue<number, PossiblyEvaluatedPropertyValue<number>>): SizeData {\n const {expression} = value;\n\n if (expression.kind === 'constant') {\n // $FlowFixMe[method-unbinding]\n const layoutSize = expression.evaluate(new EvaluationParameters(tileZoom + 1));\n return {kind: 'constant', layoutSize};\n\n } else if (expression.kind === 'source') {\n return {kind: 'source'};\n\n } else {\n const {zoomStops, interpolationType} = expression;\n\n // calculate covering zoom stops for zoom-dependent values\n let lower = 0;\n while (lower < zoomStops.length && zoomStops[lower] <= tileZoom) lower++;\n lower = Math.max(0, lower - 1);\n let upper = lower;\n while (upper < zoomStops.length && zoomStops[upper] < tileZoom + 1) upper++;\n upper = Math.min(zoomStops.length - 1, upper);\n\n const minZoom = zoomStops[lower];\n const maxZoom = zoomStops[upper];\n\n // We'd like to be able to use CameraExpression or CompositeExpression in these\n // return types rather than ExpressionSpecification, but the former are not\n // transferrable across Web Worker boundaries.\n if (expression.kind === 'composite') {\n return {kind: 'composite', minZoom, maxZoom, interpolationType};\n }\n\n // for camera functions, also save off the function values\n // evaluated at the covering zoom levels\n // $FlowFixMe[method-unbinding]\n const minSize = expression.evaluate(new EvaluationParameters(minZoom));\n // $FlowFixMe[method-unbinding]\n const maxSize = expression.evaluate(new EvaluationParameters(maxZoom));\n\n return {kind: 'camera', minZoom, maxZoom, minSize, maxSize, interpolationType};\n }\n}\n\nfunction evaluateSizeForFeature(sizeData: SizeData,\n {uSize, uSizeT}: InterpolatedSize,\n {lowerSize, upperSize}: interface {+lowerSize: number, +upperSize: number}): number {\n if (sizeData.kind === 'source') {\n return lowerSize / SIZE_PACK_FACTOR;\n } else if (sizeData.kind === 'composite') {\n return interpolate(lowerSize / SIZE_PACK_FACTOR, upperSize / SIZE_PACK_FACTOR, uSizeT);\n }\n return uSize;\n}\n\nfunction evaluateSizeForZoom(sizeData: SizeData, zoom: number): InterpolatedSize {\n let uSizeT = 0;\n let uSize = 0;\n\n if (sizeData.kind === 'constant') {\n uSize = sizeData.layoutSize;\n\n } else if (sizeData.kind !== 'source') {\n const {interpolationType, minZoom, maxZoom} = sizeData;\n\n // Even though we could get the exact value of the camera function\n // at z = tr.zoom, we intentionally do not: instead, we interpolate\n // between the camera function values at a pair of zoom stops covering\n // [tileZoom, tileZoom + 1] in order to be consistent with this\n // restriction on composite functions\n const t = !interpolationType ? 0 : clamp(\n Interpolate.interpolationFactor(interpolationType, zoom, minZoom, maxZoom), 0, 1);\n\n if (sizeData.kind === 'camera') {\n uSize = interpolate(sizeData.minSize, sizeData.maxSize, t);\n } else {\n uSizeT = t;\n }\n }\n\n return {uSizeT, uSize};\n}\n","// @flow\n\nimport {plugin as rtlTextPlugin} from '../source/rtl_text_plugin.js';\n\nimport type SymbolStyleLayer from '../style/style_layer/symbol_style_layer.js';\nimport type {Feature} from '../style-spec/expression/index.js';\nimport Formatted from '../style-spec/expression/types/formatted.js';\n\nfunction transformText(text: string, layer: SymbolStyleLayer, feature: Feature) {\n const transform = layer.layout.get('text-transform').evaluate(feature, {});\n if (transform === 'uppercase') {\n text = text.toLocaleUpperCase();\n } else if (transform === 'lowercase') {\n text = text.toLocaleLowerCase();\n }\n\n if (rtlTextPlugin.applyArabicShaping) {\n text = rtlTextPlugin.applyArabicShaping(text);\n }\n\n return text;\n}\n\nexport default function(text: Formatted, layer: SymbolStyleLayer, feature: Feature): Formatted {\n text.sections.forEach(section => {\n section.text = transformText(section.text, layer, feature);\n });\n return text;\n}\n","// @flow\n\nimport {charHasRotatedVerticalOrientation} from './script_detection.js';\n\nexport const verticalizedCharacterMap = {\n '!': '︕',\n '#': '#',\n '$': '$',\n '%': '%',\n '&': '&',\n '(': '︵',\n ')': '︶',\n '*': '*',\n '+': '+',\n ',': '︐',\n '-': '︲',\n '.': '・',\n '/': '/',\n ':': '︓',\n ';': '︔',\n '<': '︿',\n '=': '=',\n '>': '﹀',\n '?': '︖',\n '@': '@',\n '[': '﹇',\n '\\\\': '\',\n ']': '﹈',\n '^': '^',\n '_': '︳',\n '`': '`',\n '{': '︷',\n '|': '―',\n '}': '︸',\n '~': '~',\n '¢': '¢',\n '£': '£',\n '¥': '¥',\n '¦': '¦',\n '¬': '¬',\n '¯': ' ̄',\n '–': '︲',\n '—': '︱',\n '‘': '﹃',\n '’': '﹄',\n '“': '﹁',\n '”': '﹂',\n '…': '︙',\n '‧': '・',\n '₩': '₩',\n '、': '︑',\n '。': '︒',\n '〈': '︿',\n '〉': '﹀',\n '《': '︽',\n '》': '︾',\n '「': '﹁',\n '」': '﹂',\n '『': '﹃',\n '』': '﹄',\n '【': '︻',\n '】': '︼',\n '〔': '︹',\n '〕': '︺',\n '〖': '︗',\n '〗': '︘',\n '!': '︕',\n '(': '︵',\n ')': '︶',\n ',': '︐',\n '-': '︲',\n '.': '・',\n ':': '︓',\n ';': '︔',\n '<': '︿',\n '>': '﹀',\n '?': '︖',\n '[': '﹇',\n ']': '﹈',\n '_': '︳',\n '{': '︷',\n '|': '―',\n '}': '︸',\n '⦅': '︵',\n '⦆': '︶',\n '。': '︒',\n '「': '﹁',\n '」': '﹂',\n '←': '↑',\n '→': '↓'\n};\n\nexport default function verticalizePunctuation(input: string, skipContextChecking: boolean): string {\n let output = '';\n\n for (let i = 0; i < input.length; i++) {\n const nextCharCode = input.charCodeAt(i + 1) || null;\n const prevCharCode = input.charCodeAt(i - 1) || null;\n\n const canReplacePunctuation = skipContextChecking || (\n (!nextCharCode || !charHasRotatedVerticalOrientation(nextCharCode) || verticalizedCharacterMap[input[i + 1]]) &&\n (!prevCharCode || !charHasRotatedVerticalOrientation(prevCharCode) || verticalizedCharacterMap[input[i - 1]])\n );\n\n if (canReplacePunctuation && verticalizedCharacterMap[input[i]]) {\n output += verticalizedCharacterMap[input[i]];\n } else {\n output += input[i];\n }\n }\n\n return output;\n}\n\nexport function isVerticalClosePunctuation(chr: string): boolean {\n return chr === '︶' || chr === '﹈' || chr === '︸' || chr === '﹄' || chr === '﹂' || chr === '︾' ||\n chr === '︼' || chr === '︺' || chr === '︘' || chr === '﹀' || chr === '︐' || chr === '︓' ||\n chr === '︔' || chr === '`' || chr === ' ̄' || chr === '︑' || chr === '︒';\n}\n\nexport function isVerticalOpenPunctuation(chr: string): boolean {\n return chr === '︵' || chr === '﹇' || chr === '︷' || chr === '﹃' || chr === '﹁' || chr === '︽' ||\n chr === '︻' || chr === '︹' || chr === '︗' || chr === '︿';\n}\n","'use strict';\n\nmodule.exports = Pbf;\n\nvar ieee754 = require('ieee754');\n\nfunction Pbf(buf) {\n this.buf = ArrayBuffer.isView && ArrayBuffer.isView(buf) ? buf : new Uint8Array(buf || 0);\n this.pos = 0;\n this.type = 0;\n this.length = this.buf.length;\n}\n\nPbf.Varint = 0; // varint: int32, int64, uint32, uint64, sint32, sint64, bool, enum\nPbf.Fixed64 = 1; // 64-bit: double, fixed64, sfixed64\nPbf.Bytes = 2; // length-delimited: string, bytes, embedded messages, packed repeated fields\nPbf.Fixed32 = 5; // 32-bit: float, fixed32, sfixed32\n\nvar SHIFT_LEFT_32 = (1 << 16) * (1 << 16),\n SHIFT_RIGHT_32 = 1 / SHIFT_LEFT_32;\n\n// Threshold chosen based on both benchmarking and knowledge about browser string\n// data structures (which currently switch structure types at 12 bytes or more)\nvar TEXT_DECODER_MIN_LENGTH = 12;\nvar utf8TextDecoder = typeof TextDecoder === 'undefined' ? null : new TextDecoder('utf8');\n\nPbf.prototype = {\n\n destroy: function() {\n this.buf = null;\n },\n\n // === READING =================================================================\n\n readFields: function(readField, result, end) {\n end = end || this.length;\n\n while (this.pos < end) {\n var val = this.readVarint(),\n tag = val >> 3,\n startPos = this.pos;\n\n this.type = val & 0x7;\n readField(tag, result, this);\n\n if (this.pos === startPos) this.skip(val);\n }\n return result;\n },\n\n readMessage: function(readField, result) {\n return this.readFields(readField, result, this.readVarint() + this.pos);\n },\n\n readFixed32: function() {\n var val = readUInt32(this.buf, this.pos);\n this.pos += 4;\n return val;\n },\n\n readSFixed32: function() {\n var val = readInt32(this.buf, this.pos);\n this.pos += 4;\n return val;\n },\n\n // 64-bit int handling is based on github.com/dpw/node-buffer-more-ints (MIT-licensed)\n\n readFixed64: function() {\n var val = readUInt32(this.buf, this.pos) + readUInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;\n this.pos += 8;\n return val;\n },\n\n readSFixed64: function() {\n var val = readUInt32(this.buf, this.pos) + readInt32(this.buf, this.pos + 4) * SHIFT_LEFT_32;\n this.pos += 8;\n return val;\n },\n\n readFloat: function() {\n var val = ieee754.read(this.buf, this.pos, true, 23, 4);\n this.pos += 4;\n return val;\n },\n\n readDouble: function() {\n var val = ieee754.read(this.buf, this.pos, true, 52, 8);\n this.pos += 8;\n return val;\n },\n\n readVarint: function(isSigned) {\n var buf = this.buf,\n val, b;\n\n b = buf[this.pos++]; val = b & 0x7f; if (b < 0x80) return val;\n b = buf[this.pos++]; val |= (b & 0x7f) << 7; if (b < 0x80) return val;\n b = buf[this.pos++]; val |= (b & 0x7f) << 14; if (b < 0x80) return val;\n b = buf[this.pos++]; val |= (b & 0x7f) << 21; if (b < 0x80) return val;\n b = buf[this.pos]; val |= (b & 0x0f) << 28;\n\n return readVarintRemainder(val, isSigned, this);\n },\n\n readVarint64: function() { // for compatibility with v2.0.1\n return this.readVarint(true);\n },\n\n readSVarint: function() {\n var num = this.readVarint();\n return num % 2 === 1 ? (num + 1) / -2 : num / 2; // zigzag encoding\n },\n\n readBoolean: function() {\n return Boolean(this.readVarint());\n },\n\n readString: function() {\n var end = this.readVarint() + this.pos;\n var pos = this.pos;\n this.pos = end;\n\n if (end - pos >= TEXT_DECODER_MIN_LENGTH && utf8TextDecoder) {\n // longer strings are fast with the built-in browser TextDecoder API\n return readUtf8TextDecoder(this.buf, pos, end);\n }\n // short strings are fast with our custom implementation\n return readUtf8(this.buf, pos, end);\n },\n\n readBytes: function() {\n var end = this.readVarint() + this.pos,\n buffer = this.buf.subarray(this.pos, end);\n this.pos = end;\n return buffer;\n },\n\n // verbose for performance reasons; doesn't affect gzipped size\n\n readPackedVarint: function(arr, isSigned) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readVarint(isSigned));\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readVarint(isSigned));\n return arr;\n },\n readPackedSVarint: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readSVarint());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readSVarint());\n return arr;\n },\n readPackedBoolean: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readBoolean());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readBoolean());\n return arr;\n },\n readPackedFloat: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readFloat());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readFloat());\n return arr;\n },\n readPackedDouble: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readDouble());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readDouble());\n return arr;\n },\n readPackedFixed32: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readFixed32());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readFixed32());\n return arr;\n },\n readPackedSFixed32: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed32());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readSFixed32());\n return arr;\n },\n readPackedFixed64: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readFixed64());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readFixed64());\n return arr;\n },\n readPackedSFixed64: function(arr) {\n if (this.type !== Pbf.Bytes) return arr.push(this.readSFixed64());\n var end = readPackedEnd(this);\n arr = arr || [];\n while (this.pos < end) arr.push(this.readSFixed64());\n return arr;\n },\n\n skip: function(val) {\n var type = val & 0x7;\n if (type === Pbf.Varint) while (this.buf[this.pos++] > 0x7f) {}\n else if (type === Pbf.Bytes) this.pos = this.readVarint() + this.pos;\n else if (type === Pbf.Fixed32) this.pos += 4;\n else if (type === Pbf.Fixed64) this.pos += 8;\n else throw new Error('Unimplemented type: ' + type);\n },\n\n // === WRITING =================================================================\n\n writeTag: function(tag, type) {\n this.writeVarint((tag << 3) | type);\n },\n\n realloc: function(min) {\n var length = this.length || 16;\n\n while (length < this.pos + min) length *= 2;\n\n if (length !== this.length) {\n var buf = new Uint8Array(length);\n buf.set(this.buf);\n this.buf = buf;\n this.length = length;\n }\n },\n\n finish: function() {\n this.length = this.pos;\n this.pos = 0;\n return this.buf.subarray(0, this.length);\n },\n\n writeFixed32: function(val) {\n this.realloc(4);\n writeInt32(this.buf, val, this.pos);\n this.pos += 4;\n },\n\n writeSFixed32: function(val) {\n this.realloc(4);\n writeInt32(this.buf, val, this.pos);\n this.pos += 4;\n },\n\n writeFixed64: function(val) {\n this.realloc(8);\n writeInt32(this.buf, val & -1, this.pos);\n writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);\n this.pos += 8;\n },\n\n writeSFixed64: function(val) {\n this.realloc(8);\n writeInt32(this.buf, val & -1, this.pos);\n writeInt32(this.buf, Math.floor(val * SHIFT_RIGHT_32), this.pos + 4);\n this.pos += 8;\n },\n\n writeVarint: function(val) {\n val = +val || 0;\n\n if (val > 0xfffffff || val < 0) {\n writeBigVarint(val, this);\n return;\n }\n\n this.realloc(4);\n\n this.buf[this.pos++] = val & 0x7f | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;\n this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;\n this.buf[this.pos++] = ((val >>>= 7) & 0x7f) | (val > 0x7f ? 0x80 : 0); if (val <= 0x7f) return;\n this.buf[this.pos++] = (val >>> 7) & 0x7f;\n },\n\n writeSVarint: function(val) {\n this.writeVarint(val < 0 ? -val * 2 - 1 : val * 2);\n },\n\n writeBoolean: function(val) {\n this.writeVarint(Boolean(val));\n },\n\n writeString: function(str) {\n str = String(str);\n this.realloc(str.length * 4);\n\n this.pos++; // reserve 1 byte for short string length\n\n var startPos = this.pos;\n // write the string directly to the buffer and see how much was written\n this.pos = writeUtf8(this.buf, str, this.pos);\n var len = this.pos - startPos;\n\n if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);\n\n // finally, write the message length in the reserved place and restore the position\n this.pos = startPos - 1;\n this.writeVarint(len);\n this.pos += len;\n },\n\n writeFloat: function(val) {\n this.realloc(4);\n ieee754.write(this.buf, val, this.pos, true, 23, 4);\n this.pos += 4;\n },\n\n writeDouble: function(val) {\n this.realloc(8);\n ieee754.write(this.buf, val, this.pos, true, 52, 8);\n this.pos += 8;\n },\n\n writeBytes: function(buffer) {\n var len = buffer.length;\n this.writeVarint(len);\n this.realloc(len);\n for (var i = 0; i < len; i++) this.buf[this.pos++] = buffer[i];\n },\n\n writeRawMessage: function(fn, obj) {\n this.pos++; // reserve 1 byte for short message length\n\n // write the message directly to the buffer and see how much was written\n var startPos = this.pos;\n fn(obj, this);\n var len = this.pos - startPos;\n\n if (len >= 0x80) makeRoomForExtraLength(startPos, len, this);\n\n // finally, write the message length in the reserved place and restore the position\n this.pos = startPos - 1;\n this.writeVarint(len);\n this.pos += len;\n },\n\n writeMessage: function(tag, fn, obj) {\n this.writeTag(tag, Pbf.Bytes);\n this.writeRawMessage(fn, obj);\n },\n\n writePackedVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedVarint, arr); },\n writePackedSVarint: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSVarint, arr); },\n writePackedBoolean: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedBoolean, arr); },\n writePackedFloat: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFloat, arr); },\n writePackedDouble: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedDouble, arr); },\n writePackedFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed32, arr); },\n writePackedSFixed32: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed32, arr); },\n writePackedFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedFixed64, arr); },\n writePackedSFixed64: function(tag, arr) { if (arr.length) this.writeMessage(tag, writePackedSFixed64, arr); },\n\n writeBytesField: function(tag, buffer) {\n this.writeTag(tag, Pbf.Bytes);\n this.writeBytes(buffer);\n },\n writeFixed32Field: function(tag, val) {\n this.writeTag(tag, Pbf.Fixed32);\n this.writeFixed32(val);\n },\n writeSFixed32Field: function(tag, val) {\n this.writeTag(tag, Pbf.Fixed32);\n this.writeSFixed32(val);\n },\n writeFixed64Field: function(tag, val) {\n this.writeTag(tag, Pbf.Fixed64);\n this.writeFixed64(val);\n },\n writeSFixed64Field: function(tag, val) {\n this.writeTag(tag, Pbf.Fixed64);\n this.writeSFixed64(val);\n },\n writeVarintField: function(tag, val) {\n this.writeTag(tag, Pbf.Varint);\n this.writeVarint(val);\n },\n writeSVarintField: function(tag, val) {\n this.writeTag(tag, Pbf.Varint);\n this.writeSVarint(val);\n },\n writeStringField: function(tag, str) {\n this.writeTag(tag, Pbf.Bytes);\n this.writeString(str);\n },\n writeFloatField: function(tag, val) {\n this.writeTag(tag, Pbf.Fixed32);\n this.writeFloat(val);\n },\n writeDoubleField: function(tag, val) {\n this.writeTag(tag, Pbf.Fixed64);\n this.writeDouble(val);\n },\n writeBooleanField: function(tag, val) {\n this.writeVarintField(tag, Boolean(val));\n }\n};\n\nfunction readVarintRemainder(l, s, p) {\n var buf = p.buf,\n h, b;\n\n b = buf[p.pos++]; h = (b & 0x70) >> 4; if (b < 0x80) return toNum(l, h, s);\n b = buf[p.pos++]; h |= (b & 0x7f) << 3; if (b < 0x80) return toNum(l, h, s);\n b = buf[p.pos++]; h |= (b & 0x7f) << 10; if (b < 0x80) return toNum(l, h, s);\n b = buf[p.pos++]; h |= (b & 0x7f) << 17; if (b < 0x80) return toNum(l, h, s);\n b = buf[p.pos++]; h |= (b & 0x7f) << 24; if (b < 0x80) return toNum(l, h, s);\n b = buf[p.pos++]; h |= (b & 0x01) << 31; if (b < 0x80) return toNum(l, h, s);\n\n throw new Error('Expected varint not more than 10 bytes');\n}\n\nfunction readPackedEnd(pbf) {\n return pbf.type === Pbf.Bytes ?\n pbf.readVarint() + pbf.pos : pbf.pos + 1;\n}\n\nfunction toNum(low, high, isSigned) {\n if (isSigned) {\n return high * 0x100000000 + (low >>> 0);\n }\n\n return ((high >>> 0) * 0x100000000) + (low >>> 0);\n}\n\nfunction writeBigVarint(val, pbf) {\n var low, high;\n\n if (val >= 0) {\n low = (val % 0x100000000) | 0;\n high = (val / 0x100000000) | 0;\n } else {\n low = ~(-val % 0x100000000);\n high = ~(-val / 0x100000000);\n\n if (low ^ 0xffffffff) {\n low = (low + 1) | 0;\n } else {\n low = 0;\n high = (high + 1) | 0;\n }\n }\n\n if (val >= 0x10000000000000000 || val < -0x10000000000000000) {\n throw new Error('Given varint doesn\\'t fit into 10 bytes');\n }\n\n pbf.realloc(10);\n\n writeBigVarintLow(low, high, pbf);\n writeBigVarintHigh(high, pbf);\n}\n\nfunction writeBigVarintLow(low, high, pbf) {\n pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;\n pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;\n pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;\n pbf.buf[pbf.pos++] = low & 0x7f | 0x80; low >>>= 7;\n pbf.buf[pbf.pos] = low & 0x7f;\n}\n\nfunction writeBigVarintHigh(high, pbf) {\n var lsb = (high & 0x07) << 4;\n\n pbf.buf[pbf.pos++] |= lsb | ((high >>>= 3) ? 0x80 : 0); if (!high) return;\n pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;\n pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;\n pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;\n pbf.buf[pbf.pos++] = high & 0x7f | ((high >>>= 7) ? 0x80 : 0); if (!high) return;\n pbf.buf[pbf.pos++] = high & 0x7f;\n}\n\nfunction makeRoomForExtraLength(startPos, len, pbf) {\n var extraLen =\n len <= 0x3fff ? 1 :\n len <= 0x1fffff ? 2 :\n len <= 0xfffffff ? 3 : Math.floor(Math.log(len) / (Math.LN2 * 7));\n\n // if 1 byte isn't enough for encoding message length, shift the data to the right\n pbf.realloc(extraLen);\n for (var i = pbf.pos - 1; i >= startPos; i--) pbf.buf[i + extraLen] = pbf.buf[i];\n}\n\nfunction writePackedVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeVarint(arr[i]); }\nfunction writePackedSVarint(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSVarint(arr[i]); }\nfunction writePackedFloat(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFloat(arr[i]); }\nfunction writePackedDouble(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeDouble(arr[i]); }\nfunction writePackedBoolean(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeBoolean(arr[i]); }\nfunction writePackedFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed32(arr[i]); }\nfunction writePackedSFixed32(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed32(arr[i]); }\nfunction writePackedFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeFixed64(arr[i]); }\nfunction writePackedSFixed64(arr, pbf) { for (var i = 0; i < arr.length; i++) pbf.writeSFixed64(arr[i]); }\n\n// Buffer code below from https://github.com/feross/buffer, MIT-licensed\n\nfunction readUInt32(buf, pos) {\n return ((buf[pos]) |\n (buf[pos + 1] << 8) |\n (buf[pos + 2] << 16)) +\n (buf[pos + 3] * 0x1000000);\n}\n\nfunction writeInt32(buf, val, pos) {\n buf[pos] = val;\n buf[pos + 1] = (val >>> 8);\n buf[pos + 2] = (val >>> 16);\n buf[pos + 3] = (val >>> 24);\n}\n\nfunction readInt32(buf, pos) {\n return ((buf[pos]) |\n (buf[pos + 1] << 8) |\n (buf[pos + 2] << 16)) +\n (buf[pos + 3] << 24);\n}\n\nfunction readUtf8(buf, pos, end) {\n var str = '';\n var i = pos;\n\n while (i < end) {\n var b0 = buf[i];\n var c = null; // codepoint\n var bytesPerSequence =\n b0 > 0xEF ? 4 :\n b0 > 0xDF ? 3 :\n b0 > 0xBF ? 2 : 1;\n\n if (i + bytesPerSequence > end) break;\n\n var b1, b2, b3;\n\n if (bytesPerSequence === 1) {\n if (b0 < 0x80) {\n c = b0;\n }\n } else if (bytesPerSequence === 2) {\n b1 = buf[i + 1];\n if ((b1 & 0xC0) === 0x80) {\n c = (b0 & 0x1F) << 0x6 | (b1 & 0x3F);\n if (c <= 0x7F) {\n c = null;\n }\n }\n } else if (bytesPerSequence === 3) {\n b1 = buf[i + 1];\n b2 = buf[i + 2];\n if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80) {\n c = (b0 & 0xF) << 0xC | (b1 & 0x3F) << 0x6 | (b2 & 0x3F);\n if (c <= 0x7FF || (c >= 0xD800 && c <= 0xDFFF)) {\n c = null;\n }\n }\n } else if (bytesPerSequence === 4) {\n b1 = buf[i + 1];\n b2 = buf[i + 2];\n b3 = buf[i + 3];\n if ((b1 & 0xC0) === 0x80 && (b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {\n c = (b0 & 0xF) << 0x12 | (b1 & 0x3F) << 0xC | (b2 & 0x3F) << 0x6 | (b3 & 0x3F);\n if (c <= 0xFFFF || c >= 0x110000) {\n c = null;\n }\n }\n }\n\n if (c === null) {\n c = 0xFFFD;\n bytesPerSequence = 1;\n\n } else if (c > 0xFFFF) {\n c -= 0x10000;\n str += String.fromCharCode(c >>> 10 & 0x3FF | 0xD800);\n c = 0xDC00 | c & 0x3FF;\n }\n\n str += String.fromCharCode(c);\n i += bytesPerSequence;\n }\n\n return str;\n}\n\nfunction readUtf8TextDecoder(buf, pos, end) {\n return utf8TextDecoder.decode(buf.subarray(pos, end));\n}\n\nfunction writeUtf8(buf, str, pos) {\n for (var i = 0, c, lead; i < str.length; i++) {\n c = str.charCodeAt(i); // code point\n\n if (c > 0xD7FF && c < 0xE000) {\n if (lead) {\n if (c < 0xDC00) {\n buf[pos++] = 0xEF;\n buf[pos++] = 0xBF;\n buf[pos++] = 0xBD;\n lead = c;\n continue;\n } else {\n c = lead - 0xD800 << 10 | c - 0xDC00 | 0x10000;\n lead = null;\n }\n } else {\n if (c > 0xDBFF || (i + 1 === str.length)) {\n buf[pos++] = 0xEF;\n buf[pos++] = 0xBF;\n buf[pos++] = 0xBD;\n } else {\n lead = c;\n }\n continue;\n }\n } else if (lead) {\n buf[pos++] = 0xEF;\n buf[pos++] = 0xBF;\n buf[pos++] = 0xBD;\n lead = null;\n }\n\n if (c < 0x80) {\n buf[pos++] = c;\n } else {\n if (c < 0x800) {\n buf[pos++] = c >> 0x6 | 0xC0;\n } else {\n if (c < 0x10000) {\n buf[pos++] = c >> 0xC | 0xE0;\n } else {\n buf[pos++] = c >> 0x12 | 0xF0;\n buf[pos++] = c >> 0xC & 0x3F | 0x80;\n }\n buf[pos++] = c >> 0x6 & 0x3F | 0x80;\n }\n buf[pos++] = c & 0x3F | 0x80;\n }\n }\n return pos;\n}\n","/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n","// @flow\n\nimport {AlphaImage} from '../util/image.js';\n\nimport Protobuf from 'pbf';\nconst border = 3;\n\nimport type {StyleGlyph} from './style_glyph.js';\n\nfunction readFontstacks(tag: number, glyphData: {glyphs: Array<StyleGlyph>, ascender?: number, descender?: number}, pbf: Protobuf) {\n glyphData.glyphs = [];\n if (tag === 1) {\n pbf.readMessage(readFontstack, glyphData);\n }\n}\n\nfunction readFontstack(tag: number, glyphData: {glyphs: Array<StyleGlyph>, ascender?: number, descender?: number}, pbf: Protobuf) {\n if (tag === 3) {\n const {id, bitmap, width, height, left, top, advance} = pbf.readMessage(readGlyph, {});\n glyphData.glyphs.push({\n id,\n bitmap: new AlphaImage({\n width: width + 2 * border,\n height: height + 2 * border\n }, bitmap),\n metrics: {width, height, left, top, advance}\n });\n } else if (tag === 4) {\n glyphData.ascender = pbf.readSVarint();\n } else if (tag === 5) {\n glyphData.descender = pbf.readSVarint();\n }\n}\n\nfunction readGlyph(tag: number, glyph: Object, pbf: Protobuf) {\n if (tag === 1) glyph.id = pbf.readVarint();\n else if (tag === 2) glyph.bitmap = pbf.readBytes();\n else if (tag === 3) glyph.width = pbf.readVarint();\n else if (tag === 4) glyph.height = pbf.readVarint();\n else if (tag === 5) glyph.left = pbf.readSVarint();\n else if (tag === 6) glyph.top = pbf.readSVarint();\n else if (tag === 7) glyph.advance = pbf.readVarint();\n}\n\nexport default function (data: ArrayBuffer | Uint8Array): {glyphs: Array<StyleGlyph>, ascender?: number, descender?: number} {\n return new Protobuf(data).readFields(readFontstacks, {});\n}\n\nexport const GLYPH_PBF_BORDER = border;\n","\nexport default function potpack(boxes) {\n\n // calculate total box area and maximum box width\n let area = 0;\n let maxWidth = 0;\n\n for (const box of boxes) {\n area += box.w * box.h;\n maxWidth = Math.max(maxWidth, box.w);\n }\n\n // sort the boxes for insertion by height, descending\n boxes.sort((a, b) => b.h - a.h);\n\n // aim for a squarish resulting container,\n // slightly adjusted for sub-100% space utilization\n const startWidth = Math.max(Math.ceil(Math.sqrt(area / 0.95)), maxWidth);\n\n // start with a single empty space, unbounded at the bottom\n const spaces = [{x: 0, y: 0, w: startWidth, h: Infinity}];\n\n let width = 0;\n let height = 0;\n\n for (const box of boxes) {\n // look through spaces backwards so that we check smaller spaces first\n for (let i = spaces.length - 1; i >= 0; i--) {\n const space = spaces[i];\n\n // look for empty spaces that can accommodate the current box\n if (box.w > space.w || box.h > space.h) continue;\n\n // found the space; add the box to its top-left corner\n // |-------|-------|\n // | box | |\n // |_______| |\n // | space |\n // |_______________|\n box.x = space.x;\n box.y = space.y;\n\n height = Math.max(height, box.y + box.h);\n width = Math.max(width, box.x + box.w);\n\n if (box.w === space.w && box.h === space.h) {\n // space matches the box exactly; remove it\n const last = spaces.pop();\n if (i < spaces.length) spaces[i] = last;\n\n } else if (box.h === space.h) {\n // space matches the box height; update it accordingly\n // |-------|---------------|\n // | box | updated space |\n // |_______|_______________|\n space.x += box.w;\n space.w -= box.w;\n\n } else if (box.w === space.w) {\n // space matches the box width; update it accordingly\n // |---------------|\n // | box |\n // |_______________|\n // | updated space |\n // |_______________|\n space.y += box.h;\n space.h -= box.h;\n\n } else {\n // otherwise the box splits the space into two spaces\n // |-------|-----------|\n // | box | new space |\n // |_______|___________|\n // | updated space |\n // |___________________|\n spaces.push({\n x: space.x + box.w,\n y: space.y,\n w: space.w - box.w,\n h: box.h\n });\n space.y += box.h;\n space.h -= box.h;\n }\n break;\n }\n }\n\n return {\n w: width, // container width\n h: height, // container height\n fill: (area / (width * height)) || 0 // space utilization\n };\n}\n","// @flow\n\nimport {RGBAImage} from '../util/image.js';\nimport {register} from '../util/web_worker_transfer.js';\nimport potpack from 'potpack';\n\nimport type {StyleImage} from '../style/style_image.js';\nimport type ImageManager from './image_manager.js';\nimport type Texture from './texture.js';\nimport type {SpritePosition} from '../util/image.js';\n\nconst IMAGE_PADDING: number = 1;\nexport {IMAGE_PADDING};\n\ntype Rect = {\n x: number,\n y: number,\n w: number,\n h: number\n};\n\nexport class ImagePosition implements SpritePosition {\n paddedRect: Rect;\n pixelRatio: number;\n version: number;\n stretchY: ?Array<[number, number]>;\n stretchX: ?Array<[number, number]>;\n content: ?[number, number, number, number];\n\n constructor(paddedRect: Rect, {pixelRatio, version, stretchX, stretchY, content}: StyleImage) {\n this.paddedRect = paddedRect;\n this.pixelRatio = pixelRatio;\n this.stretchX = stretchX;\n this.stretchY = stretchY;\n this.content = content;\n this.version = version;\n }\n\n get tl(): [number, number] {\n return [\n this.paddedRect.x + IMAGE_PADDING,\n this.paddedRect.y + IMAGE_PADDING\n ];\n }\n\n get br(): [number, number] {\n return [\n this.paddedRect.x + this.paddedRect.w - IMAGE_PADDING,\n this.paddedRect.y + this.paddedRect.h - IMAGE_PADDING\n ];\n }\n\n get displaySize(): [number, number] {\n return [\n (this.paddedRect.w - IMAGE_PADDING * 2) / this.pixelRatio,\n (this.paddedRect.h - IMAGE_PADDING * 2) / this.pixelRatio\n ];\n }\n}\n\nexport default class ImageAtlas {\n image: RGBAImage;\n iconPositions: {[_: string]: ImagePosition};\n patternPositions: {[_: string]: ImagePosition};\n haveRenderCallbacks: Array<string>;\n uploaded: ?boolean;\n\n constructor(icons: {[_: string]: StyleImage}, patterns: {[_: string]: StyleImage}) {\n const iconPositions = {}, patternPositions = {};\n this.haveRenderCallbacks = [];\n\n const bins = [];\n\n this.addImages(icons, iconPositions, bins);\n this.addImages(patterns, patternPositions, bins);\n\n const {w, h} = potpack(bins);\n const image = new RGBAImage({width: w || 1, height: h || 1});\n\n for (const id in icons) {\n const src = icons[id];\n const bin = iconPositions[id].paddedRect;\n RGBAImage.copy(src.data, image, {x: 0, y: 0}, {x: bin.x + IMAGE_PADDING, y: bin.y + IMAGE_PADDING}, src.data);\n }\n\n for (const id in patterns) {\n const src = patterns[id];\n const bin = patternPositions[id].paddedRect;\n const x = bin.x + IMAGE_PADDING,\n y = bin.y + IMAGE_PADDING,\n w = src.data.width,\n h = src.data.height;\n\n RGBAImage.copy(src.data, image, {x: 0, y: 0}, {x, y}, src.data);\n // Add 1 pixel wrapped padding on each side of the image.\n RGBAImage.copy(src.data, image, {x: 0, y: h - 1}, {x, y: y - 1}, {width: w, height: 1}); // T\n RGBAImage.copy(src.data, image, {x: 0, y: 0}, {x, y: y + h}, {width: w, height: 1}); // B\n RGBAImage.copy(src.data, image, {x: w - 1, y: 0}, {x: x - 1, y}, {width: 1, height: h}); // L\n RGBAImage.copy(src.data, image, {x: 0, y: 0}, {x: x + w, y}, {width: 1, height: h}); // R\n }\n\n this.image = image;\n this.iconPositions = iconPositions;\n this.patternPositions = patternPositions;\n }\n\n addImages(images: {[_: string]: StyleImage}, positions: {[_: string]: ImagePosition}, bins: Array<Rect>) {\n for (const id in images) {\n const src = images[id];\n const bin = {\n x: 0,\n y: 0,\n w: src.data.width + 2 * IMAGE_PADDING,\n h: src.data.height + 2 * IMAGE_PADDING,\n };\n bins.push(bin);\n positions[id] = new ImagePosition(bin, src);\n\n if (src.hasRenderCallback) {\n this.haveRenderCallbacks.push(id);\n }\n }\n }\n\n patchUpdatedImages(imageManager: ImageManager, texture: Texture) {\n this.haveRenderCallbacks = this.haveRenderCallbacks.filter(id => imageManager.hasImage(id));\n imageManager.dispatchRenderCallbacks(this.haveRenderCallbacks);\n for (const name in imageManager.updatedImages) {\n this.patchUpdatedImage(this.iconPositions[name], imageManager.getImage(name), texture);\n this.patchUpdatedImage(this.patternPositions[name], imageManager.getImage(name), texture);\n }\n }\n\n patchUpdatedImage(position: ?ImagePosition, image: ?StyleImage, texture: Texture) {\n if (!position || !image) return;\n\n if (position.version === image.version) return;\n\n position.version = image.version;\n const [x, y] = position.tl;\n texture.update(image.data, undefined, {x, y});\n }\n\n}\n\nregister(ImagePosition, 'ImagePosition');\nregister(ImageAtlas, 'ImageAtlas');\n","// @flow\n\nimport assert from 'assert';\nimport {\n charHasUprightVerticalOrientation,\n charAllowsIdeographicBreaking,\n charInComplexShapingScript\n} from '../util/script_detection.js';\nimport verticalizePunctuation from '../util/verticalize_punctuation.js';\nimport {plugin as rtlTextPlugin} from '../source/rtl_text_plugin.js';\nimport ONE_EM from './one_em.js';\nimport {warnOnce} from '../util/util.js';\n\nimport type {StyleGlyph, GlyphMetrics} from '../style/style_glyph.js';\nimport {GLYPH_PBF_BORDER} from '../style/parse_glyph_pbf.js';\nimport type {ImagePosition} from '../render/image_atlas.js';\nimport {IMAGE_PADDING} from '../render/image_atlas.js';\nimport type {GlyphRect, GlyphPositions} from '../render/glyph_atlas.js';\nimport Formatted, {FormattedSection} from '../style-spec/expression/types/formatted.js';\n\nconst WritingMode = {\n horizontal: 1,\n vertical: 2,\n horizontalOnly: 3\n};\n\nconst SHAPING_DEFAULT_OFFSET = -17;\nexport {shapeText, shapeIcon, fitIconToText, getAnchorAlignment, WritingMode, SHAPING_DEFAULT_OFFSET};\n\n// The position of a glyph relative to the text's anchor point.\nexport type PositionedGlyph = {\n glyph: number,\n imageName: string | null,\n x: number,\n y: number,\n vertical: boolean,\n scale: number,\n fontStack: string,\n sectionIndex: number,\n metrics: GlyphMetrics,\n rect: GlyphRect | null,\n localGlyph?: boolean\n};\n\nexport type PositionedLine = {\n positionedGlyphs: Array<PositionedGlyph>,\n lineOffset: number\n};\n\n// A collection of positioned glyphs and some metadata\nexport type Shaping = {\n positionedLines: Array<PositionedLine>,\n top: number,\n bottom: number,\n left: number,\n right: number,\n writingMode: 1 | 2,\n text: string,\n iconsInText: boolean,\n verticalizable: boolean,\n hasBaseline: boolean\n};\n\ntype AnchorAlignment = {|\n horizontalAlign: number,\n verticalAlign: number\n|};\n\nfunction isEmpty(positionedLines: Array<PositionedLine>) {\n for (const line of positionedLines) {\n if (line.positionedGlyphs.length !== 0) {\n return false;\n }\n }\n return true;\n}\n\nexport type SymbolAnchor = 'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\nexport type TextJustify = 'left' | 'center' | 'right';\n\n// Max number of images in label is 6401 U+E000–U+F8FF that covers\n// Basic Multilingual Plane Unicode Private Use Area (PUA).\nconst PUAbegin = 0xE000;\nconst PUAend = 0xF8FF;\n\nclass SectionOptions {\n // Text options\n scale: number;\n fontStack: string;\n // Image options\n imageName: string | null;\n\n constructor() {\n this.scale = 1.0;\n this.fontStack = \"\";\n this.imageName = null;\n }\n\n static forText(scale: ?number, fontStack: string): SectionOptions {\n const textOptions = new SectionOptions();\n textOptions.scale = scale || 1;\n textOptions.fontStack = fontStack;\n return textOptions;\n }\n\n static forImage(imageName: string): SectionOptions {\n const imageOptions = new SectionOptions();\n imageOptions.imageName = imageName;\n return imageOptions;\n }\n\n}\n\nclass TaggedString {\n text: string;\n sectionIndex: Array<number> // maps each character in 'text' to its corresponding entry in 'sections'\n sections: Array<SectionOptions>\n imageSectionID: number | null;\n\n constructor() {\n this.text = \"\";\n this.sectionIndex = [];\n this.sections = [];\n this.imageSectionID = null;\n }\n\n static fromFeature(text: Formatted, defaultFontStack: string): TaggedString {\n const result = new TaggedString();\n for (let i = 0; i < text.sections.length; i++) {\n const section = text.sections[i];\n if (!section.image) {\n result.addTextSection(section, defaultFontStack);\n } else {\n result.addImageSection(section);\n }\n }\n return result;\n }\n\n length(): number {\n return this.text.length;\n }\n\n getSection(index: number): SectionOptions {\n return this.sections[this.sectionIndex[index]];\n }\n\n getSections(): Array<SectionOptions> {\n return this.sections;\n }\n\n getSectionIndex(index: number): number {\n return this.sectionIndex[index];\n }\n\n getCharCode(index: number): number {\n return this.text.charCodeAt(index);\n }\n\n verticalizePunctuation(skipContextChecking: boolean) {\n this.text = verticalizePunctuation(this.text, skipContextChecking);\n }\n\n trim() {\n let beginningWhitespace = 0;\n for (let i = 0;\n i < this.text.length && whitespace[this.text.charCodeAt(i)];\n i++) {\n beginningWhitespace++;\n }\n let trailingWhitespace = this.text.length;\n for (let i = this.text.length - 1;\n i >= 0 && i >= beginningWhitespace && whitespace[this.text.charCodeAt(i)];\n i--) {\n trailingWhitespace--;\n }\n this.text = this.text.substring(beginningWhitespace, trailingWhitespace);\n this.sectionIndex = this.sectionIndex.slice(beginningWhitespace, trailingWhitespace);\n }\n\n substring(start: number, end: number): TaggedString {\n const substring = new TaggedString();\n substring.text = this.text.substring(start, end);\n substring.sectionIndex = this.sectionIndex.slice(start, end);\n substring.sections = this.sections;\n return substring;\n }\n\n toString(): string {\n return this.text;\n }\n\n getMaxScale(): number {\n return this.sectionIndex.reduce((max, index) => Math.max(max, this.sections[index].scale), 0);\n }\n\n addTextSection(section: FormattedSection, defaultFontStack: string) {\n this.text += section.text;\n this.sections.push(SectionOptions.forText(section.scale, section.fontStack || defaultFontStack));\n const index = this.sections.length - 1;\n for (let i = 0; i < section.text.length; ++i) {\n this.sectionIndex.push(index);\n }\n }\n\n addImageSection(section: FormattedSection) {\n const imageName = section.image ? section.image.name : '';\n if (imageName.length === 0) {\n warnOnce(`Can't add FormattedSection with an empty image.`);\n return;\n }\n\n const nextImageSectionCharCode = this.getNextImageSectionCharCode();\n if (!nextImageSectionCharCode) {\n warnOnce(`Reached maximum number of images ${PUAend - PUAbegin + 2}`);\n return;\n }\n\n this.text += String.fromCharCode(nextImageSectionCharCode);\n this.sections.push(SectionOptions.forImage(imageName));\n this.sectionIndex.push(this.sections.length - 1);\n }\n\n getNextImageSectionCharCode(): number | null {\n if (!this.imageSectionID) {\n this.imageSectionID = PUAbegin;\n return this.imageSectionID;\n }\n\n if (this.imageSectionID >= PUAend) return null;\n return ++this.imageSectionID;\n }\n}\n\nfunction breakLines(input: TaggedString, lineBreakPoints: Array<number>): Array<TaggedString> {\n const lines = [];\n const text = input.text;\n let start = 0;\n for (const lineBreak of lineBreakPoints) {\n lines.push(input.substring(start, lineBreak));\n start = lineBreak;\n }\n\n if (start < text.length) {\n lines.push(input.substring(start, text.length));\n }\n return lines;\n}\n\nfunction shapeText(text: Formatted,\n glyphMap: {[_: string]: {glyphs: {[_: number]: ?StyleGlyph}, ascender?: number, descender?: number}},\n glyphPositions: GlyphPositions,\n imagePositions: {[_: string]: ImagePosition},\n defaultFontStack: string,\n maxWidth: number,\n lineHeight: number,\n textAnchor: SymbolAnchor,\n textJustify: TextJustify,\n spacing: number,\n translate: [number, number],\n writingMode: 1 | 2,\n allowVerticalPlacement: boolean,\n layoutTextSize: number,\n layoutTextSizeThisZoom: number): Shaping | false {\n const logicalInput = TaggedString.fromFeature(text, defaultFontStack);\n\n if (writingMode === WritingMode.vertical) {\n logicalInput.verticalizePunctuation(allowVerticalPlacement);\n }\n\n let lines: Array<TaggedString> = [];\n\n const lineBreaks = determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize);\n\n const {processBidirectionalText, processStyledBidirectionalText} = rtlTextPlugin;\n if (processBidirectionalText && logicalInput.sections.length === 1) {\n // Bidi doesn't have to be style-aware\n const untaggedLines = processBidirectionalText(logicalInput.toString(), lineBreaks);\n for (const line of untaggedLines) {\n const taggedLine = new TaggedString();\n taggedLine.text = line;\n taggedLine.sections = logicalInput.sections;\n for (let i = 0; i < line.length; i++) {\n taggedLine.sectionIndex.push(0);\n }\n lines.push(taggedLine);\n }\n } else if (processStyledBidirectionalText) {\n // Need version of mapbox-gl-rtl-text with style support for combining RTL text with formatting\n const processedLines = processStyledBidirectionalText(logicalInput.text, logicalInput.sectionIndex, lineBreaks);\n for (const line of processedLines) {\n const taggedLine = new TaggedString();\n taggedLine.text = line[0];\n taggedLine.sectionIndex = line[1];\n taggedLine.sections = logicalInput.sections;\n lines.push(taggedLine);\n }\n } else {\n lines = breakLines(logicalInput, lineBreaks);\n }\n\n const positionedLines = [];\n const shaping = {\n positionedLines,\n text: logicalInput.toString(),\n top: translate[1],\n bottom: translate[1],\n left: translate[0],\n right: translate[0],\n writingMode,\n iconsInText: false,\n verticalizable: false,\n hasBaseline: false\n };\n\n shapeLines(shaping, glyphMap, glyphPositions, imagePositions, lines, lineHeight, textAnchor, textJustify, writingMode, spacing, allowVerticalPlacement, layoutTextSizeThisZoom);\n if (isEmpty(positionedLines)) return false;\n\n return shaping;\n}\n\n// using computed properties due to https://github.com/facebook/flow/issues/380\n/* eslint no-useless-computed-key: 0 */\n\nconst whitespace: {[_: number]: boolean} = {\n [0x09]: true, // tab\n [0x0a]: true, // newline\n [0x0b]: true, // vertical tab\n [0x0c]: true, // form feed\n [0x0d]: true, // carriage return\n [0x20]: true, // space\n};\n\nconst breakable: {[_: number]: boolean} = {\n [0x0a]: true, // newline\n [0x20]: true, // space\n [0x26]: true, // ampersand\n [0x28]: true, // left parenthesis\n [0x29]: true, // right parenthesis\n [0x2b]: true, // plus sign\n [0x2d]: true, // hyphen-minus\n [0x2f]: true, // solidus\n [0xad]: true, // soft hyphen\n [0xb7]: true, // middle dot\n [0x200b]: true, // zero-width space\n [0x2010]: true, // hyphen\n [0x2013]: true, // en dash\n [0x2027]: true // interpunct\n // Many other characters may be reasonable breakpoints\n // Consider \"neutral orientation\" characters at scriptDetection.charHasNeutralVerticalOrientation\n // See https://github.com/mapbox/mapbox-gl-js/issues/3658\n};\n\nfunction getGlyphAdvance(codePoint: number,\n section: SectionOptions,\n glyphMap: {[_: string]: {glyphs: {[_: number]: ?StyleGlyph}, ascender?: number, descender?: number}},\n imagePositions: {[_: string]: ImagePosition},\n spacing: number,\n layoutTextSize: number): number {\n if (!section.imageName) {\n const positions = glyphMap[section.fontStack];\n const glyph = positions && positions.glyphs[codePoint];\n if (!glyph) return 0;\n return glyph.metrics.advance * section.scale + spacing;\n } else {\n const imagePosition = imagePositions[section.imageName];\n if (!imagePosition) return 0;\n return imagePosition.displaySize[0] * section.scale * ONE_EM / layoutTextSize + spacing;\n }\n}\n\nfunction determineAverageLineWidth(logicalInput: TaggedString,\n spacing: number,\n maxWidth: number,\n glyphMap: {[_: string]: {glyphs: {[_: number]: ?StyleGlyph}, ascender?: number, descender?: number}},\n imagePositions: {[_: string]: ImagePosition},\n layoutTextSize: number) {\n let totalWidth = 0;\n\n for (let index = 0; index < logicalInput.length(); index++) {\n const section = logicalInput.getSection(index);\n totalWidth += getGlyphAdvance(logicalInput.getCharCode(index), section, glyphMap, imagePositions, spacing, layoutTextSize);\n }\n\n const lineCount = Math.max(1, Math.ceil(totalWidth / maxWidth));\n return totalWidth / lineCount;\n}\n\nfunction calculateBadness(lineWidth: number,\n targetWidth: number,\n penalty: number,\n isLastBreak: boolean) {\n const raggedness = Math.pow(lineWidth - targetWidth, 2);\n if (isLastBreak) {\n // Favor finals lines shorter than average over longer than average\n if (lineWidth < targetWidth) {\n return raggedness / 2;\n } else {\n return raggedness * 2;\n }\n }\n\n return raggedness + Math.abs(penalty) * penalty;\n}\n\nfunction calculatePenalty(codePoint: number, nextCodePoint: number, penalizableIdeographicBreak: boolean) {\n let penalty = 0;\n // Force break on newline\n if (codePoint === 0x0a) {\n penalty -= 10000;\n }\n // Penalize breaks between characters that allow ideographic breaking because\n // they are less preferable than breaks at spaces (or zero width spaces).\n if (penalizableIdeographicBreak) {\n penalty += 150;\n }\n\n // Penalize open parenthesis at end of line\n if (codePoint === 0x28 || codePoint === 0xff08) {\n penalty += 50;\n }\n\n // Penalize close parenthesis at beginning of line\n if (nextCodePoint === 0x29 || nextCodePoint === 0xff09) {\n penalty += 50;\n }\n return penalty;\n}\n\ntype Break = {\n index: number,\n x: number,\n priorBreak: ?Break,\n badness: number\n};\n\nfunction evaluateBreak(breakIndex: number,\n breakX: number,\n targetWidth: number,\n potentialBreaks: Array<Break>,\n penalty: number,\n isLastBreak: boolean): Break {\n // We could skip evaluating breaks where the line length (breakX - priorBreak.x) > maxWidth\n // ...but in fact we allow lines longer than maxWidth (if there's no break points)\n // ...and when targetWidth and maxWidth are close, strictly enforcing maxWidth can give\n // more lopsided results.\n\n let bestPriorBreak: ?Break = null;\n let bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak);\n\n for (const potentialBreak of potentialBreaks) {\n const lineWidth = breakX - potentialBreak.x;\n const breakBadness =\n calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness;\n if (breakBadness <= bestBreakBadness) {\n bestPriorBreak = potentialBreak;\n bestBreakBadness = breakBadness;\n }\n }\n\n return {\n index: breakIndex,\n x: breakX,\n priorBreak: bestPriorBreak,\n badness: bestBreakBadness\n };\n}\n\nfunction leastBadBreaks(lastLineBreak: ?Break): Array<number> {\n if (!lastLineBreak) {\n return [];\n }\n return leastBadBreaks(lastLineBreak.priorBreak).concat(lastLineBreak.index);\n}\n\nfunction determineLineBreaks(logicalInput: TaggedString,\n spacing: number,\n maxWidth: number,\n glyphMap: {[_: string]: {glyphs: {[_: number]: ?StyleGlyph}, ascender?: number, descender?: number}},\n imagePositions: {[_: string]: ImagePosition},\n layoutTextSize: number): Array<number> {\n if (!logicalInput)\n return [];\n\n const potentialLineBreaks = [];\n const targetWidth = determineAverageLineWidth(logicalInput, spacing, maxWidth, glyphMap, imagePositions, layoutTextSize);\n\n const hasServerSuggestedBreakpoints = logicalInput.text.indexOf(\"\\u200b\") >= 0;\n\n let currentX = 0;\n\n for (let i = 0; i < logicalInput.length(); i++) {\n const section = logicalInput.getSection(i);\n const codePoint = logicalInput.getCharCode(i);\n if (!whitespace[codePoint]) currentX += getGlyphAdvance(codePoint, section, glyphMap, imagePositions, spacing, layoutTextSize);\n\n // Ideographic characters, spaces, and word-breaking punctuation that often appear without\n // surrounding spaces.\n if ((i < logicalInput.length() - 1)) {\n const ideographicBreak = charAllowsIdeographicBreaking(codePoint);\n if (breakable[codePoint] || ideographicBreak || section.imageName) {\n\n potentialLineBreaks.push(\n evaluateBreak(\n i + 1,\n currentX,\n targetWidth,\n potentialLineBreaks,\n calculatePenalty(codePoint, logicalInput.getCharCode(i + 1), ideographicBreak && hasServerSuggestedBreakpoints),\n false));\n }\n }\n }\n\n return leastBadBreaks(\n evaluateBreak(\n logicalInput.length(),\n currentX,\n targetWidth,\n potentialLineBreaks,\n 0,\n true));\n}\n\nfunction getAnchorAlignment(anchor: SymbolAnchor): AnchorAlignment {\n let horizontalAlign = 0.5, verticalAlign = 0.5;\n\n switch (anchor) {\n case 'right':\n case 'top-right':\n case 'bottom-right':\n horizontalAlign = 1;\n break;\n case 'left':\n case 'top-left':\n case 'bottom-left':\n horizontalAlign = 0;\n break;\n }\n\n switch (anchor) {\n case 'bottom':\n case 'bottom-right':\n case 'bottom-left':\n verticalAlign = 1;\n break;\n case 'top':\n case 'top-right':\n case 'top-left':\n verticalAlign = 0;\n break;\n }\n\n return {horizontalAlign, verticalAlign};\n}\n\nfunction shapeLines(shaping: Shaping,\n glyphMap: {[_: string]: {glyphs: {[_: number]: ?StyleGlyph}, ascender?: number, descender?: number}},\n glyphPositions: GlyphPositions,\n imagePositions: {[_: string]: ImagePosition},\n lines: Array<TaggedString>,\n lineHeight: number,\n textAnchor: SymbolAnchor,\n textJustify: TextJustify,\n writingMode: 1 | 2,\n spacing: number,\n allowVerticalPlacement: boolean,\n layoutTextSizeThisZoom: number) {\n\n let x = 0;\n let y = 0;\n\n let maxLineLength = 0;\n let maxLineHeight = 0;\n\n const justify =\n textJustify === 'right' ? 1 :\n textJustify === 'left' ? 0 : 0.5;\n\n let hasBaseline = false;\n for (const line of lines) {\n const sections = line.getSections();\n for (const section of sections) {\n if (section.imageName) continue;\n\n const glyphData = glyphMap[section.fontStack];\n if (!glyphData) continue;\n\n hasBaseline = glyphData.ascender !== undefined && glyphData.descender !== undefined;\n if (!hasBaseline) break;\n }\n if (!hasBaseline) break;\n }\n\n let lineIndex = 0;\n for (const line of lines) {\n line.trim();\n\n const lineMaxScale = line.getMaxScale();\n const maxLineOffset = (lineMaxScale - 1) * ONE_EM;\n const positionedLine = {positionedGlyphs: [], lineOffset: 0};\n shaping.positionedLines[lineIndex] = positionedLine;\n const positionedGlyphs = positionedLine.positionedGlyphs;\n let lineOffset = 0.0;\n\n if (!line.length()) {\n y += lineHeight; // Still need a line feed after empty line\n ++lineIndex;\n continue;\n }\n\n let biggestHeight = 0;\n let baselineOffset = 0;\n for (let i = 0; i < line.length(); i++) {\n const section = line.getSection(i);\n const sectionIndex = line.getSectionIndex(i);\n const codePoint = line.getCharCode(i);\n\n let sectionScale = section.scale;\n let metrics = null;\n let rect = null;\n let imageName = null;\n let verticalAdvance = ONE_EM;\n let glyphOffset = 0;\n\n const vertical = !(writingMode === WritingMode.horizontal ||\n // Don't verticalize glyphs that have no upright orientation if vertical placement is disabled.\n (!allowVerticalPlacement && !charHasUprightVerticalOrientation(codePoint)) ||\n // If vertical placement is enabled, don't verticalize glyphs that\n // are from complex text layout script, or whitespaces.\n (allowVerticalPlacement && (whitespace[codePoint] || charInComplexShapingScript(codePoint))));\n\n if (!section.imageName) {\n // Find glyph position in the glyph atlas, if bitmap is null,\n // glyphPosition will not exit in the glyphPosition map\n const glyphPositionData = glyphPositions[section.fontStack];\n if (!glyphPositionData) continue;\n if (glyphPositionData[codePoint]) {\n rect = glyphPositionData[codePoint];\n }\n const glyphData = glyphMap[section.fontStack];\n if (!glyphData) continue;\n const glyph = glyphData.glyphs[codePoint];\n if (!glyph) continue;\n\n metrics = glyph.metrics;\n verticalAdvance = codePoint !== 0x200b ? ONE_EM : 0;\n\n // In order to make different fonts aligned, they must share a general baseline that aligns with every\n // font's real baseline. Glyph's offset is counted from the top left corner, where the ascender line\n // starts.\n // First of all, each glyph's baseline lies on the center line of the shaping line. Since ascender\n // is above the baseline, the glyphOffset is the negative shift. Then, in order to make glyphs fit in\n // the shaping box, for each line, we shift the glyph with biggest height(with scale) to make its center\n // lie on the center line of the line, which will lead to a baseline shift. Then adjust the whole line\n // with the baseline offset we calculated from the shift.\n if (hasBaseline) {\n const ascender = glyphData.ascender !== undefined ? Math.abs(glyphData.ascender) : 0;\n const descender = glyphData.descender !== undefined ? Math.abs(glyphData.descender) : 0;\n const value = (ascender + descender) * sectionScale;\n if (biggestHeight < value) {\n biggestHeight = value;\n baselineOffset = (ascender - descender) / 2 * sectionScale;\n }\n glyphOffset = -ascender * sectionScale;\n } else {\n // If font's baseline is not applicable, fall back to use a default baseline offset, see\n // Shaping::yOffset. Since we're laying out at 24 points, we need also calculate how much it will\n // move when we scale up or down.\n glyphOffset = SHAPING_DEFAULT_OFFSET + (lineMaxScale - sectionScale) * ONE_EM;\n }\n } else {\n const imagePosition = imagePositions[section.imageName];\n if (!imagePosition) continue;\n imageName = section.imageName;\n shaping.iconsInText = shaping.iconsInText || true;\n rect = imagePosition.paddedRect;\n const size = imagePosition.displaySize;\n // If needed, allow to set scale factor for an image using\n // alias \"image-scale\" that could be alias for \"font-scale\"\n // when FormattedSection is an image section.\n sectionScale = sectionScale * ONE_EM / layoutTextSizeThisZoom;\n\n metrics = {width: size[0],\n height: size[1],\n left: IMAGE_PADDING,\n top: -GLYPH_PBF_BORDER,\n advance: vertical ? size[1] : size[0],\n localGlyph: false};\n\n if (!hasBaseline) {\n glyphOffset = SHAPING_DEFAULT_OFFSET + lineMaxScale * ONE_EM - size[1] * sectionScale;\n } else {\n // Based on node-fontnik: 'top = heightAboveBaseline - Ascender'(it is not valid for locally\n // generated glyph). Since the top is a constant: glyph's borderSize. So if we set image glyph with\n // 'ascender = height', it means we pull down the glyph under baseline with a distance of glyph's borderSize.\n const imageAscender = metrics.height;\n glyphOffset = -imageAscender * sectionScale;\n\n }\n verticalAdvance = metrics.advance;\n\n // Difference between height of an image and one EM at max line scale.\n // Pushes current line down if an image size is over 1 EM at max line scale.\n const offset = (vertical ? size[0] : size[1]) * sectionScale - ONE_EM * lineMaxScale;\n if (offset > 0 && offset > lineOffset) {\n lineOffset = offset;\n }\n }\n\n if (!vertical) {\n positionedGlyphs.push({glyph: codePoint, imageName, x, y: y + glyphOffset, vertical, scale: sectionScale, localGlyph: metrics.localGlyph, fontStack: section.fontStack, sectionIndex, metrics, rect});\n x += metrics.advance * sectionScale + spacing;\n } else {\n shaping.verticalizable = true;\n positionedGlyphs.push({glyph: codePoint, imageName, x, y: y + glyphOffset, vertical, scale: sectionScale, localGlyph: metrics.localGlyph, fontStack: section.fontStack, sectionIndex, metrics, rect});\n x += verticalAdvance * sectionScale + spacing;\n }\n }\n\n // Only justify if we placed at least one glyph\n if (positionedGlyphs.length !== 0) {\n const lineLength = x - spacing;\n maxLineLength = Math.max(lineLength, maxLineLength);\n // Justify the line so that its top is aligned with the current height of y, and its horizontal coordinates\n // are justified according to the TextJustifyType\n if (hasBaseline) {\n justifyLine(positionedGlyphs, justify, lineOffset, baselineOffset, lineHeight * lineMaxScale / 2);\n } else {\n // Scaled line height offset is counted in glyphOffset, so here just use an unscaled line height\n justifyLine(positionedGlyphs, justify, lineOffset, 0, lineHeight / 2);\n }\n }\n\n x = 0;\n const currentLineHeight = lineHeight * lineMaxScale + lineOffset;\n positionedLine.lineOffset = Math.max(lineOffset, maxLineOffset);\n y += currentLineHeight;\n maxLineHeight = Math.max(currentLineHeight, maxLineHeight);\n ++lineIndex;\n }\n\n const height = y;\n const {horizontalAlign, verticalAlign} = getAnchorAlignment(textAnchor);\n align(shaping.positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, height);\n // Calculate the bounding box\n shaping.top += -verticalAlign * height;\n shaping.bottom = shaping.top + height;\n shaping.left += -horizontalAlign * maxLineLength;\n shaping.right = shaping.left + maxLineLength;\n shaping.hasBaseline = hasBaseline;\n}\n\n// justify right = 1, left = 0, center = 0.5\nfunction justifyLine(positionedGlyphs: Array<PositionedGlyph>,\n justify: 1 | 0 | 0.5,\n lineOffset: number,\n baselineOffset: number,\n halfLineHeight: number) {\n if (!justify && !lineOffset && !baselineOffset && !halfLineHeight) {\n return;\n }\n const end = positionedGlyphs.length - 1;\n const lastGlyph = positionedGlyphs[end];\n const lastAdvance = lastGlyph.metrics.advance * lastGlyph.scale;\n const lineIndent = (lastGlyph.x + lastAdvance) * justify;\n\n for (let j = 0; j <= end; j++) {\n positionedGlyphs[j].x -= lineIndent;\n positionedGlyphs[j].y += lineOffset + baselineOffset + halfLineHeight;\n }\n}\n\nfunction align(positionedLines: Array<PositionedLine>,\n justify: number,\n horizontalAlign: number,\n verticalAlign: number,\n maxLineLength: number,\n blockHeight: number) {\n const shiftX = (justify - horizontalAlign) * maxLineLength;\n\n const shiftY = -blockHeight * verticalAlign;\n for (const line of positionedLines) {\n for (const positionedGlyph of line.positionedGlyphs) {\n positionedGlyph.x += shiftX;\n positionedGlyph.y += shiftY;\n }\n }\n}\n\nexport type PositionedIcon = {\n image: ImagePosition,\n top: number,\n bottom: number,\n left: number,\n right: number,\n collisionPadding?: [number, number, number, number]\n};\n\nfunction shapeIcon(image: ImagePosition, iconOffset: [number, number], iconAnchor: SymbolAnchor): PositionedIcon {\n const {horizontalAlign, verticalAlign} = getAnchorAlignment(iconAnchor);\n const dx = iconOffset[0];\n const dy = iconOffset[1];\n const x1 = dx - image.displaySize[0] * horizontalAlign;\n const x2 = x1 + image.displaySize[0];\n const y1 = dy - image.displaySize[1] * verticalAlign;\n const y2 = y1 + image.displaySize[1];\n return {image, top: y1, bottom: y2, left: x1, right: x2};\n}\n\nfunction fitIconToText(shapedIcon: PositionedIcon, shapedText: Shaping,\n textFit: string,\n padding: [ number, number, number, number ],\n iconOffset: [ number, number ], fontScale: number): PositionedIcon {\n assert(textFit !== 'none');\n assert(Array.isArray(padding) && padding.length === 4);\n assert(Array.isArray(iconOffset) && iconOffset.length === 2);\n\n const image = shapedIcon.image;\n\n let collisionPadding;\n if (image.content) {\n const content = image.content;\n const pixelRatio = image.pixelRatio || 1;\n collisionPadding = [\n content[0] / pixelRatio,\n content[1] / pixelRatio,\n image.displaySize[0] - content[2] / pixelRatio,\n image.displaySize[1] - content[3] / pixelRatio\n ];\n }\n\n // We don't respect the icon-anchor, because icon-text-fit is set. Instead,\n // the icon will be centered on the text, then stretched in the given\n // dimensions.\n\n const textLeft = shapedText.left * fontScale;\n const textRight = shapedText.right * fontScale;\n\n let top, right, bottom, left;\n if (textFit === 'width' || textFit === 'both') {\n // Stretched horizontally to the text width\n left = iconOffset[0] + textLeft - padding[3];\n right = iconOffset[0] + textRight + padding[1];\n } else {\n // Centered on the text\n left = iconOffset[0] + (textLeft + textRight - image.displaySize[0]) / 2;\n right = left + image.displaySize[0];\n }\n\n const textTop = shapedText.top * fontScale;\n const textBottom = shapedText.bottom * fontScale;\n if (textFit === 'height' || textFit === 'both') {\n // Stretched vertically to the text height\n top = iconOffset[1] + textTop - padding[0];\n bottom = iconOffset[1] + textBottom + padding[2];\n } else {\n // Centered on the text\n top = iconOffset[1] + (textTop + textBottom - image.displaySize[1]) / 2;\n bottom = top + image.displaySize[1];\n }\n\n return {image, top, right, bottom, left, collisionPadding};\n}\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport {register} from '../util/web_worker_transfer.js';\n\nclass Anchor extends Point {\n angle: any;\n z: number;\n segment: number | void;\n\n constructor(x: number, y: number, z: number, angle: number, segment?: number) {\n super(x, y);\n this.angle = angle;\n this.z = z;\n if (segment !== undefined) {\n this.segment = segment;\n }\n }\n\n clone(): Anchor {\n return new Anchor(this.x, this.y, this.z, this.angle, this.segment);\n }\n}\n\nregister(Anchor, 'Anchor');\n\nexport default Anchor;\n","// @flow\n\nexport default checkMaxAngle;\n\nimport type Point from '@mapbox/point-geometry';\nimport type Anchor from './anchor.js';\n\n/**\n * Labels placed around really sharp angles aren't readable. Check if any\n * part of the potential label has a combined angle that is too big.\n *\n * @param line\n * @param anchor The point on the line around which the label is anchored.\n * @param labelLength The length of the label in geometry units.\n * @param windowSize The check fails if the combined angles within a part of the line that is `windowSize` long is too big.\n * @param maxAngle The maximum combined angle that any window along the label is allowed to have.\n *\n * @returns {boolean} whether the label should be placed\n * @private\n */\nfunction checkMaxAngle(line: Array<Point>, anchor: Anchor, labelLength: number, windowSize: number, maxAngle: number): boolean {\n\n // horizontal labels always pass\n if (anchor.segment === undefined) return true;\n\n let p: Point = anchor;\n let index = anchor.segment + 1;\n let anchorDistance = 0;\n\n // move backwards along the line to the first segment the label appears on\n while (anchorDistance > -labelLength / 2) {\n index--;\n\n // there isn't enough room for the label after the beginning of the line\n if (index < 0) return false;\n\n anchorDistance -= line[index].dist(p);\n p = line[index];\n }\n\n anchorDistance += line[index].dist(line[index + 1]);\n index++;\n\n // store recent corners and their total angle difference\n const recentCorners = [];\n let recentAngleDelta = 0;\n\n // move forwards by the length of the label and check angles along the way\n while (anchorDistance < labelLength / 2) {\n const prev = line[index - 1];\n const current = line[index];\n const next = line[index + 1];\n\n // there isn't enough room for the label before the end of the line\n if (!next) return false;\n\n let angleDelta = prev.angleTo(current) - current.angleTo(next);\n // restrict angle to -pi..pi range\n angleDelta = Math.abs(((angleDelta + 3 * Math.PI) % (Math.PI * 2)) - Math.PI);\n\n recentCorners.push({\n distance: anchorDistance,\n angleDelta\n });\n recentAngleDelta += angleDelta;\n\n // remove corners that are far enough away from the list of recent anchors\n while (anchorDistance - recentCorners[0].distance > windowSize) {\n recentAngleDelta -= recentCorners.shift().angleDelta;\n }\n\n // the sum of angles within the window area exceeds the maximum allowed value. check fails.\n if (recentAngleDelta > maxAngle) return false;\n\n index++;\n anchorDistance += current.dist(next);\n }\n\n // no part of the line had an angle greater than the maximum allowed. check passes.\n return true;\n}\n","// @flow\n\nimport {number as interpolate} from '../style-spec/util/interpolate.js';\n\nimport Anchor from '../symbol/anchor.js';\nimport checkMaxAngle from './check_max_angle.js';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {Shaping, PositionedIcon} from './shaping.js';\n\nexport {getAnchors, getCenterAnchor};\n\nfunction getLineLength(line: Array<Point>): number {\n let lineLength = 0;\n for (let k = 0; k < line.length - 1; k++) {\n lineLength += line[k].dist(line[k + 1]);\n }\n return lineLength;\n}\n\nfunction getAngleWindowSize(shapedText: ?Shaping,\n glyphSize: number,\n boxScale: number): number {\n return shapedText ?\n 3 / 5 * glyphSize * boxScale :\n 0;\n}\n\nfunction getShapedLabelLength(shapedText: ?Shaping, shapedIcon: ?PositionedIcon): number {\n return Math.max(\n shapedText ? shapedText.right - shapedText.left : 0,\n shapedIcon ? shapedIcon.right - shapedIcon.left : 0);\n}\n\nfunction getCenterAnchor(line: Array<Point>,\n maxAngle: number,\n shapedText: ?Shaping,\n shapedIcon: ?PositionedIcon,\n glyphSize: number,\n boxScale: number): ?Anchor {\n const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale);\n const labelLength = getShapedLabelLength(shapedText, shapedIcon) * boxScale;\n\n let prevDistance = 0;\n const centerDistance = getLineLength(line) / 2;\n\n for (let i = 0; i < line.length - 1; i++) {\n\n const a = line[i],\n b = line[i + 1];\n\n const segmentDistance = a.dist(b);\n\n if (prevDistance + segmentDistance > centerDistance) {\n // The center is on this segment\n const t = (centerDistance - prevDistance) / segmentDistance,\n x = interpolate(a.x, b.x, t),\n y = interpolate(a.y, b.y, t);\n\n const anchor = new Anchor(x, y, 0, b.angleTo(a), i);\n if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) {\n return anchor;\n } else {\n return;\n }\n }\n\n prevDistance += segmentDistance;\n }\n}\n\nfunction getAnchors(line: Array<Point>,\n spacing: number,\n maxAngle: number,\n shapedText: ?Shaping,\n shapedIcon: ?PositionedIcon,\n glyphSize: number,\n boxScale: number,\n overscaling: number,\n tileExtent: number): Array<Anchor> {\n\n // Resample a line to get anchor points for labels and check that each\n // potential label passes text-max-angle check and has enough froom to fit\n // on the line.\n\n const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale);\n const shapedLabelLength = getShapedLabelLength(shapedText, shapedIcon);\n const labelLength = shapedLabelLength * boxScale;\n\n // Is the line continued from outside the tile boundary?\n const isLineContinued = line[0].x === 0 || line[0].x === tileExtent || line[0].y === 0 || line[0].y === tileExtent;\n\n // Is the label long, relative to the spacing?\n // If so, adjust the spacing so there is always a minimum space of `spacing / 4` between label edges.\n if (spacing - labelLength < spacing / 4) {\n spacing = labelLength + spacing / 4;\n }\n\n // Offset the first anchor by:\n // Either half the label length plus a fixed extra offset if the line is not continued\n // Or half the spacing if the line is continued.\n\n // For non-continued lines, add a bit of fixed extra offset to avoid collisions at T intersections.\n const fixedExtraOffset = glyphSize * 2;\n\n const offset = !isLineContinued ?\n ((shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling) % spacing :\n (spacing / 2 * overscaling) % spacing;\n\n return resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, false, tileExtent);\n}\n\nfunction resample(line: Array<Point>, offset: number, spacing: number, angleWindowSize: number, maxAngle: number, labelLength: number, isLineContinued: boolean, placeAtMiddle: boolean, tileExtent: number) {\n\n const halfLabelLength = labelLength / 2;\n const lineLength = getLineLength(line);\n\n let distance = 0,\n markedDistance = offset - spacing;\n\n let anchors = [];\n\n for (let i = 0; i < line.length - 1; i++) {\n\n const a = line[i],\n b = line[i + 1];\n\n const segmentDist = a.dist(b),\n angle = b.angleTo(a);\n\n while (markedDistance + spacing < distance + segmentDist) {\n markedDistance += spacing;\n\n const t = (markedDistance - distance) / segmentDist,\n x = interpolate(a.x, b.x, t),\n y = interpolate(a.y, b.y, t);\n\n // Check that the point is within the tile boundaries and that\n // the label would fit before the beginning and end of the line\n // if placed at this point.\n if (x >= 0 && x < tileExtent && y >= 0 && y < tileExtent &&\n markedDistance - halfLabelLength >= 0 &&\n markedDistance + halfLabelLength <= lineLength) {\n const anchor = new Anchor(x, y, 0, angle, i);\n anchor._round();\n\n if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) {\n anchors.push(anchor);\n }\n }\n }\n\n distance += segmentDist;\n }\n\n if (!placeAtMiddle && !anchors.length && !isLineContinued) {\n // The first attempt at finding anchors at which labels can be placed failed.\n // Try again, but this time just try placing one anchor at the middle of the line.\n // This has the most effect for short lines in overscaled tiles, since the\n // initial offset used in overscaled tiles is calculated to align labels with positions in\n // parent tiles instead of placing the label as close to the beginning as possible.\n anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, true, tileExtent);\n }\n\n return anchors;\n}\n","// @flow\n\nimport loadGlyphRange from '../style/load_glyph_range.js';\n\nimport TinySDF from '@mapbox/tiny-sdf';\nimport isChar from '../util/is_char_in_unicode_block.js';\nimport {asyncAll} from '../util/util.js';\nimport {AlphaImage} from '../util/image.js';\n\nimport type {StyleGlyph} from '../style/style_glyph.js';\nimport type {RequestManager} from '../util/mapbox.js';\nimport type {Callback} from '../types/callback.js';\n\n/*\n SDF_SCALE controls the pixel density of locally generated glyphs relative\n to \"normal\" SDFs which are generated at 24pt font and a \"pixel ratio\" of 1.\n The GlyphManager will generate glyphs SDF_SCALE times as large,\n but with the same glyph metrics, and the quad generation code will scale them\n back down so they display at the same size.\n\n The choice of SDF_SCALE is a trade-off between performance and quality.\n Glyph generation time grows quadratically with the the scale, while quality\n improvements drop off rapidly when the scale is higher than the pixel ratio\n of the device. The scale of 2 buys noticeable improvements on HDPI screens\n at acceptable cost.\n\n The scale can be any value, but in order to avoid small distortions, these\n pixel-based values must come out to integers:\n - \"localGlyphPadding\" in GlyphAtlas\n - Font/Canvas/Buffer size for TinySDF\n localGlyphPadding + buffer should equal 4 * SDF_SCALE. So if you wanted to\n use an SDF_SCALE of 1.75, you could manually set localGlyphAdding to 2 and\n buffer to 5.\n*/\nexport const SDF_SCALE = 2;\n\ntype Entry = {\n // null means we've requested the range, but the glyph wasn't included in the result.\n glyphs: {[id: number]: StyleGlyph | null},\n requests: {[range: number]: Array<Callback<{glyphs: {[number]: StyleGlyph | null}, ascender?: number, descender?: number}>>},\n ranges: {[range: number]: boolean | null},\n tinySDF?: TinySDF,\n ascender?: number,\n descender?: number\n};\n\nexport const LocalGlyphMode = {\n none: 0,\n ideographs: 1,\n all: 2\n};\n\nclass GlyphManager {\n requestManager: RequestManager;\n localFontFamily: ?string;\n localGlyphMode: number;\n entries: {[_: string]: Entry};\n // Multiple fontstacks may share the same local glyphs, so keep an index\n // into the glyphs based soley on font weight\n localGlyphs: {[_: string]: {glyphs: {[id: number]: StyleGlyph | null}, ascender: ?number, descender: ?number}};\n url: ?string;\n\n // exposed as statics to enable stubbing in unit tests\n static loadGlyphRange: typeof loadGlyphRange;\n static TinySDF: Class<TinySDF>;\n\n constructor(requestManager: RequestManager, localGlyphMode: number, localFontFamily: ?string) {\n this.requestManager = requestManager;\n this.localGlyphMode = localGlyphMode;\n this.localFontFamily = localFontFamily;\n this.entries = {};\n this.localGlyphs = {\n // Only these four font weights are supported\n '200': {},\n '400': {},\n '500': {},\n '900': {}\n };\n }\n\n setURL(url: ?string) {\n this.url = url;\n }\n\n getGlyphs(glyphs: {[stack: string]: Array<number>}, callback: Callback<{[stack: string]: {glyphs: {[_: number]: ?StyleGlyph}, ascender?: number, descender?: number}}>) {\n const all = [];\n\n for (const stack in glyphs) {\n for (const id of glyphs[stack]) {\n all.push({stack, id});\n }\n }\n\n asyncAll(all, ({stack, id}, fnCallback: Callback<{stack: string, id: number, glyph: ?StyleGlyph}>) => {\n let entry = this.entries[stack];\n if (!entry) {\n entry = this.entries[stack] = {\n glyphs: {},\n requests: {},\n ranges: {},\n ascender: undefined,\n descender: undefined\n };\n }\n\n let glyph = entry.glyphs[id];\n if (glyph !== undefined) {\n fnCallback(null, {stack, id, glyph});\n return;\n }\n\n glyph = this._tinySDF(entry, stack, id);\n if (glyph) {\n entry.glyphs[id] = glyph;\n fnCallback(null, {stack, id, glyph});\n return;\n }\n\n const range = Math.floor(id / 256);\n if (range * 256 > 65535) {\n fnCallback(new Error('glyphs > 65535 not supported'));\n return;\n }\n\n if (entry.ranges[range]) {\n fnCallback(null, {stack, id, glyph});\n return;\n }\n\n let requests = entry.requests[range];\n if (!requests) {\n requests = entry.requests[range] = [];\n GlyphManager.loadGlyphRange(stack, range, (this.url: any), this.requestManager,\n (err, response: ?{glyphs: {[_: number]: StyleGlyph | null}, ascender?: number, descender?: number}) => {\n if (response) {\n entry.ascender = response.ascender;\n entry.descender = response.descender;\n for (const id in response.glyphs) {\n if (!this._doesCharSupportLocalGlyph(+id)) {\n entry.glyphs[+id] = response.glyphs[+id];\n }\n }\n entry.ranges[range] = true;\n }\n for (const cb of requests) {\n cb(err, response);\n }\n delete entry.requests[range];\n });\n }\n\n requests.push((err, result: ?{glyphs: {[_: number]: StyleGlyph | null}, ascender?: number, descender?: number}) => {\n if (err) {\n fnCallback(err);\n } else if (result) {\n fnCallback(null, {stack, id, glyph: result.glyphs[id] || null});\n }\n });\n }, (err, glyphs: ?Array<{stack: string, id: number, glyph: ?StyleGlyph}>) => {\n if (err) {\n callback(err);\n } else if (glyphs) {\n const result = {};\n\n for (const {stack, id, glyph} of glyphs) {\n // Clone the glyph so that our own copy of its ArrayBuffer doesn't get transferred.\n if (result[stack] === undefined) result[stack] = {};\n if (result[stack].glyphs === undefined) result[stack].glyphs = {};\n result[stack].glyphs[id] = glyph && {\n id: glyph.id,\n bitmap: glyph.bitmap.clone(),\n metrics: glyph.metrics\n };\n result[stack].ascender = this.entries[stack].ascender;\n result[stack].descender = this.entries[stack].descender;\n }\n\n callback(null, result);\n }\n });\n }\n\n _doesCharSupportLocalGlyph(id: number): boolean {\n if (this.localGlyphMode === LocalGlyphMode.none) {\n return false;\n } else if (this.localGlyphMode === LocalGlyphMode.all) {\n return !!this.localFontFamily;\n } else {\n /* eslint-disable new-cap */\n return !!this.localFontFamily &&\n ((isChar['CJK Unified Ideographs'](id) ||\n isChar['Hangul Syllables'](id) ||\n isChar['Hiragana'](id) ||\n isChar['Katakana'](id)) ||\n // gl-native parity: Extend Ideographs rasterization range to include CJK symbols and punctuations\n isChar['CJK Symbols and Punctuation'](id));\n /* eslint-enable new-cap */\n }\n }\n\n _tinySDF(entry: Entry, stack: string, id: number): ?StyleGlyph {\n const fontFamily = this.localFontFamily;\n if (!fontFamily || !this._doesCharSupportLocalGlyph(id)) return;\n\n let tinySDF = entry.tinySDF;\n if (!tinySDF) {\n let fontWeight = '400';\n if (/bold/i.test(stack)) {\n fontWeight = '900';\n } else if (/medium/i.test(stack)) {\n fontWeight = '500';\n } else if (/light/i.test(stack)) {\n fontWeight = '200';\n }\n\n const fontSize = 24 * SDF_SCALE;\n const buffer = 3 * SDF_SCALE;\n const radius = 8 * SDF_SCALE;\n tinySDF = entry.tinySDF = new GlyphManager.TinySDF({fontFamily, fontWeight, fontSize, buffer, radius});\n tinySDF.fontWeight = fontWeight;\n }\n\n if (this.localGlyphs[tinySDF.fontWeight][id]) {\n return this.localGlyphs[tinySDF.fontWeight][id];\n }\n\n const char = String.fromCharCode(id);\n const {data, width, height, glyphWidth, glyphHeight, glyphLeft, glyphTop, glyphAdvance} = tinySDF.draw(char);\n /*\n TinySDF's \"top\" is the distance from the alphabetic baseline to the\n top of the glyph.\n\n Server-generated fonts specify \"top\" relative to an origin above the\n em box (the origin comes from FreeType, but I'm unclear on exactly\n how it's derived)\n ref: https://github.com/mapbox/sdf-glyph-foundry\n\n Server fonts don't yet include baseline information, so we can't line\n up exactly with them (and they don't line up with each other)\n ref: https://github.com/mapbox/node-fontnik/pull/160\n\n To approximately align TinySDF glyphs with server-provided glyphs, we\n use this baseline adjustment factor calibrated to be in between DIN Pro\n and Arial Unicode (but closer to Arial Unicode)\n */\n const baselineAdjustment = 27;\n\n const glyph = this.localGlyphs[tinySDF.fontWeight][id] = {\n id,\n bitmap: new AlphaImage({width, height}, data),\n metrics: {\n width: glyphWidth / SDF_SCALE,\n height: glyphHeight / SDF_SCALE,\n left: glyphLeft / SDF_SCALE,\n top: glyphTop / SDF_SCALE - baselineAdjustment,\n advance: glyphAdvance / SDF_SCALE,\n localGlyph: true\n }\n };\n return glyph;\n }\n}\n\nGlyphManager.loadGlyphRange = loadGlyphRange;\nGlyphManager.TinySDF = TinySDF;\n\nexport default GlyphManager;\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport {GLYPH_PBF_BORDER} from '../style/parse_glyph_pbf.js';\n\nimport type Anchor from './anchor.js';\nimport type {PositionedIcon, Shaping} from './shaping.js';\nimport {IMAGE_PADDING} from '../render/image_atlas.js';\nimport {SDF_SCALE} from '../render/glyph_manager.js';\nimport type SymbolStyleLayer from '../style/style_layer/symbol_style_layer.js';\nimport type {Feature} from '../style-spec/expression/index.js';\nimport type {StyleImage} from '../style/style_image.js';\nimport {isVerticalClosePunctuation, isVerticalOpenPunctuation} from '../util/verticalize_punctuation.js';\nimport ONE_EM from './one_em.js';\nimport {warnOnce} from '../util/util.js';\n\ntype Size = {| fixed: number, stretch: number |};\n\n/**\n * A textured quad for rendering a single icon or glyph.\n *\n * The zoom range the glyph can be shown is defined by minScale and maxScale.\n *\n * @param tl The offset of the top left corner from the anchor.\n * @param tr The offset of the top right corner from the anchor.\n * @param bl The offset of the bottom left corner from the anchor.\n * @param br The offset of the bottom right corner from the anchor.\n * @param tex The texture coordinates.\n *\n * @private\n */\nexport type SymbolQuad = {\n tl: Point,\n tr: Point,\n bl: Point,\n br: Point,\n tex: {\n x: number,\n y: number,\n w: number,\n h: number\n },\n pixelOffsetTL: Point,\n pixelOffsetBR: Point,\n writingMode: any | void,\n glyphOffset: [number, number],\n sectionIndex: number,\n isSDF: boolean,\n minFontScaleX: number,\n minFontScaleY: number\n};\n\n// If you have a 10px icon that isn't perfectly aligned to the pixel grid it will cover 11 actual\n// pixels. The quad needs to be padded to account for this, otherwise they'll look slightly clipped\n// on one edge in some cases.\nconst border = IMAGE_PADDING;\n\n/**\n * Create the quads used for rendering an icon.\n * @private\n */\nexport function getIconQuads(\n shapedIcon: PositionedIcon,\n iconRotate: number,\n isSDFIcon: boolean,\n hasIconTextFit: boolean): Array<SymbolQuad> {\n const quads = [];\n\n const image = shapedIcon.image;\n const pixelRatio = image.pixelRatio;\n const imageWidth = image.paddedRect.w - 2 * border;\n const imageHeight = image.paddedRect.h - 2 * border;\n\n const iconWidth = shapedIcon.right - shapedIcon.left;\n const iconHeight = shapedIcon.bottom - shapedIcon.top;\n\n const stretchX = image.stretchX || [[0, imageWidth]];\n const stretchY = image.stretchY || [[0, imageHeight]];\n\n const reduceRanges = (sum: number, range: [number, number]) => sum + range[1] - range[0];\n const stretchWidth = stretchX.reduce(reduceRanges, 0);\n const stretchHeight = stretchY.reduce(reduceRanges, 0);\n const fixedWidth = imageWidth - stretchWidth;\n const fixedHeight = imageHeight - stretchHeight;\n\n let stretchOffsetX = 0;\n let stretchContentWidth = stretchWidth;\n let stretchOffsetY = 0;\n let stretchContentHeight = stretchHeight;\n let fixedOffsetX = 0;\n let fixedContentWidth = fixedWidth;\n let fixedOffsetY = 0;\n let fixedContentHeight = fixedHeight;\n\n if (image.content && hasIconTextFit) {\n const content = image.content;\n stretchOffsetX = sumWithinRange(stretchX, 0, content[0]);\n stretchOffsetY = sumWithinRange(stretchY, 0, content[1]);\n stretchContentWidth = sumWithinRange(stretchX, content[0], content[2]);\n stretchContentHeight = sumWithinRange(stretchY, content[1], content[3]);\n fixedOffsetX = content[0] - stretchOffsetX;\n fixedOffsetY = content[1] - stretchOffsetY;\n fixedContentWidth = content[2] - content[0] - stretchContentWidth;\n fixedContentHeight = content[3] - content[1] - stretchContentHeight;\n }\n\n const makeBox = (left: Size, top: Size, right: Size, bottom: Size) => {\n\n const leftEm = getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left);\n const leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth);\n\n const topEm = getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top);\n const topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight);\n\n const rightEm = getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left);\n const rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth);\n\n const bottomEm = getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top);\n const bottomPx = getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight);\n\n const tl = new Point(leftEm, topEm);\n const tr = new Point(rightEm, topEm);\n const br = new Point(rightEm, bottomEm);\n const bl = new Point(leftEm, bottomEm);\n const pixelOffsetTL = new Point(leftPx / pixelRatio, topPx / pixelRatio);\n const pixelOffsetBR = new Point(rightPx / pixelRatio, bottomPx / pixelRatio);\n\n const angle = iconRotate * Math.PI / 180;\n\n if (angle) {\n const sin = Math.sin(angle),\n cos = Math.cos(angle),\n matrix = [cos, -sin, sin, cos];\n\n tl._matMult(matrix);\n tr._matMult(matrix);\n bl._matMult(matrix);\n br._matMult(matrix);\n }\n\n const x1 = left.stretch + left.fixed;\n const x2 = right.stretch + right.fixed;\n const y1 = top.stretch + top.fixed;\n const y2 = bottom.stretch + bottom.fixed;\n\n const subRect = {\n x: image.paddedRect.x + border + x1,\n y: image.paddedRect.y + border + y1,\n w: x2 - x1,\n h: y2 - y1\n };\n\n const minFontScaleX = fixedContentWidth / pixelRatio / iconWidth;\n const minFontScaleY = fixedContentHeight / pixelRatio / iconHeight;\n\n // Icon quad is padded, so texture coordinates also need to be padded.\n return {tl, tr, bl, br, tex: subRect, writingMode: undefined, glyphOffset: [0, 0], sectionIndex: 0, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, isSDF: isSDFIcon};\n };\n\n if (!hasIconTextFit || (!image.stretchX && !image.stretchY)) {\n quads.push(makeBox(\n {fixed: 0, stretch: -1},\n {fixed: 0, stretch: -1},\n {fixed: 0, stretch: imageWidth + 1},\n {fixed: 0, stretch: imageHeight + 1}));\n } else {\n const xCuts = stretchZonesToCuts(stretchX, fixedWidth, stretchWidth);\n const yCuts = stretchZonesToCuts(stretchY, fixedHeight, stretchHeight);\n\n for (let xi = 0; xi < xCuts.length - 1; xi++) {\n const x1 = xCuts[xi];\n const x2 = xCuts[xi + 1];\n for (let yi = 0; yi < yCuts.length - 1; yi++) {\n const y1 = yCuts[yi];\n const y2 = yCuts[yi + 1];\n quads.push(makeBox(x1, y1, x2, y2));\n }\n }\n }\n\n return quads;\n}\n\nfunction sumWithinRange(ranges: Array<[number, number]>, min: number, max: number) {\n let sum = 0;\n for (const range of ranges) {\n sum += Math.max(min, Math.min(max, range[1])) - Math.max(min, Math.min(max, range[0]));\n }\n return sum;\n}\n\nfunction stretchZonesToCuts(stretchZones: Array<[number, number]>, fixedSize: number, stretchSize: number) {\n const cuts = [{fixed: -border, stretch: 0}];\n\n for (const [c1, c2] of stretchZones) {\n const last = cuts[cuts.length - 1];\n cuts.push({\n fixed: c1 - last.stretch,\n stretch: last.stretch\n });\n cuts.push({\n fixed: c1 - last.stretch,\n stretch: last.stretch + (c2 - c1)\n });\n }\n cuts.push({\n fixed: fixedSize + border,\n stretch: stretchSize\n });\n return cuts;\n}\n\nfunction getEmOffset(stretchOffset: number, stretchSize: number, iconSize: number, iconOffset: number) {\n return stretchOffset / stretchSize * iconSize + iconOffset;\n}\n\nfunction getPxOffset(fixedOffset: number, fixedSize: number, stretchOffset: number, stretchSize: number) {\n return fixedOffset - fixedSize * stretchOffset / stretchSize;\n}\n\nfunction getRotateOffset(textOffset: [number, number]) {\n const x = textOffset[0], y = textOffset[1];\n const product = x * y;\n if (product > 0) {\n return [x, -y];\n } else if (product < 0) {\n return [-x, y];\n } else if (x === 0) {\n return [y, x];\n } else {\n return [y, -x];\n }\n}\n\nfunction getMidlineOffset(shaping: Shaping, lineHeight: number, previousOffset: number, lineIndex: number) {\n const currentLineHeight = (lineHeight + shaping.positionedLines[lineIndex].lineOffset);\n if (lineIndex === 0) {\n return previousOffset + currentLineHeight / 2.0;\n }\n const aboveLineHeight = (lineHeight + shaping.positionedLines[lineIndex - 1].lineOffset);\n return previousOffset + (currentLineHeight + aboveLineHeight) / 2.0;\n}\n\n/**\n * Create the quads used for rendering a text label.\n * @private\n */\nexport function getGlyphQuads(anchor: Anchor,\n shaping: Shaping,\n textOffset: [number, number],\n layer: SymbolStyleLayer,\n alongLine: boolean,\n feature: Feature,\n imageMap: {[_: string]: StyleImage},\n allowVerticalPlacement: boolean): Array<SymbolQuad> {\n const quads = [];\n if (shaping.positionedLines.length === 0) return quads;\n\n const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}) * Math.PI / 180;\n const rotateOffset = getRotateOffset(textOffset);\n\n let shapingHeight = Math.abs(shaping.top - shaping.bottom);\n for (const line of shaping.positionedLines) {\n shapingHeight -= line.lineOffset;\n }\n const lineCounts = shaping.positionedLines.length;\n const lineHeight = shapingHeight / lineCounts;\n let currentOffset = shaping.top - textOffset[1];\n for (let lineIndex = 0; lineIndex < lineCounts; ++lineIndex) {\n const line = shaping.positionedLines[lineIndex];\n currentOffset = getMidlineOffset(shaping, lineHeight, currentOffset, lineIndex);\n for (const positionedGlyph of line.positionedGlyphs) {\n if (!positionedGlyph.rect) continue;\n const textureRect = positionedGlyph.rect || {};\n\n // The rects have an additional buffer that is not included in their size.\n const glyphPadding = 1.0;\n let rectBuffer = GLYPH_PBF_BORDER + glyphPadding;\n let isSDF = true;\n let pixelRatio = 1.0;\n let lineOffset = 0.0;\n if (positionedGlyph.imageName) {\n const image = imageMap[positionedGlyph.imageName];\n if (!image) continue;\n if (image.sdf) {\n warnOnce(\"SDF images are not supported in formatted text and will be ignored.\");\n continue;\n }\n isSDF = false;\n pixelRatio = image.pixelRatio;\n rectBuffer = IMAGE_PADDING / pixelRatio;\n }\n\n const rotateVerticalGlyph = (alongLine || allowVerticalPlacement) && positionedGlyph.vertical;\n const halfAdvance = positionedGlyph.metrics.advance * positionedGlyph.scale / 2;\n const metrics = positionedGlyph.metrics;\n const rect = positionedGlyph.rect;\n if (rect === null) continue;\n\n // Align images and scaled glyphs in the middle of a vertical line.\n if (allowVerticalPlacement && shaping.verticalizable) {\n // image's advance for vertical shaping is its height, so that we have to take the difference into\n // account after image glyph is rotated\n lineOffset = positionedGlyph.imageName ? halfAdvance - positionedGlyph.metrics.width * positionedGlyph.scale / 2.0 : 0;\n }\n\n const glyphOffset = alongLine ?\n [positionedGlyph.x + halfAdvance, positionedGlyph.y] :\n [0, 0];\n\n let builtInOffset = [0, 0];\n let verticalizedLabelOffset = [0, 0];\n let useRotateOffset = false;\n if (!alongLine) {\n if (rotateVerticalGlyph) {\n // Vertical POI labels that are rotated 90deg CW and whose glyphs must preserve upright orientation\n // need to be rotated 90deg CCW. After a quad is rotated, it is translated to the original built-in offset.\n verticalizedLabelOffset =\n [positionedGlyph.x + halfAdvance + rotateOffset[0], positionedGlyph.y + rotateOffset[1] - lineOffset];\n useRotateOffset = true;\n } else {\n builtInOffset = [positionedGlyph.x + halfAdvance + textOffset[0], positionedGlyph.y + textOffset[1] - lineOffset];\n }\n }\n\n const paddedWidth =\n rect.w * positionedGlyph.scale / (pixelRatio * (positionedGlyph.localGlyph ? SDF_SCALE : 1));\n const paddedHeight =\n rect.h * positionedGlyph.scale / (pixelRatio * (positionedGlyph.localGlyph ? SDF_SCALE : 1));\n\n let tl, tr, bl, br;\n if (!rotateVerticalGlyph) {\n const x1 = (metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset[0];\n const y1 = (-metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset[1];\n const x2 = x1 + paddedWidth;\n const y2 = y1 + paddedHeight;\n\n tl = new Point(x1, y1);\n tr = new Point(x2, y1);\n bl = new Point(x1, y2);\n br = new Point(x2, y2);\n } else {\n // For vertical glyph placement, follow the steps to put the glyph bitmap in right coordinates:\n // 1. Rotate the glyph by using original glyph coordinates instead of padded coordinates, since the\n // rotation center and xOffsetCorrection are all based on original glyph's size.\n // 2. Do x offset correction so that 'tl' is shifted to the same x coordinate before rotation.\n // 3. Adjust glyph positon for 'tl' by applying vertial padding and horizontal shift, now 'tl' is the\n // coordinate where we draw the glyph bitmap.\n // 4. Calculate other three bitmap coordinates.\n\n // Vertical-supporting glyphs are laid out in 24x24 point boxes (1 square em)\n // In horizontal orientation, the \"yShift\" is the negative value of the height that\n // the glyph is above the horizontal midline.\n // By rotating counter-clockwise around the point at the center of the left\n // edge of a 24x24 layout box centered below the midline, we align the midline\n // of the rotated glyphs with the horizontal midline, so the yShift is no longer\n // necessary, but we also pull the glyph to the left along the x axis.\n const yShift = (positionedGlyph.y - currentOffset);\n const center = new Point(-halfAdvance, halfAdvance - yShift);\n const verticalRotation = -Math.PI / 2;\n const verticalOffsetCorrection = new Point(...verticalizedLabelOffset);\n // Relative position before rotation\n // tl ----- tr\n // | |\n // | |\n // bl ----- br\n tl = new Point(-halfAdvance + builtInOffset[0], builtInOffset[1]);\n tl._rotateAround(verticalRotation, center)._add(verticalOffsetCorrection);\n\n // Relative position after rotating\n // tr ----- br\n // | |\n // | |\n // tl ----- bl\n // After rotation, glyph lies on the horizontal midline.\n // Shift back to tl's original x coordinate before rotation by applying 'xOffsetCorrection'.\n tl.x += -yShift + halfAdvance;\n\n // Add padding for y coordinate's justification\n tl.y -= (metrics.left - rectBuffer) * positionedGlyph.scale;\n\n // Adjust x coordinate according to glyph bitmap's height and the vectical advance\n const verticalAdvance = positionedGlyph.imageName ? metrics.advance * positionedGlyph.scale :\n ONE_EM * positionedGlyph.scale;\n // Check wether the glyph is generated from server side or locally\n const chr = String.fromCharCode(positionedGlyph.glyph);\n if (isVerticalClosePunctuation(chr)) {\n // Place vertical punctuation in right place, pull down 1 pixel's space for close punctuations\n tl.x += (-rectBuffer + 1) * positionedGlyph.scale;\n } else if (isVerticalOpenPunctuation(chr)) {\n const xOffset = verticalAdvance - metrics.height * positionedGlyph.scale;\n // Place vertical punctuation in right place, pull up 1 pixel's space for open punctuations\n tl.x += xOffset + (-rectBuffer - 1) * positionedGlyph.scale;\n } else if (!positionedGlyph.imageName &&\n ((metrics.width + rectBuffer * 2) !== rect.w || metrics.height + rectBuffer * 2 !== rect.h)) {\n // Locally generated glyphs' bitmap do not have exact 'rectBuffer' padded around the glyphs,\n // but the original tl do have distance of rectBuffer padded to the top of the glyph.\n const perfectPaddedHeight = (metrics.height + rectBuffer * 2) * positionedGlyph.scale;\n const delta = verticalAdvance - perfectPaddedHeight;\n tl.x += delta / 2;\n } else {\n // Place the glyph bitmap right in the center of the 24x24 point boxes\n const delta = verticalAdvance - paddedHeight;\n tl.x += delta / 2;\n }\n // Calculate other three points\n tr = new Point(tl.x, tl.y - paddedWidth);\n bl = new Point(tl.x + paddedHeight, tl.y);\n br = new Point(tl.x + paddedHeight, tl.y - paddedWidth);\n }\n\n if (textRotate) {\n let center;\n if (!alongLine) {\n if (useRotateOffset) {\n center = new Point(rotateOffset[0], rotateOffset[1]);\n } else {\n center = new Point(textOffset[0], textOffset[1]);\n }\n } else {\n center = new Point(0, 0);\n }\n tl._rotateAround(textRotate, center);\n tr._rotateAround(textRotate, center);\n bl._rotateAround(textRotate, center);\n br._rotateAround(textRotate, center);\n }\n\n const pixelOffsetTL = new Point(0, 0);\n const pixelOffsetBR = new Point(0, 0);\n const minFontScaleX = 0;\n const minFontScaleY = 0;\n quads.push({tl, tr, bl, br, tex: textureRect, writingMode: shaping.writingMode, glyphOffset, sectionIndex: positionedGlyph.sectionIndex, isSDF, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY});\n }\n }\n\n return quads;\n}\n","\nexport default class TinyQueue {\n constructor(data = [], compare = defaultCompare) {\n this.data = data;\n this.length = this.data.length;\n this.compare = compare;\n\n if (this.length > 0) {\n for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i);\n }\n }\n\n push(item) {\n this.data.push(item);\n this.length++;\n this._up(this.length - 1);\n }\n\n pop() {\n if (this.length === 0) return undefined;\n\n const top = this.data[0];\n const bottom = this.data.pop();\n this.length--;\n\n if (this.length > 0) {\n this.data[0] = bottom;\n this._down(0);\n }\n\n return top;\n }\n\n peek() {\n return this.data[0];\n }\n\n _up(pos) {\n const {data, compare} = this;\n const item = data[pos];\n\n while (pos > 0) {\n const parent = (pos - 1) >> 1;\n const current = data[parent];\n if (compare(item, current) >= 0) break;\n data[pos] = current;\n pos = parent;\n }\n\n data[pos] = item;\n }\n\n _down(pos) {\n const {data, compare} = this;\n const halfLength = this.length >> 1;\n const item = data[pos];\n\n while (pos < halfLength) {\n let left = (pos << 1) + 1;\n let best = data[left];\n const right = left + 1;\n\n if (right < this.length && compare(data[right], best) < 0) {\n left = right;\n best = data[right];\n }\n if (compare(best, item) >= 0) break;\n\n data[pos] = best;\n pos = left;\n }\n\n data[pos] = item;\n }\n}\n\nfunction defaultCompare(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","// @flow\n\nimport Queue from 'tinyqueue';\n\nimport Point from '@mapbox/point-geometry';\nimport {distToSegmentSquared} from './intersection_tests.js';\n\n/**\n * Finds an approximation of a polygon's Pole Of Inaccessibility https://en.wikipedia.org/wiki/Pole_of_inaccessibility\n * This is a copy of http://github.com/mapbox/polylabel adapted to use Points\n *\n * @param polygonRings first item in array is the outer ring followed optionally by the list of holes, should be an element of the result of util/classify_rings\n * @param precision Specified in input coordinate units. If 0 returns after first run, if > 0 repeatedly narrows the search space until the radius of the area searched for the best pole is less than precision\n * @param debug Print some statistics to the console during execution\n * @returns Pole of Inaccessibility.\n * @private\n */\nexport default function (polygonRings: Array<Array<Point>>, precision?: number = 1, debug?: boolean = false): Point {\n // find the bounding box of the outer ring\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n const outerRing = polygonRings[0];\n for (let i = 0; i < outerRing.length; i++) {\n const p = outerRing[i];\n if (!i || p.x < minX) minX = p.x;\n if (!i || p.y < minY) minY = p.y;\n if (!i || p.x > maxX) maxX = p.x;\n if (!i || p.y > maxY) maxY = p.y;\n }\n\n const width = maxX - minX;\n const height = maxY - minY;\n const cellSize = Math.min(width, height);\n let h = cellSize / 2;\n\n // a priority queue of cells in order of their \"potential\" (max distance to polygon)\n const cellQueue = new Queue([], compareMax);\n\n if (cellSize === 0) return new Point(minX, minY);\n\n // cover polygon with initial cells\n for (let x = minX; x < maxX; x += cellSize) {\n for (let y = minY; y < maxY; y += cellSize) {\n cellQueue.push(new Cell(x + h, y + h, h, polygonRings));\n }\n }\n\n // take centroid as the first best guess\n let bestCell = getCentroidCell(polygonRings);\n let numProbes = cellQueue.length;\n\n while (cellQueue.length) {\n // pick the most promising cell from the queue\n const cell = cellQueue.pop();\n\n // update the best cell if we found a better one\n if (cell.d > bestCell.d || !bestCell.d) {\n bestCell = cell;\n if (debug) console.log('found best %d after %d probes', Math.round(1e4 * cell.d) / 1e4, numProbes);\n }\n\n // do not drill down further if there's no chance of a better solution\n if (cell.max - bestCell.d <= precision) continue;\n\n // split the cell into four cells\n h = cell.h / 2;\n cellQueue.push(new Cell(cell.p.x - h, cell.p.y - h, h, polygonRings));\n cellQueue.push(new Cell(cell.p.x + h, cell.p.y - h, h, polygonRings));\n cellQueue.push(new Cell(cell.p.x - h, cell.p.y + h, h, polygonRings));\n cellQueue.push(new Cell(cell.p.x + h, cell.p.y + h, h, polygonRings));\n numProbes += 4;\n }\n\n if (debug) {\n console.log(`num probes: ${numProbes}`);\n console.log(`best distance: ${bestCell.d}`);\n }\n\n return bestCell.p;\n}\n\nfunction compareMax(a: Cell, b: Cell) {\n return b.max - a.max;\n}\n\nclass Cell {\n p: Point;\n h: number;\n d: number;\n max: number;\n\n constructor(x: number, y: number, h: number, polygon: Array<Array<Point>>) {\n this.p = new Point(x, y);\n this.h = h; // half the cell size\n this.d = pointToPolygonDist(this.p, polygon); // distance from cell center to polygon\n this.max = this.d + this.h * Math.SQRT2; // max distance to polygon within a cell\n }\n}\n\n// signed distance from point to polygon outline (negative if point is outside)\nfunction pointToPolygonDist(p: Point, polygon: Array<Array<Point>>) {\n let inside = false;\n let minDistSq = Infinity;\n\n for (let k = 0; k < polygon.length; k++) {\n const ring = polygon[k];\n\n for (let i = 0, len = ring.length, j = len - 1; i < len; j = i++) {\n const a = ring[i];\n const b = ring[j];\n\n if ((a.y > p.y !== b.y > p.y) &&\n (p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x)) inside = !inside;\n\n minDistSq = Math.min(minDistSq, distToSegmentSquared(p, a, b));\n }\n }\n\n return (inside ? 1 : -1) * Math.sqrt(minDistSq);\n}\n\n// get polygon centroid\nfunction getCentroidCell(polygon: Array<Array<Point>>) {\n let area = 0;\n let x = 0;\n let y = 0;\n const points = polygon[0];\n for (let i = 0, len = points.length, j = len - 1; i < len; j = i++) {\n const a = points[i];\n const b = points[j];\n const f = a.x * b.y - b.x * a.y;\n x += (a.x + b.x) * f;\n y += (a.y + b.y) * f;\n area += f * 3;\n }\n return new Cell(x / area, y / area, 0, polygon);\n}\n","// @flow\n\nimport Anchor from './anchor.js';\n\nimport {getAnchors, getCenterAnchor} from './get_anchors.js';\nimport clipLine from './clip_line.js';\nimport {shapeText, shapeIcon, WritingMode, fitIconToText} from './shaping.js';\nimport {getGlyphQuads, getIconQuads} from './quads.js';\nimport {warnOnce, degToRad} from '../util/util.js';\nimport {\n allowsVerticalWritingMode,\n allowsLetterSpacing\n} from '../util/script_detection.js';\nimport findPoleOfInaccessibility from '../util/find_pole_of_inaccessibility.js';\nimport classifyRings from '../util/classify_rings.js';\nimport EXTENT from '../data/extent.js';\nimport SymbolBucket from '../data/bucket/symbol_bucket.js';\nimport EvaluationParameters from '../style/evaluation_parameters.js';\nimport {SIZE_PACK_FACTOR} from './symbol_size.js';\nimport ONE_EM from './one_em.js';\nimport type {CanonicalTileID} from '../source/tile_id.js';\nimport type {Shaping, PositionedIcon, TextJustify} from './shaping.js';\nimport type {CollisionBoxArray} from '../data/array_types.js';\nimport type {SymbolFeature} from '../data/bucket/symbol_bucket.js';\nimport type {StyleImage} from '../style/style_image.js';\nimport type {StyleGlyph} from '../style/style_glyph.js';\nimport type SymbolStyleLayer from '../style/style_layer/symbol_style_layer.js';\nimport type {ImagePosition} from '../render/image_atlas.js';\nimport type {GlyphPositions} from '../render/glyph_atlas.js';\nimport type {PossiblyEvaluatedPropertyValue} from '../style/properties.js';\nimport type Projection from '../geo/projection/projection.js';\nimport type {Vec3} from 'gl-matrix';\n\nimport Point from '@mapbox/point-geometry';\nimport murmur3 from 'murmurhash-js';\n\n// The symbol layout process needs `text-size` evaluated at up to five different zoom levels, and\n// `icon-size` at up to three:\n//\n// 1. `text-size` at the zoom level of the bucket. Used to calculate a per-feature size for source `text-size`\n// expressions, and to calculate the box dimensions for icon-text-fit.\n// 2. `icon-size` at the zoom level of the bucket. Used to calculate a per-feature size for source `icon-size`\n// expressions.\n// 3. `text-size` and `icon-size` at the zoom level of the bucket, plus one. Used to calculate collision boxes.\n// 4. `text-size` at zoom level 18. Used for something line-symbol-placement-related.\n// 5. For composite `*-size` expressions: two zoom levels of curve stops that \"cover\" the zoom level of the\n// bucket. These go into a vertex buffer and are used by the shader to interpolate the size at render time.\n//\n// (1) and (2) are stored in `bucket.layers[0].layout`. The remainder are below.\n//\ntype Sizes = {\n layoutTextSize: PossiblyEvaluatedPropertyValue<number>, // (3)\n layoutIconSize: PossiblyEvaluatedPropertyValue<number>, // (3)\n textMaxSize: PossiblyEvaluatedPropertyValue<number>, // (4)\n compositeTextSizes: [PossiblyEvaluatedPropertyValue<number>, PossiblyEvaluatedPropertyValue<number>], // (5)\n compositeIconSizes: [PossiblyEvaluatedPropertyValue<number>, PossiblyEvaluatedPropertyValue<number>], // (5)\n};\n\nexport type TextAnchor = 'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n\n// The radial offset is to the edge of the text box\n// In the horizontal direction, the edge of the text box is where glyphs start\n// But in the vertical direction, the glyphs appear to \"start\" at the baseline\n// We don't actually load baseline data, but we assume an offset of ONE_EM - 17\n// (see \"yOffset\" in shaping.js)\nconst baselineOffset = 7;\nconst INVALID_TEXT_OFFSET = Number.POSITIVE_INFINITY;\nconst sqrt2 = Math.sqrt(2);\n\nexport function evaluateVariableOffset(anchor: TextAnchor, [offsetX, offsetY]: [number, number]): [number, number] {\n let x = 0, y = 0;\n\n if (offsetY === INVALID_TEXT_OFFSET) { // radial offset\n if (offsetX < 0) offsetX = 0; // Ignore negative offset.\n // solve for r where r^2 + r^2 = offsetX^2\n const hypotenuse = offsetX / sqrt2;\n switch (anchor) {\n case 'top-right':\n case 'top-left':\n y = hypotenuse - baselineOffset;\n break;\n case 'bottom-right':\n case 'bottom-left':\n y = -hypotenuse + baselineOffset;\n break;\n case 'bottom':\n y = -offsetX + baselineOffset;\n break;\n case 'top':\n y = offsetX - baselineOffset;\n break;\n }\n\n switch (anchor) {\n case 'top-right':\n case 'bottom-right':\n x = -hypotenuse;\n break;\n case 'top-left':\n case 'bottom-left':\n x = hypotenuse;\n break;\n case 'left':\n x = offsetX;\n break;\n case 'right':\n x = -offsetX;\n break;\n }\n\n } else { // text offset\n // Use absolute offset values.\n offsetX = Math.abs(offsetX);\n offsetY = Math.abs(offsetY);\n\n switch (anchor) {\n case 'top-right':\n case 'top-left':\n case 'top':\n y = offsetY - baselineOffset;\n break;\n case 'bottom-right':\n case 'bottom-left':\n case 'bottom':\n y = -offsetY + baselineOffset;\n break;\n }\n\n switch (anchor) {\n case 'top-right':\n case 'bottom-right':\n case 'right':\n x = -offsetX;\n break;\n case 'top-left':\n case 'bottom-left':\n case 'left':\n x = offsetX;\n break;\n }\n }\n\n return [x, y];\n}\n\nexport function performSymbolLayout(bucket: SymbolBucket,\n glyphMap: {[_: string]: {glyphs: {[_: number]: ?StyleGlyph}, ascender?: number, descender?: number}},\n glyphPositions: GlyphPositions,\n imageMap: {[_: string]: StyleImage},\n imagePositions: {[_: string]: ImagePosition},\n showCollisionBoxes: boolean,\n availableImages: Array<string>,\n canonical: CanonicalTileID,\n tileZoom: number,\n projection: Projection) {\n bucket.createArrays();\n\n const tileSize = 512 * bucket.overscaling;\n bucket.tilePixelRatio = EXTENT / tileSize;\n bucket.compareText = {};\n bucket.iconsNeedLinear = false;\n\n const layout = bucket.layers[0].layout;\n const unevaluatedLayoutValues = bucket.layers[0]._unevaluatedLayout._values;\n\n const sizes = {};\n\n if (bucket.textSizeData.kind === 'composite') {\n const {minZoom, maxZoom} = bucket.textSizeData;\n sizes.compositeTextSizes = [\n unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(minZoom), canonical),\n unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), canonical)\n ];\n }\n\n if (bucket.iconSizeData.kind === 'composite') {\n const {minZoom, maxZoom} = bucket.iconSizeData;\n sizes.compositeIconSizes = [\n unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(minZoom), canonical),\n unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), canonical)\n ];\n }\n\n sizes.layoutTextSize = unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(tileZoom + 1), canonical);\n sizes.layoutIconSize = unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(tileZoom + 1), canonical);\n sizes.textMaxSize = unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(18), canonical);\n\n const textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point';\n const textSize = layout.get('text-size');\n\n for (const feature of bucket.features) {\n const fontstack = layout.get('text-font').evaluate(feature, {}, canonical).join(',');\n const layoutTextSizeThisZoom = textSize.evaluate(feature, {}, canonical);\n const layoutTextSize = sizes.layoutTextSize.evaluate(feature, {}, canonical);\n const layoutIconSize = sizes.layoutIconSize.evaluate(feature, {}, canonical);\n\n const shapedTextOrientations = {\n horizontal: {},\n vertical: undefined\n };\n const text = feature.text;\n let textOffset: [number, number] = [0, 0];\n if (text) {\n const unformattedText = text.toString();\n const spacing = layout.get('text-letter-spacing').evaluate(feature, {}, canonical) * ONE_EM;\n const lineHeight = layout.get('text-line-height').evaluate(feature, {}, canonical) * ONE_EM;\n const spacingIfAllowed = allowsLetterSpacing(unformattedText) ? spacing : 0;\n\n const textAnchor = layout.get('text-anchor').evaluate(feature, {}, canonical);\n const variableTextAnchor = layout.get('text-variable-anchor');\n\n if (!variableTextAnchor) {\n const radialOffset = layout.get('text-radial-offset').evaluate(feature, {}, canonical);\n // Layers with variable anchors use the `text-radial-offset` property and the [x, y] offset vector\n // is calculated at placement time instead of layout time\n if (radialOffset) {\n // The style spec says don't use `text-offset` and `text-radial-offset` together\n // but doesn't actually specify what happens if you use both. We go with the radial offset.\n textOffset = evaluateVariableOffset(textAnchor, [radialOffset * ONE_EM, INVALID_TEXT_OFFSET]);\n } else {\n textOffset = (layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM): any);\n }\n }\n\n let textJustify = textAlongLine ?\n \"center\" :\n layout.get('text-justify').evaluate(feature, {}, canonical);\n\n const isPointPlacement = layout.get('symbol-placement') === 'point';\n const maxWidth = isPointPlacement ?\n layout.get('text-max-width').evaluate(feature, {}, canonical) * ONE_EM :\n Infinity;\n\n const addVerticalShapingIfNeeded = (textJustify: TextJustify) => {\n if (bucket.allowVerticalPlacement && allowsVerticalWritingMode(unformattedText)) {\n // Vertical POI label placement is meant to be used for scripts that support vertical\n // writing mode, thus, default left justification is used. If Latin\n // scripts would need to be supported, this should take into account other justifications.\n shapedTextOrientations.vertical = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor,\n textJustify, spacingIfAllowed, textOffset, WritingMode.vertical, true, layoutTextSize, layoutTextSizeThisZoom);\n }\n };\n\n // If this layer uses text-variable-anchor, generate shapings for all justification possibilities.\n if (!textAlongLine && variableTextAnchor) {\n const justifications = textJustify === \"auto\" ?\n variableTextAnchor.map(a => getAnchorJustification(a)) :\n [textJustify];\n\n let singleLine = false;\n for (let i = 0; i < justifications.length; i++) {\n const justification: TextJustify = justifications[i];\n if (shapedTextOrientations.horizontal[justification]) continue;\n if (singleLine) {\n // If the shaping for the first justification was only a single line, we\n // can re-use it for the other justifications\n shapedTextOrientations.horizontal[justification] = shapedTextOrientations.horizontal[0];\n } else {\n // If using text-variable-anchor for the layer, we use a center anchor for all shapings and apply\n // the offsets for the anchor in the placement step.\n const shaping = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, 'center',\n justification, spacingIfAllowed, textOffset, WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom);\n if (shaping) {\n shapedTextOrientations.horizontal[justification] = shaping;\n singleLine = shaping.positionedLines.length === 1;\n }\n }\n }\n\n addVerticalShapingIfNeeded('left');\n } else {\n if (textJustify === \"auto\") {\n textJustify = getAnchorJustification(textAnchor);\n }\n // Add horizontal shaping for all point labels and line labels that need horizontal writing mode.\n if (isPointPlacement || ((layout.get(\"text-writing-mode\").indexOf('horizontal') >= 0) || !allowsVerticalWritingMode(unformattedText))) {\n const shaping = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed,\n textOffset, WritingMode.horizontal, false, layoutTextSize, layoutTextSizeThisZoom);\n if (shaping) shapedTextOrientations.horizontal[textJustify] = shaping;\n }\n\n // Vertical point label (if allowVerticalPlacement is enabled).\n addVerticalShapingIfNeeded(isPointPlacement ? 'left' : textJustify);\n }\n }\n\n let shapedIcon;\n let isSDFIcon = false;\n if (feature.icon && feature.icon.name) {\n const image = imageMap[feature.icon.name];\n if (image) {\n shapedIcon = shapeIcon(\n imagePositions[feature.icon.name],\n layout.get('icon-offset').evaluate(feature, {}, canonical),\n layout.get('icon-anchor').evaluate(feature, {}, canonical));\n isSDFIcon = image.sdf;\n if (bucket.sdfIcons === undefined) {\n bucket.sdfIcons = image.sdf;\n } else if (bucket.sdfIcons !== image.sdf) {\n warnOnce('Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer');\n }\n if (image.pixelRatio !== bucket.pixelRatio) {\n bucket.iconsNeedLinear = true;\n } else if (layout.get('icon-rotate').constantOr(1) !== 0) {\n bucket.iconsNeedLinear = true;\n }\n }\n }\n\n const shapedText = getDefaultHorizontalShaping(shapedTextOrientations.horizontal) || shapedTextOrientations.vertical;\n if (!bucket.iconsInText) {\n bucket.iconsInText = shapedText ? shapedText.iconsInText : false;\n }\n if (shapedText || shapedIcon) {\n addFeature(bucket, feature, shapedTextOrientations, shapedIcon, imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, availableImages, canonical, projection);\n }\n }\n\n if (showCollisionBoxes) {\n bucket.generateCollisionDebugBuffers(tileZoom, bucket.collisionBoxArray);\n }\n}\n\n// Choose the justification that matches the direction of the TextAnchor\nexport function getAnchorJustification(anchor: TextAnchor): TextJustify {\n switch (anchor) {\n case 'right':\n case 'top-right':\n case 'bottom-right':\n return 'right';\n case 'left':\n case 'top-left':\n case 'bottom-left':\n return 'left';\n }\n return 'center';\n}\n\n/**\n * for \"very\" overscaled tiles (overscaleFactor > 2) on high zoom levels (z > 18)\n * we use the tile pixel ratio from the previous zoom level and clamp it to 1\n * in order to thin out labels density and save memory and CPU .\n * @private\n */\nfunction tilePixelRatioForSymbolSpacing(overscaleFactor: number, overscaledZ: number) {\n if (overscaledZ > 18 && overscaleFactor > 2) {\n overscaleFactor >>= 1;\n }\n const tilePixelRatio = EXTENT / (512 * overscaleFactor);\n return Math.max(tilePixelRatio, 1);\n}\n\n/**\n * Given a feature and its shaped text and icon data, add a 'symbol\n * instance' for each _possible_ placement of the symbol feature.\n * (At render time Placement.updateBucketOpacities() selects which of these\n * instances to show or hide based on collisions with symbols in other layers.)\n * @private\n */\nfunction addFeature(bucket: SymbolBucket,\n feature: SymbolFeature,\n shapedTextOrientations: any,\n shapedIcon: PositionedIcon | void,\n imageMap: {[_: string]: StyleImage},\n sizes: Sizes,\n layoutTextSize: number,\n layoutIconSize: number,\n textOffset: [number, number],\n isSDFIcon: boolean,\n availableImages: Array<string>,\n canonical: CanonicalTileID,\n projection: Projection) {\n // To reduce the number of labels that jump around when zooming we need\n // to use a text-size value that is the same for all zoom levels.\n // bucket calculates text-size at a high zoom level so that all tiles can\n // use the same value when calculating anchor positions.\n let textMaxSize = sizes.textMaxSize.evaluate(feature, {}, canonical);\n if (textMaxSize === undefined) {\n textMaxSize = layoutTextSize;\n }\n const layout = bucket.layers[0].layout;\n const iconOffset = layout.get('icon-offset').evaluate(feature, {}, canonical);\n const defaultShaping = getDefaultHorizontalShaping(shapedTextOrientations.horizontal) || shapedTextOrientations.vertical;\n const isGlobe = projection.name === 'globe';\n\n const glyphSize = ONE_EM,\n fontScale = layoutTextSize / glyphSize,\n textMaxBoxScale = bucket.tilePixelRatio * textMaxSize / glyphSize,\n iconBoxScale = bucket.tilePixelRatio * layoutIconSize,\n symbolMinDistance = tilePixelRatioForSymbolSpacing(bucket.overscaling, bucket.zoom) * layout.get('symbol-spacing'),\n textPadding = layout.get('text-padding') * bucket.tilePixelRatio,\n iconPadding = layout.get('icon-padding') * bucket.tilePixelRatio,\n textMaxAngle = degToRad(layout.get('text-max-angle')),\n textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point',\n iconAlongLine = layout.get('icon-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point',\n symbolPlacement = layout.get('symbol-placement'),\n textRepeatDistance = symbolMinDistance / 2;\n\n const iconTextFit = layout.get('icon-text-fit');\n let verticallyShapedIcon;\n\n // Adjust shaped icon size when icon-text-fit is used.\n if (shapedIcon && iconTextFit !== 'none') {\n if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) {\n verticallyShapedIcon = fitIconToText(shapedIcon, shapedTextOrientations.vertical, iconTextFit,\n layout.get('icon-text-fit-padding'), iconOffset, fontScale);\n }\n if (defaultShaping) {\n shapedIcon = fitIconToText(shapedIcon, defaultShaping, iconTextFit,\n layout.get('icon-text-fit-padding'), iconOffset, fontScale);\n }\n }\n\n const addSymbolAtAnchor = (line: Array<Point>, anchor: Anchor, canonicalId: CanonicalTileID) => {\n if (anchor.x < 0 || anchor.x >= EXTENT || anchor.y < 0 || anchor.y >= EXTENT) {\n // Symbol layers are drawn across tile boundaries, We filter out symbols\n // outside our tile boundaries (which may be included in vector tile buffers)\n // to prevent double-drawing symbols.\n return;\n }\n\n let globe: ?{anchor: Anchor, up: Vec3} = null;\n if (isGlobe) {\n const {x, y, z} = projection.projectTilePoint(anchor.x, anchor.y, canonicalId);\n globe = {\n anchor: new Anchor(x, y, z, 0, undefined),\n up: projection.upVector(canonicalId, anchor.x, anchor.y)\n };\n }\n\n addSymbol(bucket, anchor, globe, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, bucket.layers[0],\n bucket.collisionBoxArray, feature.index, feature.sourceLayerIndex,\n bucket.index, textPadding, textAlongLine, textOffset,\n iconBoxScale, iconPadding, iconAlongLine, iconOffset,\n feature, sizes, isSDFIcon, availableImages, canonical);\n };\n\n if (symbolPlacement === 'line') {\n for (const line of clipLine(feature.geometry, 0, 0, EXTENT, EXTENT)) {\n const anchors = getAnchors(\n line,\n symbolMinDistance,\n textMaxAngle,\n shapedTextOrientations.vertical || defaultShaping,\n shapedIcon,\n glyphSize,\n textMaxBoxScale,\n bucket.overscaling,\n EXTENT\n );\n for (const anchor of anchors) {\n const shapedText = defaultShaping;\n if (!shapedText || !anchorIsTooClose(bucket, shapedText.text, textRepeatDistance, anchor)) {\n addSymbolAtAnchor(line, anchor, canonical);\n }\n }\n }\n } else if (symbolPlacement === 'line-center') {\n // No clipping, multiple lines per feature are allowed\n // \"lines\" with only one point are ignored as in clipLines\n for (const line of feature.geometry) {\n if (line.length > 1) {\n const anchor = getCenterAnchor(\n line,\n textMaxAngle,\n shapedTextOrientations.vertical || defaultShaping,\n shapedIcon,\n glyphSize,\n textMaxBoxScale);\n if (anchor) {\n addSymbolAtAnchor(line, anchor, canonical);\n }\n }\n }\n } else if (feature.type === 'Polygon') {\n for (const polygon of classifyRings(feature.geometry, 0)) {\n // 16 here represents 2 pixels\n const poi = findPoleOfInaccessibility(polygon, 16);\n addSymbolAtAnchor(polygon[0], new Anchor(poi.x, poi.y, 0, 0, undefined), canonical);\n }\n } else if (feature.type === 'LineString') {\n // https://github.com/mapbox/mapbox-gl-js/issues/3808\n for (const line of feature.geometry) {\n addSymbolAtAnchor(line, new Anchor(line[0].x, line[0].y, 0, 0, undefined), canonical);\n }\n } else if (feature.type === 'Point') {\n for (const points of feature.geometry) {\n for (const point of points) {\n addSymbolAtAnchor([point], new Anchor(point.x, point.y, 0, 0, undefined), canonical);\n }\n }\n }\n}\n\nconst MAX_GLYPH_ICON_SIZE = 255;\nconst MAX_PACKED_SIZE = MAX_GLYPH_ICON_SIZE * SIZE_PACK_FACTOR;\nexport {MAX_PACKED_SIZE};\n\nfunction addTextVertices(bucket: SymbolBucket,\n globe: ?{ anchor: Anchor, up: Vec3 },\n tileAnchor: Anchor,\n shapedText: Shaping,\n imageMap: {[_: string]: StyleImage},\n layer: SymbolStyleLayer,\n textAlongLine: boolean,\n feature: SymbolFeature,\n textOffset: [number, number],\n lineArray: {lineStartIndex: number, lineLength: number},\n writingMode: number,\n placementTypes: Array<'vertical' | 'center' | 'left' | 'right'>,\n placedTextSymbolIndices: {[_: string]: number},\n placedIconIndex: number,\n sizes: Sizes,\n availableImages: Array<string>,\n canonical: CanonicalTileID) {\n const glyphQuads = getGlyphQuads(tileAnchor, shapedText, textOffset,\n layer, textAlongLine, feature, imageMap, bucket.allowVerticalPlacement);\n\n const sizeData = bucket.textSizeData;\n let textSizeData = null;\n\n if (sizeData.kind === 'source') {\n textSizeData = [\n SIZE_PACK_FACTOR * layer.layout.get('text-size').evaluate(feature, {}, canonical)\n ];\n if (textSizeData[0] > MAX_PACKED_SIZE) {\n warnOnce(`${bucket.layerIds[0]}: Value for \"text-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"text-size\".`);\n }\n } else if (sizeData.kind === 'composite') {\n textSizeData = [\n SIZE_PACK_FACTOR * sizes.compositeTextSizes[0].evaluate(feature, {}, canonical),\n SIZE_PACK_FACTOR * sizes.compositeTextSizes[1].evaluate(feature, {}, canonical)\n ];\n if (textSizeData[0] > MAX_PACKED_SIZE || textSizeData[1] > MAX_PACKED_SIZE) {\n warnOnce(`${bucket.layerIds[0]}: Value for \"text-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"text-size\".`);\n }\n }\n\n bucket.addSymbols(\n bucket.text,\n glyphQuads,\n textSizeData,\n textOffset,\n textAlongLine,\n feature,\n writingMode,\n globe,\n tileAnchor,\n lineArray.lineStartIndex,\n lineArray.lineLength,\n placedIconIndex,\n availableImages,\n canonical);\n\n // The placedSymbolArray is used at render time in drawTileSymbols\n // These indices allow access to the array at collision detection time\n for (const placementType of placementTypes) {\n placedTextSymbolIndices[placementType] = bucket.text.placedSymbolArray.length - 1;\n }\n\n return glyphQuads.length * 4;\n}\n\nfunction getDefaultHorizontalShaping(horizontalShaping: {[_: TextJustify]: Shaping}): Shaping | null {\n // We don't care which shaping we get because this is used for collision purposes\n // and all the justifications have the same collision box\n for (const justification: any in horizontalShaping) {\n return horizontalShaping[justification];\n }\n return null;\n}\n\nexport function evaluateBoxCollisionFeature(collisionBoxArray: CollisionBoxArray,\n projectedAnchor: Anchor,\n tileAnchor: Anchor,\n featureIndex: number,\n sourceLayerIndex: number,\n bucketIndex: number,\n shaped: Object,\n padding: number,\n rotate: number,\n textOffset: ?[number, number]): number {\n let y1 = shaped.top;\n let y2 = shaped.bottom;\n let x1 = shaped.left;\n let x2 = shaped.right;\n\n const collisionPadding = shaped.collisionPadding;\n if (collisionPadding) {\n x1 -= collisionPadding[0];\n y1 -= collisionPadding[1];\n x2 += collisionPadding[2];\n y2 += collisionPadding[3];\n }\n\n if (rotate) {\n // Account for *-rotate in point collision boxes\n // See https://github.com/mapbox/mapbox-gl-js/issues/6075\n // Doesn't account for icon-text-fit\n\n const tl = new Point(x1, y1);\n const tr = new Point(x2, y1);\n const bl = new Point(x1, y2);\n const br = new Point(x2, y2);\n\n const rotateRadians = degToRad(rotate);\n let rotateCenter = new Point(0, 0);\n\n if (textOffset) {\n rotateCenter = new Point(textOffset[0], textOffset[1]);\n }\n\n tl._rotateAround(rotateRadians, rotateCenter);\n tr._rotateAround(rotateRadians, rotateCenter);\n bl._rotateAround(rotateRadians, rotateCenter);\n br._rotateAround(rotateRadians, rotateCenter);\n\n // Collision features require an \"on-axis\" geometry,\n // so take the envelope of the rotated geometry\n // (may be quite large for wide labels rotated 45 degrees)\n x1 = Math.min(tl.x, tr.x, bl.x, br.x);\n x2 = Math.max(tl.x, tr.x, bl.x, br.x);\n y1 = Math.min(tl.y, tr.y, bl.y, br.y);\n y2 = Math.max(tl.y, tr.y, bl.y, br.y);\n }\n\n collisionBoxArray.emplaceBack(projectedAnchor.x, projectedAnchor.y, projectedAnchor.z, tileAnchor.x, tileAnchor.y, x1, y1, x2, y2, padding, featureIndex, sourceLayerIndex, bucketIndex);\n\n return collisionBoxArray.length - 1;\n}\n\nexport function evaluateCircleCollisionFeature(shaped: Object): number | null {\n if (shaped.collisionPadding) {\n // Compute height of the shape in glyph metrics and apply padding.\n // Note that the pixel based 'text-padding' is applied at runtime\n shaped.top -= shaped.collisionPadding[1];\n shaped.bottom += shaped.collisionPadding[3];\n }\n\n // Set minimum box height to avoid very many small labels\n const height = shaped.bottom - shaped.top;\n return height > 0 ? Math.max(10, height) : null;\n}\n\n/**\n * Add a single label & icon placement.\n *\n * @private\n */\nfunction addSymbol(bucket: SymbolBucket,\n anchor: Anchor,\n globe: ?{ anchor: Anchor, up: Vec3 },\n line: Array<Point>,\n shapedTextOrientations: any,\n shapedIcon: PositionedIcon | void,\n imageMap: {[_: string]: StyleImage},\n verticallyShapedIcon: PositionedIcon | void,\n layer: SymbolStyleLayer,\n collisionBoxArray: CollisionBoxArray,\n featureIndex: number,\n sourceLayerIndex: number,\n bucketIndex: number,\n textPadding: number,\n textAlongLine: boolean,\n textOffset: [number, number],\n iconBoxScale: number,\n iconPadding: number,\n iconAlongLine: boolean,\n iconOffset: [number, number],\n feature: SymbolFeature,\n sizes: Sizes,\n isSDFIcon: boolean,\n availableImages: Array<string>,\n canonical: CanonicalTileID) {\n const lineArray = bucket.addToLineVertexArray(anchor, line);\n let textBoxIndex, iconBoxIndex, verticalTextBoxIndex, verticalIconBoxIndex;\n let textCircle, verticalTextCircle, verticalIconCircle;\n\n let numIconVertices = 0;\n let numVerticalIconVertices = 0;\n let numHorizontalGlyphVertices = 0;\n let numVerticalGlyphVertices = 0;\n let placedIconSymbolIndex = -1;\n let verticalPlacedIconSymbolIndex = -1;\n const placedTextSymbolIndices = {};\n let key = murmur3('');\n const collisionFeatureAnchor: Anchor = globe ? globe.anchor : anchor;\n\n let textOffset0 = 0;\n let textOffset1 = 0;\n if (layer._unevaluatedLayout.getValue('text-radial-offset') === undefined) {\n [textOffset0, textOffset1] = (layer.layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM): any);\n } else {\n textOffset0 = layer.layout.get('text-radial-offset').evaluate(feature, {}, canonical) * ONE_EM;\n textOffset1 = INVALID_TEXT_OFFSET;\n }\n\n if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) {\n const verticalShaping = shapedTextOrientations.vertical;\n if (textAlongLine) {\n verticalTextCircle = evaluateCircleCollisionFeature(verticalShaping);\n if (verticallyShapedIcon) {\n verticalIconCircle = evaluateCircleCollisionFeature(verticallyShapedIcon);\n }\n } else {\n const textRotation = layer.layout.get('text-rotate').evaluate(feature, {}, canonical);\n const verticalTextRotation = textRotation + 90.0;\n verticalTextBoxIndex = evaluateBoxCollisionFeature(collisionBoxArray, collisionFeatureAnchor, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textPadding, verticalTextRotation, textOffset);\n if (verticallyShapedIcon) {\n verticalIconBoxIndex = evaluateBoxCollisionFeature(collisionBoxArray, collisionFeatureAnchor, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticallyShapedIcon, iconPadding, verticalTextRotation);\n }\n }\n }\n\n // Place icon first, so text can have a reference to its index in the placed symbol array.\n // Text symbols can lazily shift at render-time because of variable anchor placement.\n // If the style specifies an `icon-text-fit` then the icon would have to shift along with it.\n // For more info check `updateVariableAnchors` in `draw_symbol.js` .\n\n if (shapedIcon) {\n const iconRotate = layer.layout.get('icon-rotate').evaluate(feature, {}, canonical);\n const hasIconTextFit = layer.layout.get('icon-text-fit') !== 'none';\n const iconQuads = getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit);\n const verticalIconQuads = verticallyShapedIcon ? getIconQuads(verticallyShapedIcon, iconRotate, isSDFIcon, hasIconTextFit) : undefined;\n iconBoxIndex = evaluateBoxCollisionFeature(collisionBoxArray, collisionFeatureAnchor, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconPadding, iconRotate);\n numIconVertices = iconQuads.length * 4;\n\n const sizeData = bucket.iconSizeData;\n let iconSizeData = null;\n\n if (sizeData.kind === 'source') {\n iconSizeData = [\n SIZE_PACK_FACTOR * layer.layout.get('icon-size').evaluate(feature, {}, canonical)\n ];\n if (iconSizeData[0] > MAX_PACKED_SIZE) {\n warnOnce(`${bucket.layerIds[0]}: Value for \"icon-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"icon-size\".`);\n }\n } else if (sizeData.kind === 'composite') {\n iconSizeData = [\n SIZE_PACK_FACTOR * sizes.compositeIconSizes[0].evaluate(feature, {}, canonical),\n SIZE_PACK_FACTOR * sizes.compositeIconSizes[1].evaluate(feature, {}, canonical)\n ];\n if (iconSizeData[0] > MAX_PACKED_SIZE || iconSizeData[1] > MAX_PACKED_SIZE) {\n warnOnce(`${bucket.layerIds[0]}: Value for \"icon-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"icon-size\".`);\n }\n }\n\n bucket.addSymbols(\n bucket.icon,\n iconQuads,\n iconSizeData,\n iconOffset,\n iconAlongLine,\n feature,\n false,\n globe,\n anchor,\n lineArray.lineStartIndex,\n lineArray.lineLength,\n // The icon itself does not have an associated symbol since the text isnt placed yet\n -1,\n availableImages,\n canonical);\n\n placedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1;\n\n if (verticalIconQuads) {\n numVerticalIconVertices = verticalIconQuads.length * 4;\n\n bucket.addSymbols(\n bucket.icon,\n verticalIconQuads,\n iconSizeData,\n iconOffset,\n iconAlongLine,\n feature,\n WritingMode.vertical,\n globe,\n anchor,\n lineArray.lineStartIndex,\n lineArray.lineLength,\n // The icon itself does not have an associated symbol since the text isnt placed yet\n -1,\n availableImages,\n canonical);\n\n verticalPlacedIconSymbolIndex = bucket.icon.placedSymbolArray.length - 1;\n }\n }\n\n for (const justification: any in shapedTextOrientations.horizontal) {\n const shaping = shapedTextOrientations.horizontal[justification];\n\n if (!textBoxIndex) {\n key = murmur3(shaping.text);\n // As a collision approximation, we can use either the vertical or any of the horizontal versions of the feature\n // We're counting on all versions having similar dimensions\n if (textAlongLine) {\n textCircle = evaluateCircleCollisionFeature(shaping);\n } else {\n const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}, canonical);\n textBoxIndex = evaluateBoxCollisionFeature(collisionBoxArray, collisionFeatureAnchor, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textPadding, textRotate, textOffset);\n }\n }\n\n const singleLine = shaping.positionedLines.length === 1;\n numHorizontalGlyphVertices += addTextVertices(\n bucket, globe, anchor, shaping, imageMap, layer, textAlongLine, feature, textOffset, lineArray,\n shapedTextOrientations.vertical ? WritingMode.horizontal : WritingMode.horizontalOnly,\n singleLine ? (Object.keys(shapedTextOrientations.horizontal): any) : [justification],\n placedTextSymbolIndices, placedIconSymbolIndex, sizes, availableImages, canonical);\n\n if (singleLine) {\n break;\n }\n }\n\n if (shapedTextOrientations.vertical) {\n numVerticalGlyphVertices += addTextVertices(\n bucket, globe, anchor, shapedTextOrientations.vertical, imageMap, layer, textAlongLine, feature,\n textOffset, lineArray, WritingMode.vertical, ['vertical'], placedTextSymbolIndices, verticalPlacedIconSymbolIndex, sizes, availableImages, canonical);\n }\n\n // Check if runtime collision circles should be used for any of the collision features.\n // It is enough to choose the tallest feature shape as circles are always placed on a line.\n // All measurements are in glyph metrics and later converted into pixels using proper font size \"layoutTextSize\"\n let collisionCircleDiameter = -1;\n\n const getCollisionCircleHeight = (diameter: ?number, prevHeight: number): number => {\n return diameter ? Math.max(diameter, prevHeight) : prevHeight;\n };\n\n collisionCircleDiameter = getCollisionCircleHeight(textCircle, collisionCircleDiameter);\n collisionCircleDiameter = getCollisionCircleHeight(verticalTextCircle, collisionCircleDiameter);\n collisionCircleDiameter = getCollisionCircleHeight(verticalIconCircle, collisionCircleDiameter);\n const useRuntimeCollisionCircles = (collisionCircleDiameter > -1) ? 1 : 0;\n\n if (bucket.glyphOffsetArray.length >= SymbolBucket.MAX_GLYPHS) warnOnce(\n \"Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907\"\n );\n\n if (feature.sortKey !== undefined) {\n bucket.addToSortKeyRanges(bucket.symbolInstances.length, feature.sortKey);\n }\n\n const projectedAnchor = collisionFeatureAnchor;\n\n bucket.symbolInstances.emplaceBack(\n projectedAnchor.x,\n projectedAnchor.y,\n projectedAnchor.z,\n anchor.x,\n anchor.y,\n placedTextSymbolIndices.right >= 0 ? placedTextSymbolIndices.right : -1,\n placedTextSymbolIndices.center >= 0 ? placedTextSymbolIndices.center : -1,\n placedTextSymbolIndices.left >= 0 ? placedTextSymbolIndices.left : -1,\n placedTextSymbolIndices.vertical >= 0 ? placedTextSymbolIndices.vertical : -1,\n placedIconSymbolIndex,\n verticalPlacedIconSymbolIndex,\n key,\n textBoxIndex !== undefined ? textBoxIndex : bucket.collisionBoxArray.length,\n textBoxIndex !== undefined ? textBoxIndex + 1 : bucket.collisionBoxArray.length,\n verticalTextBoxIndex !== undefined ? verticalTextBoxIndex : bucket.collisionBoxArray.length,\n verticalTextBoxIndex !== undefined ? verticalTextBoxIndex + 1 : bucket.collisionBoxArray.length,\n iconBoxIndex !== undefined ? iconBoxIndex : bucket.collisionBoxArray.length,\n iconBoxIndex !== undefined ? iconBoxIndex + 1 : bucket.collisionBoxArray.length,\n verticalIconBoxIndex ? verticalIconBoxIndex : bucket.collisionBoxArray.length,\n verticalIconBoxIndex ? verticalIconBoxIndex + 1 : bucket.collisionBoxArray.length,\n featureIndex,\n numHorizontalGlyphVertices,\n numVerticalGlyphVertices,\n numIconVertices,\n numVerticalIconVertices,\n useRuntimeCollisionCircles,\n 0,\n textOffset0,\n textOffset1,\n collisionCircleDiameter);\n}\n\nfunction anchorIsTooClose(bucket: any, text: string, repeatDistance: number, anchor: Point) {\n const compareText = bucket.compareText;\n if (!(text in compareText)) {\n compareText[text] = [];\n } else {\n const otherAnchors = compareText[text];\n for (let k = otherAnchors.length - 1; k >= 0; k--) {\n if (anchor.dist(otherAnchors[k]) < repeatDistance) {\n // If it's within repeatDistance of one anchor, stop looking\n return true;\n }\n }\n }\n // If anchor is not within repeatDistance of any other anchor, add to array\n compareText[text].push(anchor);\n return false;\n}\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nexport default clipLine;\n\n/**\n * Returns the part of a multiline that intersects with the provided rectangular box.\n *\n * @param lines\n * @param x1 the left edge of the box\n * @param y1 the top edge of the box\n * @param x2 the right edge of the box\n * @param y2 the bottom edge of the box\n * @returns lines\n * @private\n */\nfunction clipLine(lines: Array<Array<Point>>, x1: number, y1: number, x2: number, y2: number): Array<Array<Point>> {\n const clippedLines = [];\n\n for (let l = 0; l < lines.length; l++) {\n const line = lines[l];\n let clippedLine;\n\n for (let i = 0; i < line.length - 1; i++) {\n let p0 = line[i];\n let p1 = line[i + 1];\n\n if (p0.x < x1 && p1.x < x1) {\n continue;\n } else if (p0.x < x1) {\n p0 = new Point(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round();\n } else if (p1.x < x1) {\n p1 = new Point(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round();\n }\n\n if (p0.y < y1 && p1.y < y1) {\n continue;\n } else if (p0.y < y1) {\n p0 = new Point(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round();\n } else if (p1.y < y1) {\n p1 = new Point(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round();\n }\n\n if (p0.x >= x2 && p1.x >= x2) {\n continue;\n } else if (p0.x >= x2) {\n p0 = new Point(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round();\n } else if (p1.x >= x2) {\n p1 = new Point(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round();\n }\n\n if (p0.y >= y2 && p1.y >= y2) {\n continue;\n } else if (p0.y >= y2) {\n p0 = new Point(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round();\n } else if (p1.y >= y2) {\n p1 = new Point(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round();\n }\n\n if (!clippedLine || !p0.equals(clippedLine[clippedLine.length - 1])) {\n clippedLine = [p0];\n clippedLines.push(clippedLine);\n }\n\n clippedLine.push(p1);\n }\n }\n\n return clippedLines;\n}\n","// @flow\nimport {vec3} from 'gl-matrix';\nimport {Ray} from '../../util/primitives.js';\nimport type Transform from '../transform.js';\n\nexport function farthestPixelDistanceOnPlane(tr: Transform, pixelsPerMeter: number): number {\n // Find the distance from the center point [width/2 + offset.x, height/2 + offset.y] to the\n // center top point [width/2 + offset.x, 0] in Z units, using the law of sines.\n // 1 Z unit is equivalent to 1 horizontal px at the center of the map\n // (the distance between[width/2, height/2] and [width/2 + 1, height/2])\n const fovAboveCenter = tr.fovAboveCenter;\n\n // Adjust distance to MSL by the minimum possible elevation visible on screen,\n // this way the far plane is pushed further in the case of negative elevation.\n const minElevationInPixels = tr.elevation ?\n tr.elevation.getMinElevationBelowMSL() * pixelsPerMeter :\n 0;\n const cameraToSeaLevelDistance = ((tr._camera.position[2] * tr.worldSize) - minElevationInPixels) / Math.cos(tr._pitch);\n const topHalfSurfaceDistance = Math.sin(fovAboveCenter) * cameraToSeaLevelDistance / Math.sin(Math.max(Math.PI / 2.0 - tr._pitch - fovAboveCenter, 0.01));\n\n // Calculate z distance of the farthest fragment that should be rendered.\n const furthestDistance = Math.sin(tr._pitch) * topHalfSurfaceDistance + cameraToSeaLevelDistance;\n const horizonDistance = cameraToSeaLevelDistance * (1 / tr._horizonShift);\n\n // Add a bit extra to avoid precision problems when a fragment's distance is exactly `furthestDistance`\n return Math.min(furthestDistance * 1.01, horizonDistance);\n}\n\nexport function farthestPixelDistanceOnSphere(tr: Transform, pixelsPerMeter: number): number {\n // Find farthest distance of the globe that is potentially visible to the camera.\n // First check if the view frustum is fully covered by the map by casting a ray\n // from the top left/right corner and see if it intersects with the globe. In case\n // of no intersection we need to find distance to the horizon point where the\n // surface normal is perpendicular to the camera forward direction.\n const cameraDistance = tr.cameraToCenterDistance;\n const centerPixelAltitude = tr._centerAltitude * pixelsPerMeter;\n\n const camera = tr._camera;\n const forward = tr._camera.forward();\n const cameraPosition = vec3.add([], vec3.scale([], forward, -cameraDistance), [0, 0, centerPixelAltitude]);\n\n const globeRadius = tr.worldSize / (2.0 * Math.PI);\n const globeCenter = [0, 0, -globeRadius];\n\n const aspectRatio = tr.width / tr.height;\n const tanFovAboveCenter = Math.tan(tr.fovAboveCenter);\n\n const up = vec3.scale([], camera.up(), tanFovAboveCenter);\n const right = vec3.scale([], camera.right(), tanFovAboveCenter * aspectRatio);\n const dir = vec3.normalize([], vec3.add([], vec3.add([], forward, up), right));\n\n const pointOnGlobe = [];\n const ray = new Ray(cameraPosition, dir);\n\n let pixelDistance;\n if (ray.closestPointOnSphere(globeCenter, globeRadius, pointOnGlobe)) {\n const p0 = vec3.add([], pointOnGlobe, globeCenter);\n const p1 = vec3.sub([], p0, cameraPosition);\n // Globe is fully covering the view frustum. Project the intersection\n // point to the camera view vector in order to find the pixel distance\n pixelDistance = Math.cos(tr.fovAboveCenter) * vec3.length(p1);\n } else {\n // Background space is visible. Find distance to the point of the\n // globe where surface normal is parallel to the view vector\n const globeCenterToCamera = vec3.sub([], cameraPosition, globeCenter);\n const cameraToGlobe = vec3.sub([], globeCenter, cameraPosition);\n vec3.normalize(cameraToGlobe, cameraToGlobe);\n\n const cameraHeight = vec3.length(globeCenterToCamera) - globeRadius;\n pixelDistance = Math.sqrt(cameraHeight * (cameraHeight + 2 * globeRadius));\n const angle = Math.acos(pixelDistance / (globeRadius + cameraHeight)) - Math.acos(vec3.dot(forward, cameraToGlobe));\n pixelDistance *= Math.cos(angle);\n }\n\n return pixelDistance * 1.01;\n}\n","// @flow\nimport Point from '@mapbox/point-geometry';\nimport MercatorCoordinate, {altitudeFromMercatorZ, lngFromMercatorX, latFromMercatorY} from '../mercator_coordinate.js';\nimport EXTENT from '../../data/extent.js';\nimport {vec3} from 'gl-matrix';\nimport {Aabb} from '../../util/primitives.js';\nimport {aabbForTileOnGlobe} from './globe_util.js';\nimport assert from 'assert';\nimport {CanonicalTileID} from '../../source/tile_id.js';\n\nimport type {Vec3} from 'gl-matrix';\nimport type Projection, {ProjectedPoint} from './projection.js';\nimport type Transform from '../transform.js';\n\nexport type TileTransform = {\n scale: number,\n x: number,\n y: number,\n x2: number,\n y2: number,\n projection: Projection\n};\n\nexport default function tileTransform(id: Object, projection: Projection): TileTransform {\n if (!projection.isReprojectedInTileSpace) {\n return {scale: 1 << id.z, x: id.x, y: id.y, x2: id.x + 1, y2: id.y + 1, projection};\n }\n\n const s = Math.pow(2, -id.z);\n\n const x1 = (id.x) * s;\n const x2 = (id.x + 1) * s;\n const y1 = (id.y) * s;\n const y2 = (id.y + 1) * s;\n\n const lng1 = lngFromMercatorX(x1);\n const lng2 = lngFromMercatorX(x2);\n const lat1 = latFromMercatorY(y1);\n const lat2 = latFromMercatorY(y2);\n\n const p0 = projection.project(lng1, lat1);\n const p1 = projection.project(lng2, lat1);\n const p2 = projection.project(lng2, lat2);\n const p3 = projection.project(lng1, lat2);\n\n let minX = Math.min(p0.x, p1.x, p2.x, p3.x);\n let minY = Math.min(p0.y, p1.y, p2.y, p3.y);\n let maxX = Math.max(p0.x, p1.x, p2.x, p3.x);\n let maxY = Math.max(p0.y, p1.y, p2.y, p3.y);\n\n // we pick an error threshold for calculating the bbox that balances between performance and precision\n const maxErr = s / 16;\n\n function processSegment(pa: ProjectedPoint, pb: ProjectedPoint, ax: number, ay: number, bx: number, by: number) {\n const mx = (ax + bx) / 2;\n const my = (ay + by) / 2;\n\n const pm = projection.project(lngFromMercatorX(mx), latFromMercatorY(my));\n const err = Math.max(0, minX - pm.x, minY - pm.y, pm.x - maxX, pm.y - maxY);\n\n minX = Math.min(minX, pm.x);\n maxX = Math.max(maxX, pm.x);\n minY = Math.min(minY, pm.y);\n maxY = Math.max(maxY, pm.y);\n\n if (err > maxErr) {\n processSegment(pa, pm, ax, ay, mx, my);\n processSegment(pm, pb, mx, my, bx, by);\n }\n }\n\n processSegment(p0, p1, x1, y1, x2, y1);\n processSegment(p1, p2, x2, y1, x2, y2);\n processSegment(p2, p3, x2, y2, x1, y2);\n processSegment(p3, p0, x1, y2, x1, y1);\n\n // extend the bbox by max error to make sure coords don't go past tile extent\n minX -= maxErr;\n minY -= maxErr;\n maxX += maxErr;\n maxY += maxErr;\n\n const max = Math.max(maxX - minX, maxY - minY);\n const scale = 1 / max;\n\n return {\n scale,\n x: minX * scale,\n y: minY * scale,\n x2: maxX * scale,\n y2: maxY * scale,\n projection\n };\n}\n\nexport function tileAABB(tr: Transform, numTiles: number, z: number, x: number, y: number, wrap: number, min: number, max: number, projection: Projection): Aabb {\n if (projection.name === 'globe') {\n const tileId = new CanonicalTileID(z, x, y);\n return aabbForTileOnGlobe(tr, numTiles, tileId);\n }\n\n const tt = tileTransform({z, x, y}, projection);\n const tx = tt.x / tt.scale;\n const ty = tt.y / tt.scale;\n const tx2 = tt.x2 / tt.scale;\n const ty2 = tt.y2 / tt.scale;\n\n if (isNaN(tx) || isNaN(tx2) || isNaN(ty) || isNaN(ty2)) {\n assert(false);\n }\n\n return new Aabb(\n [(wrap + tx) * numTiles, numTiles * ty, min],\n [(wrap + tx2) * numTiles, numTiles * ty2, max]);\n}\n\nexport function getTilePoint(tileTransform: TileTransform, {x, y}: interface { x: number, y: number }, wrap: number = 0): Point {\n return new Point(\n ((x - wrap) * tileTransform.scale - tileTransform.x) * EXTENT,\n (y * tileTransform.scale - tileTransform.y) * EXTENT);\n}\n\nexport function getTileVec3(tileTransform: TileTransform, coord: MercatorCoordinate, wrap: number = 0): Vec3 {\n const x = ((coord.x - wrap) * tileTransform.scale - tileTransform.x) * EXTENT;\n const y = (coord.y * tileTransform.scale - tileTransform.y) * EXTENT;\n return vec3.fromValues(x, y, altitudeFromMercatorZ(coord.z, coord.y));\n}\n","// @flow\nimport LngLat from '../lng_lat.js';\nimport {mercatorZfromAltitude} from '../mercator_coordinate.js';\nimport Point from '@mapbox/point-geometry';\nimport {farthestPixelDistanceOnPlane} from './far_z.js';\nimport {mat4} from 'gl-matrix';\nimport EXTENT from '../../data/extent.js';\nimport tileTransform from './tile_transform.js';\n\nimport type Transform from '../../geo/transform.js';\nimport type {Vec3} from 'gl-matrix';\nimport type MercatorCoordinate from '../mercator_coordinate.js';\nimport type {ProjectionSpecification} from '../../style-spec/types.js';\nimport type {CanonicalTileID, UnwrappedTileID} from '../../source/tile_id.js';\n\nexport type ProjectedPoint = {\n x: number;\n y: number;\n z: number;\n};\n\nexport type ElevationScale = {\n // `metersToTile` converts meters to units used to describe elevation in tile space.\n // Default units in mercator space are x & y: [0, 8192] and z: meters\n metersToTile: number\n}\n\nconst identity = mat4.identity(new Float32Array(16));\n\nexport default class Projection {\n name: string;\n wrap: boolean;\n conic: boolean;\n requiresDraping: boolean;\n supportsWorldCopies: boolean;\n supportsTerrain: boolean;\n supportsFog: boolean;\n supportsFreeCamera: boolean;\n zAxisUnit: 'meters' | 'pixels';\n isReprojectedInTileSpace: boolean;\n center: [number, number];\n range: ?[number, number];\n parallels: ?[number, number];\n unsupportedLayers: Array<string>;\n spec: ProjectionSpecification;\n\n constructor(options: ProjectionSpecification) {\n this.spec = options;\n this.name = options.name;\n this.wrap = false;\n this.requiresDraping = false;\n this.supportsWorldCopies = false;\n this.supportsTerrain = false;\n this.supportsFog = false;\n this.supportsFreeCamera = false;\n this.zAxisUnit = 'meters';\n this.isReprojectedInTileSpace = true;\n this.unsupportedLayers = ['custom'];\n this.center = [0, 0];\n this.range = [3.5, 7];\n }\n\n project(lng: number, lat: number): ProjectedPoint { // eslint-disable-line\n return {x: 0, y: 0, z: 0}; // overriden in subclasses\n }\n\n unproject(x: number, y: number): LngLat { // eslint-disable-line\n return new LngLat(0, 0); // overriden in subclasses\n }\n\n projectTilePoint(x: number, y: number, _: CanonicalTileID): ProjectedPoint {\n return {x, y, z: 0};\n }\n\n locationPoint(tr: Transform, lngLat: LngLat, terrain: boolean = true): Point {\n return tr._coordinatePoint(tr.locationCoordinate(lngLat), terrain);\n }\n\n pixelsPerMeter(lat: number, worldSize: number): number {\n return mercatorZfromAltitude(1, lat) * worldSize;\n }\n\n // pixels-per-meter is used to describe relation between real world and pixel distances.\n // `pixelSpaceConversion` can be used to convert the ratio from mercator projection to\n // the currently active projection.\n //\n // `pixelSpaceConversion` is useful for converting between pixel spaces where some logic\n // expects mercator pixels, such as raycasting where the scale is expected to be in\n // mercator pixels.\n pixelSpaceConversion(lat: number, worldSize: number, interpolationT: number): number { // eslint-disable-line\n return 1.0;\n }\n\n farthestPixelDistance(tr: Transform): number {\n return farthestPixelDistanceOnPlane(tr, tr.pixelsPerMeter);\n }\n\n pointCoordinate(tr: Transform, x: number, y: number, z: number): MercatorCoordinate {\n const horizonOffset = tr.horizonLineFromTop(false);\n const clamped = new Point(x, Math.max(horizonOffset, y));\n return tr.rayIntersectionCoordinate(tr.pointRayIntersection(clamped, z));\n }\n\n pointCoordinate3D(tr: Transform, x: number, y: number): ?Vec3 {\n const p = new Point(x, y);\n if (tr.elevation) {\n return tr.elevation.pointCoordinate(p);\n } else {\n const mc = this.pointCoordinate(tr, p.x, p.y, 0);\n return [mc.x, mc.y, mc.z];\n }\n }\n\n isPointAboveHorizon(tr: Transform, p: Point): boolean {\n if (tr.elevation) {\n const raycastOnTerrain = this.pointCoordinate3D(tr, p.x, p.y);\n return !raycastOnTerrain;\n }\n const horizon = tr.horizonLineFromTop();\n return p.y < horizon;\n }\n\n createInversionMatrix(tr: Transform, id: CanonicalTileID): Float32Array { // eslint-disable-line\n return identity;\n }\n\n createTileMatrix(tr: Transform, worldSize: number, id: UnwrappedTileID): Float64Array {\n let scale, scaledX, scaledY;\n const canonical = id.canonical;\n const posMatrix = mat4.identity(new Float64Array(16));\n\n if (this.isReprojectedInTileSpace) {\n const cs = tileTransform(canonical, this);\n scale = 1;\n scaledX = cs.x + id.wrap * cs.scale;\n scaledY = cs.y;\n mat4.scale(posMatrix, posMatrix, [scale / cs.scale, scale / cs.scale, tr.pixelsPerMeter / worldSize]);\n } else {\n scale = worldSize / tr.zoomScale(canonical.z);\n const unwrappedX = canonical.x + Math.pow(2, canonical.z) * id.wrap;\n scaledX = unwrappedX * scale;\n scaledY = canonical.y * scale;\n }\n\n mat4.translate(posMatrix, posMatrix, [scaledX, scaledY, 0]);\n mat4.scale(posMatrix, posMatrix, [scale / EXTENT, scale / EXTENT, 1]);\n\n return posMatrix;\n }\n\n upVector(id: CanonicalTileID, x: number, y: number): Vec3 { // eslint-disable-line\n return [0, 0, 1];\n }\n\n upVectorScale(id: CanonicalTileID, latitude: number, worldSize: number): ElevationScale { // eslint-disable-line\n return {metersToTile: 1};\n }\n}\n","// @flow\nimport LngLat from '../lng_lat.js';\nimport {clamp, wrap, degToRad, radToDeg} from '../../util/util.js';\nimport {MAX_MERCATOR_LATITUDE} from '../mercator_coordinate.js';\nimport Projection from './projection.js';\n\nimport type {ProjectionSpecification} from '../../style-spec/types.js';\nimport type {ProjectedPoint} from './projection.js';\n\n// based on https://github.com/d3/d3-geo-projection, MIT-licensed\nexport default class Albers extends Projection {\n n: number;\n c: number;\n r0: number;\n\n constructor(options: ProjectionSpecification) {\n super(options);\n this.range = [4, 7];\n this.center = options.center || [-96, 37.5];\n const [lat0, lat1] = this.parallels = options.parallels || [29.5, 45.5];\n\n const sy0 = Math.sin(degToRad(lat0));\n this.n = (sy0 + Math.sin(degToRad(lat1))) / 2;\n this.c = 1 + sy0 * (2 * this.n - sy0);\n this.r0 = Math.sqrt(this.c) / this.n;\n }\n\n project(lng: number, lat: number): ProjectedPoint {\n const {n, c, r0} = this;\n const lambda = degToRad(lng - this.center[0]);\n const phi = degToRad(lat);\n\n const r = Math.sqrt(c - 2 * n * Math.sin(phi)) / n;\n const x = r * Math.sin(lambda * n);\n const y = r * Math.cos(lambda * n) - r0;\n return {x, y, z: 0};\n }\n\n unproject(x: number, y: number): LngLat {\n const {n, c, r0} = this;\n const r0y = r0 + y;\n let l = Math.atan2(x, Math.abs(r0y)) * Math.sign(r0y);\n if (r0y * n < 0) {\n l -= Math.PI * Math.sign(x) * Math.sign(r0y);\n }\n const dt = degToRad(this.center[0]) * n;\n l = wrap(l, -Math.PI - dt, Math.PI - dt);\n\n const lng = clamp(radToDeg(l / n) + this.center[0], -180, 180);\n const phi = Math.asin(clamp((c - (x * x + r0y * r0y) * n * n) / (2 * n), -1, 1));\n const lat = clamp(radToDeg(phi), -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);\n\n return new LngLat(lng, lat);\n }\n}\n","// @flow\nimport LngLat from '../lng_lat.js';\nimport {clamp} from '../../util/util.js';\nimport {MAX_MERCATOR_LATITUDE} from '../mercator_coordinate.js';\nimport Projection from './projection.js';\n\nimport type {ProjectedPoint} from './projection.js';\n\nconst a1 = 1.340264;\nconst a2 = -0.081106;\nconst a3 = 0.000893;\nconst a4 = 0.003796;\nconst M = Math.sqrt(3) / 2;\n\nexport default class EqualEarth extends Projection {\n\n project(lng: number, lat: number): ProjectedPoint {\n // based on https://github.com/d3/d3-geo, MIT-licensed\n lat = lat / 180 * Math.PI;\n lng = lng / 180 * Math.PI;\n const theta = Math.asin(M * Math.sin(lat));\n const theta2 = theta * theta;\n const theta6 = theta2 * theta2 * theta2;\n const x = lng * Math.cos(theta) / (M * (a1 + 3 * a2 * theta2 + theta6 * (7 * a3 + 9 * a4 * theta2)));\n const y = theta * (a1 + a2 * theta2 + theta6 * (a3 + a4 * theta2));\n\n return {\n x: (x / Math.PI + 0.5) * 0.5,\n y: 1 - (y / Math.PI + 1) * 0.5,\n z: 0\n };\n }\n\n unproject(x: number, y: number): LngLat {\n // based on https://github.com/d3/d3-geo, MIT-licensed\n x = (2 * x - 0.5) * Math.PI;\n y = (2 * (1 - y) - 1) * Math.PI;\n let theta = y;\n let theta2 = theta * theta;\n let theta6 = theta2 * theta2 * theta2;\n\n for (let i = 0, delta, fy, fpy; i < 12; ++i) {\n fy = theta * (a1 + a2 * theta2 + theta6 * (a3 + a4 * theta2)) - y;\n fpy = a1 + 3 * a2 * theta2 + theta6 * (7 * a3 + 9 * a4 * theta2);\n delta = fy / fpy;\n theta = clamp(theta - delta, -Math.PI / 3, Math.PI / 3);\n theta2 = theta * theta;\n theta6 = theta2 * theta2 * theta2;\n if (Math.abs(delta) < 1e-12) break;\n }\n\n const lambda = M * x * (a1 + 3 * a2 * theta2 + theta6 * (7 * a3 + 9 * a4 * theta2)) / Math.cos(theta);\n const phi = Math.asin(Math.sin(theta) / M);\n const lng = clamp(lambda * 180 / Math.PI, -180, 180);\n const lat = clamp(phi * 180 / Math.PI, -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);\n\n return new LngLat(lng, lat);\n }\n}\n","// @flow\nimport LngLat from '../lng_lat.js';\nimport {clamp} from '../../util/util.js';\nimport {MAX_MERCATOR_LATITUDE} from '../mercator_coordinate.js';\nimport Projection from './projection.js';\n\nimport type {ProjectionSpecification} from '../../style-spec/types.js';\nimport type {ProjectedPoint} from './projection.js';\n\nexport default class Equirectangular extends Projection {\n\n constructor(options: ProjectionSpecification) {\n super(options);\n this.wrap = true;\n this.supportsWorldCopies = true;\n }\n\n project(lng: number, lat: number): ProjectedPoint {\n const x = 0.5 + lng / 360;\n const y = 0.5 - lat / 360;\n return {x, y, z: 0};\n }\n\n unproject(x: number, y: number): LngLat {\n const lng = (x - 0.5) * 360;\n const lat = clamp((0.5 - y) * 360, -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);\n return new LngLat(lng, lat);\n }\n}\n","// @flow\nimport LngLat from '../lng_lat.js';\nimport {clamp, degToRad, radToDeg} from '../../util/util.js';\nimport {MAX_MERCATOR_LATITUDE} from '../mercator_coordinate.js';\nimport Projection from './projection.js';\n\nimport type {ProjectionSpecification} from '../../style-spec/types.js';\nimport type {ProjectedPoint} from './projection.js';\n\nconst halfPi = Math.PI / 2;\n\nfunction tany(y: number) {\n return Math.tan((halfPi + y) / 2);\n}\n\n// based on https://github.com/d3/d3-geo, MIT-licensed\nexport default class LambertConformalConic extends Projection {\n n: number;\n f: number;\n southernCenter: boolean;\n\n constructor(options: ProjectionSpecification) {\n super(options);\n this.center = options.center || [0, 30];\n const [lat0, lat1] = this.parallels = options.parallels || [30, 30];\n\n let y0 = degToRad(lat0);\n let y1 = degToRad(lat1);\n // Run projection math on inverted lattitudes if the paralell lines are south of the equator\n // This fixes divide by zero errors with a South polar projection\n this.southernCenter = (y0 + y1) < 0;\n if (this.southernCenter) {\n y0 = -y0;\n y1 = -y1;\n }\n const cy0 = Math.cos(y0);\n const tany0 = tany(y0);\n\n this.n = y0 === y1 ? Math.sin(y0) : Math.log(cy0 / Math.cos(y1)) / Math.log(tany(y1) / tany0);\n this.f = cy0 * Math.pow(tany(y0), this.n) / this.n;\n }\n\n project(lng: number, lat: number): ProjectedPoint {\n lat = degToRad(lat);\n if (this.southernCenter) lat = -lat;\n lng = degToRad(lng - this.center[0]);\n\n const epsilon = 1e-6;\n const {n, f} = this;\n\n if (f > 0) {\n if (lat < -halfPi + epsilon) lat = -halfPi + epsilon;\n } else {\n if (lat > halfPi - epsilon) lat = halfPi - epsilon;\n }\n\n const r = f / Math.pow(tany(lat), n);\n let x = r * Math.sin(n * lng);\n let y = f - r * Math.cos(n * lng);\n x = (x / Math.PI + 0.5) * 0.5;\n y = (y / Math.PI + 0.5) * 0.5;\n\n return {\n x,\n y: this.southernCenter ? y : 1 - y,\n z: 0\n };\n }\n\n unproject(x: number, y: number): LngLat {\n x = (2 * x - 0.5) * Math.PI;\n if (this.southernCenter) y = 1 - y;\n y = (2 * (1 - y) - 0.5) * Math.PI;\n const {n, f} = this;\n const fy = f - y;\n const signFy = Math.sign(fy);\n const r = Math.sign(n) * Math.sqrt(x * x + fy * fy);\n let l = Math.atan2(x, Math.abs(fy)) * signFy;\n\n if (fy * n < 0) l -= Math.PI * Math.sign(x) * signFy;\n\n const lng = clamp(radToDeg(l / n) + this.center[0], -180, 180);\n const phi = 2 * Math.atan(Math.pow(f / r, 1 / n)) - halfPi;\n const lat = clamp(radToDeg(phi), -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);\n\n return new LngLat(lng, this.southernCenter ? -lat : lat);\n }\n}\n","// @flow\nimport LngLat from '../lng_lat.js';\nimport {mercatorXfromLng, mercatorYfromLat, lngFromMercatorX, latFromMercatorY} from '../mercator_coordinate.js';\nimport Projection from './projection.js';\n\nimport type {ProjectionSpecification} from '../../style-spec/types.js';\nimport type {ProjectedPoint} from './projection.js';\n\nexport default class Mercator extends Projection {\n\n constructor(options: ProjectionSpecification) {\n super(options);\n this.wrap = true;\n this.supportsWorldCopies = true;\n this.supportsTerrain = true;\n this.supportsFog = true;\n this.supportsFreeCamera = true;\n this.isReprojectedInTileSpace = false;\n this.unsupportedLayers = [];\n this.range = null;\n }\n\n project(lng: number, lat: number): ProjectedPoint {\n const x = mercatorXfromLng(lng);\n const y = mercatorYfromLat(lat);\n return {x, y, z: 0};\n }\n\n unproject(x: number, y: number): LngLat {\n const lng = lngFromMercatorX(x);\n const lat = latFromMercatorY(y);\n return new LngLat(lng, lat);\n }\n}\n","// @flow\nimport LngLat from '../lng_lat.js';\nimport {clamp, degToRad, radToDeg} from '../../util/util.js';\nimport {MAX_MERCATOR_LATITUDE} from '../mercator_coordinate.js';\nimport Projection from './projection.js';\n\nimport type {ProjectedPoint} from './projection.js';\n\nconst maxPhi = degToRad(MAX_MERCATOR_LATITUDE);\n\nexport default class NaturalEarth extends Projection {\n\n project(lng: number, lat: number): ProjectedPoint {\n // based on https://github.com/d3/d3-geo, MIT-licensed\n lat = degToRad(lat);\n lng = degToRad(lng);\n\n const phi2 = lat * lat;\n const phi4 = phi2 * phi2;\n const x = lng * (0.8707 - 0.131979 * phi2 + phi4 * (-0.013791 + phi4 * (0.003971 * phi2 - 0.001529 * phi4)));\n const y = lat * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4)));\n\n return {\n x: (x / Math.PI + 0.5) * 0.5,\n y: 1 - (y / Math.PI + 1) * 0.5,\n z: 0\n };\n }\n\n unproject(x: number, y: number): LngLat {\n // based on https://github.com/d3/d3-geo, MIT-licensed\n x = (2 * x - 0.5) * Math.PI;\n y = (2 * (1 - y) - 1) * Math.PI;\n const epsilon = 1e-6;\n let phi = y;\n let i = 25;\n let delta = 0;\n let phi2 = phi * phi;\n\n do {\n phi2 = phi * phi;\n const phi4 = phi2 * phi2;\n delta = (phi * (1.007226 + phi2 * (0.015085 + phi4 * (-0.044475 + 0.028874 * phi2 - 0.005916 * phi4))) - y) /\n (1.007226 + phi2 * (0.015085 * 3 + phi4 * (-0.044475 * 7 + 0.028874 * 9 * phi2 - 0.005916 * 11 * phi4)));\n phi = clamp(phi - delta, -maxPhi, maxPhi);\n } while (Math.abs(delta) > epsilon && --i > 0);\n\n phi2 = phi * phi;\n const lambda = x / (0.8707 + phi2 * (-0.131979 + phi2 * (-0.013791 + phi2 * phi2 * phi2 * (0.003971 - 0.001529 * phi2))));\n\n const lng = clamp(radToDeg(lambda), -180, 180);\n const lat = radToDeg(phi);\n\n return new LngLat(lng, lat);\n }\n}\n","// @flow\nimport LngLat from '../lng_lat.js';\nimport {clamp, degToRad, radToDeg} from '../../util/util.js';\nimport {MAX_MERCATOR_LATITUDE} from '../mercator_coordinate.js';\nimport Projection from './projection.js';\n\nimport type {ProjectedPoint} from './projection.js';\n\nconst maxPhi = degToRad(MAX_MERCATOR_LATITUDE);\n\nexport default class WinkelTripel extends Projection {\n\n project(lng: number, lat: number): ProjectedPoint {\n lat = degToRad(lat);\n lng = degToRad(lng);\n const cosLat = Math.cos(lat);\n const twoOverPi = 2 / Math.PI;\n const alpha = Math.acos(cosLat * Math.cos(lng / 2));\n const sinAlphaOverAlpha = Math.sin(alpha) / alpha;\n const x = 0.5 * (lng * twoOverPi + (2 * cosLat * Math.sin(lng / 2)) / sinAlphaOverAlpha) || 0;\n const y = 0.5 * (lat + Math.sin(lat) / sinAlphaOverAlpha) || 0;\n return {\n x: (x / Math.PI + 0.5) * 0.5,\n y: 1 - (y / Math.PI + 1) * 0.5,\n z: 0\n };\n }\n\n unproject(x: number, y: number): LngLat {\n // based on https://github.com/d3/d3-geo-projection, MIT-licensed\n x = (2 * x - 0.5) * Math.PI;\n y = (2 * (1 - y) - 1) * Math.PI;\n let lambda = x;\n let phi = y;\n let i = 25;\n const epsilon = 1e-6;\n let dlambda = 0, dphi = 0;\n do {\n const cosphi = Math.cos(phi),\n sinphi = Math.sin(phi),\n sinphi2 = 2 * sinphi * cosphi,\n sin2phi = sinphi * sinphi,\n cos2phi = cosphi * cosphi,\n coslambda2 = Math.cos(lambda / 2),\n sinlambda2 = Math.sin(lambda / 2),\n sinlambda = 2 * coslambda2 * sinlambda2,\n sin2lambda2 = sinlambda2 * sinlambda2,\n C = 1 - cos2phi * coslambda2 * coslambda2,\n F = C ? 1 / C : 0,\n E = C ? Math.acos(cosphi * coslambda2) * Math.sqrt(1 / C) : 0,\n fx = 0.5 * (2 * E * cosphi * sinlambda2 + lambda * 2 / Math.PI) - x,\n fy = 0.5 * (E * sinphi + phi) - y,\n dxdlambda = 0.5 * F * (cos2phi * sin2lambda2 + E * cosphi * coslambda2 * sin2phi) + 1 / Math.PI,\n dxdphi = F * (sinlambda * sinphi2 / 4 - E * sinphi * sinlambda2),\n dydlambda = 0.125 * F * (sinphi2 * sinlambda2 - E * sinphi * cos2phi * sinlambda),\n dydphi = 0.5 * F * (sin2phi * coslambda2 + E * sin2lambda2 * cosphi) + 0.5,\n denominator = dxdphi * dydlambda - dydphi * dxdlambda;\n\n dlambda = (fy * dxdphi - fx * dydphi) / denominator;\n dphi = (fx * dydlambda - fy * dxdlambda) / denominator;\n lambda = clamp(lambda - dlambda, -Math.PI, Math.PI);\n phi = clamp(phi - dphi, -maxPhi, maxPhi);\n\n } while ((Math.abs(dlambda) > epsilon || Math.abs(dphi) > epsilon) && --i > 0);\n\n return new LngLat(radToDeg(lambda), radToDeg(phi));\n }\n}\n","// @flow\nimport LngLat from '../lng_lat.js';\nimport {clamp, degToRad, radToDeg} from '../../util/util.js';\nimport {MAX_MERCATOR_LATITUDE} from '../mercator_coordinate.js';\nimport Projection from './projection.js';\n\nimport type {ProjectionSpecification} from '../../style-spec/types.js';\nimport type {ProjectedPoint} from './projection.js';\n\nexport default class CylindricalEqualArea extends Projection {\n cosPhi: number;\n scale: number;\n\n constructor(options: ProjectionSpecification) {\n super(options);\n this.center = options.center || [0, 0];\n this.parallels = options.parallels || [0, 0];\n this.cosPhi = Math.max(0.01, Math.cos(degToRad(this.parallels[0])));\n // scale coordinates between 0 and 1 to avoid constraint issues\n this.scale = 1 / (2 * Math.max(Math.PI * this.cosPhi, 1 / this.cosPhi));\n this.wrap = true;\n this.supportsWorldCopies = true;\n }\n\n project(lng: number, lat: number): ProjectedPoint {\n const {scale, cosPhi} = this;\n const x = degToRad(lng) * cosPhi;\n const y = Math.sin(degToRad(lat)) / cosPhi;\n\n return {\n x: (x * scale) + 0.5,\n y: (-y * scale) + 0.5,\n z: 0\n };\n }\n\n unproject(x: number, y: number): LngLat {\n const {scale, cosPhi} = this;\n const x_ = (x - 0.5) / scale;\n const y_ = -(y - 0.5) / scale;\n const lng = clamp(radToDeg(x_) / cosPhi, -180, 180);\n const y2 = y_ * cosPhi;\n const y3 = Math.asin(clamp(y2, -1, 1));\n const lat = clamp(radToDeg(y3), -MAX_MERCATOR_LATITUDE, MAX_MERCATOR_LATITUDE);\n\n return new LngLat(lng, lat);\n }\n}\n","// @flow\nimport {mat4, vec3} from 'gl-matrix';\nimport EXTENT from '../../data/extent.js';\nimport LngLat from '../lng_lat.js';\nimport {degToRad} from '../../util/util.js';\nimport MercatorCoordinate, {\n mercatorZfromAltitude,\n} from '../mercator_coordinate.js';\nimport Mercator from './mercator.js';\nimport Point from '@mapbox/point-geometry';\nimport {farthestPixelDistanceOnPlane, farthestPixelDistanceOnSphere} from './far_z.js';\nimport {number as interpolate} from '../../style-spec/util/interpolate.js';\nimport {\n GLOBE_SCALE_MATCH_LATITUDE,\n latLngToECEF,\n globeTileBounds,\n globeNormalizeECEF,\n globeDenormalizeECEF,\n globeECEFNormalizationScale,\n globeToMercatorTransition,\n globePointCoordinate,\n tileCoordToECEF,\n globeMetersToEcef\n} from './globe_util.js';\n\nimport type Transform from '../transform.js';\nimport type {ElevationScale} from './projection.js';\nimport type {Vec3} from 'gl-matrix';\nimport type {ProjectionSpecification} from '../../style-spec/types.js';\nimport type {CanonicalTileID, UnwrappedTileID} from '../../source/tile_id.js';\n\nexport default class Globe extends Mercator {\n\n constructor(options: ProjectionSpecification) {\n super(options);\n this.requiresDraping = true;\n this.supportsWorldCopies = false;\n this.supportsFog = true;\n this.zAxisUnit = \"pixels\";\n this.unsupportedLayers = ['debug'];\n this.range = [3, 5];\n }\n\n projectTilePoint(x: number, y: number, id: CanonicalTileID): {x: number, y: number, z: number} {\n const pos = tileCoordToECEF(x, y, id);\n const bounds = globeTileBounds(id);\n const normalizationMatrix = globeNormalizeECEF(bounds);\n vec3.transformMat4(pos, pos, normalizationMatrix);\n\n return {x: pos[0], y: pos[1], z: pos[2]};\n }\n\n locationPoint(tr: Transform, lngLat: LngLat): Point {\n const pos = latLngToECEF(lngLat.lat, lngLat.lng);\n const up = vec3.normalize([], pos);\n\n const elevation = tr.elevation ?\n tr.elevation.getAtPointOrZero(tr.locationCoordinate(lngLat), tr._centerAltitude) :\n tr._centerAltitude;\n\n const upScale = mercatorZfromAltitude(1, 0) * EXTENT * elevation;\n vec3.scaleAndAdd(pos, pos, up, upScale);\n const matrix = mat4.identity(new Float64Array(16));\n mat4.multiply(matrix, tr.pixelMatrix, tr.globeMatrix);\n vec3.transformMat4(pos, pos, matrix);\n\n return new Point(pos[0], pos[1]);\n }\n\n pixelsPerMeter(lat: number, worldSize: number): number {\n return mercatorZfromAltitude(1, 0) * worldSize;\n }\n\n pixelSpaceConversion(lat: number, worldSize: number, interpolationT: number): number {\n // Using only the center latitude to determine scale causes the globe to rapidly change\n // size as you pan up and down. As you approach the pole, the globe's size approaches infinity.\n // This is because zoom levels are based on mercator.\n //\n // Instead, use a fixed reference latitude at lower zoom levels. And transition between\n // this latitude and the center's latitude as you zoom in. This is a compromise that\n // makes globe view more usable with existing camera parameters, styles and data.\n const centerScale = mercatorZfromAltitude(1, lat) * worldSize;\n const referenceScale = mercatorZfromAltitude(1, GLOBE_SCALE_MATCH_LATITUDE) * worldSize;\n const combinedScale = interpolate(referenceScale, centerScale, interpolationT);\n return this.pixelsPerMeter(lat, worldSize) / combinedScale;\n }\n\n createTileMatrix(tr: Transform, worldSize: number, id: UnwrappedTileID): Float64Array {\n const decode = globeDenormalizeECEF(globeTileBounds(id.canonical));\n return mat4.multiply(new Float64Array(16), tr.globeMatrix, decode);\n }\n\n createInversionMatrix(tr: Transform, id: CanonicalTileID): Float32Array {\n const {center} = tr;\n const matrix = globeNormalizeECEF(globeTileBounds(id));\n mat4.rotateY(matrix, matrix, degToRad(center.lng));\n mat4.rotateX(matrix, matrix, degToRad(center.lat));\n mat4.scale(matrix, matrix, [tr._pixelsPerMercatorPixel, tr._pixelsPerMercatorPixel, 1.0]);\n return Float32Array.from(matrix);\n }\n\n pointCoordinate(tr: Transform, x: number, y: number, _: number): MercatorCoordinate {\n const coord = globePointCoordinate(tr, x, y, true);\n if (!coord) { return new MercatorCoordinate(0, 0); } // This won't happen, is here for Flow\n return coord;\n }\n\n pointCoordinate3D(tr: Transform, x: number, y: number): ?Vec3 {\n const coord = this.pointCoordinate(tr, x, y, 0);\n return [coord.x, coord.y, coord.z];\n }\n\n isPointAboveHorizon(tr: Transform, p: Point): boolean {\n const raycastOnGlobe = globePointCoordinate(tr, p.x, p.y, false);\n return !raycastOnGlobe;\n }\n\n farthestPixelDistance(tr: Transform): number {\n const pixelsPerMeter = this.pixelsPerMeter(tr.center.lat, tr.worldSize);\n const globePixelDistance = farthestPixelDistanceOnSphere(tr, pixelsPerMeter);\n const t = globeToMercatorTransition(tr.zoom);\n if (t > 0.0) {\n const mercatorPixelsPerMeter = mercatorZfromAltitude(1, tr.center.lat) * tr.worldSize;\n const mercatorPixelDistance = farthestPixelDistanceOnPlane(tr, mercatorPixelsPerMeter);\n const pixelRadius = tr.worldSize / (2.0 * Math.PI);\n const approxTileArcHalfAngle = Math.max(tr.width, tr.height) / tr.worldSize * Math.PI;\n const padding = pixelRadius * (1.0 - Math.cos(approxTileArcHalfAngle));\n\n // During transition to mercator we would like to keep\n // the far plane lower to ensure that geometries (e.g. circles) that are far away and are not supposed\n // to be rendered get culled out correctly. see https://github.com/mapbox/mapbox-gl-js/issues/11476\n // To achieve this we dampen the interpolation.\n return interpolate(globePixelDistance, mercatorPixelDistance + padding, Math.pow(t, 10.0));\n }\n return globePixelDistance;\n }\n\n upVector(id: CanonicalTileID, x: number, y: number): Vec3 {\n return tileCoordToECEF(x, y, id, 1);\n }\n\n upVectorScale(id: CanonicalTileID): ElevationScale {\n return {metersToTile: globeMetersToEcef(globeECEFNormalizationScale(globeTileBounds(id)))};\n }\n}\n","// @flow\nimport Albers from './albers.js';\nimport EqualEarth from './equal_earth.js';\nimport Equirectangular from './equirectangular.js';\nimport LambertConformalConic from './lambert.js';\nimport Mercator from './mercator.js';\nimport NaturalEarth from './natural_earth.js';\nimport WinkelTripel from './winkel_tripel.js';\nimport CylindricalEqualArea from './cylindrical_equal_area.js';\nimport Globe from './globe.js';\n\nimport type {ProjectionSpecification} from '../../style-spec/types.js';\nimport type Projection from './projection.js';\n\nexport function getProjection(config: ProjectionSpecification): Projection {\n\n const parallels = config.parallels;\n const isDegenerateConic = parallels ? Math.abs(parallels[0] + parallels[1]) < 0.01 : false;\n\n switch (config.name) {\n case 'mercator':\n return new Mercator(config);\n case 'equirectangular':\n return new Equirectangular(config);\n case 'naturalEarth':\n return new NaturalEarth(config);\n case 'equalEarth':\n return new EqualEarth(config);\n case 'winkelTripel':\n return new WinkelTripel(config);\n case 'albers':\n return isDegenerateConic ? new CylindricalEqualArea(config) : new Albers(config);\n case 'lambertConformalConic':\n return isDegenerateConic ? new CylindricalEqualArea(config) : new LambertConformalConic(config);\n case 'globe':\n return new Globe(config);\n }\n\n throw new Error(`Invalid projection name: ${config.name}`);\n}\n","// @flow\n\nimport {symbolLayoutAttributes,\n symbolGlobeExtAttributes,\n collisionVertexAttributes,\n collisionVertexAttributesExt,\n collisionBoxLayout,\n dynamicLayoutAttributes\n} from './symbol_attributes.js';\n\nimport {SymbolLayoutArray,\n SymbolGlobeExtArray,\n SymbolDynamicLayoutArray,\n SymbolOpacityArray,\n CollisionBoxLayoutArray,\n CollisionVertexExtArray,\n CollisionVertexArray,\n PlacedSymbolArray,\n SymbolInstanceArray,\n GlyphOffsetArray,\n SymbolLineVertexArray\n} from '../array_types.js';\n\nimport ONE_EM from '../../symbol/one_em.js';\nimport * as symbolSize from '../../symbol/symbol_size.js';\nimport Point from '@mapbox/point-geometry';\nimport SegmentVector from '../segment.js';\nimport {ProgramConfigurationSet} from '../program_configuration.js';\nimport {TriangleIndexArray, LineIndexArray} from '../index_array_type.js';\nimport transformText from '../../symbol/transform_text.js';\nimport mergeLines from '../../symbol/mergelines.js';\nimport {allowsVerticalWritingMode, stringContainsRTLText} from '../../util/script_detection.js';\nimport {WritingMode} from '../../symbol/shaping.js';\nimport loadGeometry from '../load_geometry.js';\nimport toEvaluationFeature from '../evaluation_feature.js';\nimport {VectorTileFeature} from '@mapbox/vector-tile';\nconst vectorTileFeatureTypes = VectorTileFeature.types;\nimport {verticalizedCharacterMap} from '../../util/verticalize_punctuation.js';\nimport Anchor from '../../symbol/anchor.js';\nimport {getSizeData} from '../../symbol/symbol_size.js';\nimport {MAX_PACKED_SIZE} from '../../symbol/symbol_layout.js';\nimport {register} from '../../util/web_worker_transfer.js';\nimport EvaluationParameters from '../../style/evaluation_parameters.js';\nimport Formatted from '../../style-spec/expression/types/formatted.js';\nimport ResolvedImage from '../../style-spec/expression/types/resolved_image.js';\nimport {plugin as globalRTLTextPlugin, getRTLTextPluginStatus} from '../../source/rtl_text_plugin.js';\nimport {resamplePred} from '../../geo/projection/resample.js';\nimport {tileCoordToECEF} from '../../geo/projection/globe_util.js';\nimport type {ProjectionSpecification} from '../../style-spec/types.js';\nimport {getProjection} from '../../geo/projection/index.js';\nimport type Projection from '../../geo/projection/projection.js';\nimport {mat4, vec3} from 'gl-matrix';\n\nimport type {CanonicalTileID, OverscaledTileID} from '../../source/tile_id.js';\nimport type {\n Bucket,\n BucketParameters,\n IndexedFeature,\n PopulateParameters\n} from '../bucket.js';\nimport type {CollisionBoxArray, CollisionBox, SymbolInstance} from '../array_types.js';\nimport type {StructArray, StructArrayMember} from '../../util/struct_array.js';\nimport SymbolStyleLayer from '../../style/style_layer/symbol_style_layer.js';\nimport type Context from '../../gl/context.js';\nimport type IndexBuffer from '../../gl/index_buffer.js';\nimport type VertexBuffer from '../../gl/vertex_buffer.js';\nimport type {SymbolQuad} from '../../symbol/quads.js';\nimport type {SizeData} from '../../symbol/symbol_size.js';\nimport type {FeatureStates} from '../../source/source_state.js';\nimport type {TileTransform} from '../../geo/projection/tile_transform.js';\nexport type SingleCollisionBox = {\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n padding: number;\n projectedAnchorX: number;\n projectedAnchorY: number;\n projectedAnchorZ: number;\n tileAnchorX: number;\n tileAnchorY: number;\n elevation?: number;\n tileID?: OverscaledTileID;\n};\nimport type {Mat4, Vec3} from 'gl-matrix';\nimport type {SpritePositions} from '../../util/image.js';\nimport type {IVectorTileLayer} from '@mapbox/vector-tile';\n\nexport type CollisionArrays = {\n textBox?: SingleCollisionBox;\n verticalTextBox?: SingleCollisionBox;\n iconBox?: SingleCollisionBox;\n verticalIconBox?: SingleCollisionBox;\n textFeatureIndex?: number;\n verticalTextFeatureIndex?: number;\n iconFeatureIndex?: number;\n verticalIconFeatureIndex?: number;\n};\n\nexport type SymbolFeature = {|\n sortKey: number | void,\n text: Formatted | void,\n icon: ?ResolvedImage,\n index: number,\n sourceLayerIndex: number,\n geometry: Array<Array<Point>>,\n properties: Object,\n type: 'Point' | 'LineString' | 'Polygon',\n id?: any\n|};\n\nexport type SortKeyRange = {\n sortKey: number,\n symbolInstanceStart: number,\n symbolInstanceEnd: number\n};\n\ntype LineVertexRange = {|\n lineLength: number,\n lineStartIndex: number\n|};\n\n// Opacity arrays are frequently updated but don't contain a lot of information, so we pack them\n// tight. Each Uint32 is actually four duplicate Uint8s for the four corners of a glyph\n// 7 bits are for the current opacity, and the lowest bit is the target opacity\n\n// actually defined in symbol_attributes.js\n// const placementOpacityAttributes = [\n// { name: 'a_fade_opacity', components: 1, type: 'Uint32' }\n// ];\nconst shaderOpacityAttributes = [\n {name: 'a_fade_opacity', components: 1, type: 'Uint8', offset: 0}\n];\n\nfunction addVertex(array: SymbolLayoutArray, tileAnchorX: number, tileAnchorY: number, ox: number, oy: number, tx: number, ty: number, sizeVertex: any, isSDF: boolean, pixelOffsetX: number, pixelOffsetY: number, minFontScaleX: number, minFontScaleY: number) {\n const aSizeX = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[0])) : 0;\n const aSizeY = sizeVertex ? Math.min(MAX_PACKED_SIZE, Math.round(sizeVertex[1])) : 0;\n\n array.emplaceBack(\n // a_pos_offset\n tileAnchorX,\n tileAnchorY,\n Math.round(ox * 32),\n Math.round(oy * 32),\n\n // a_data\n tx, // x coordinate of symbol on glyph atlas texture\n ty, // y coordinate of symbol on glyph atlas texture\n (aSizeX << 1) + (isSDF ? 1 : 0),\n aSizeY,\n pixelOffsetX * 16,\n pixelOffsetY * 16,\n minFontScaleX * 256,\n minFontScaleY * 256\n );\n}\n\nfunction addGlobeVertex(array: SymbolGlobeExtArray, projAnchorX: number, projAnchorY: number, projAnchorZ: number, normX: number, normY: number, normZ: number) {\n array.emplaceBack(\n // a_globe_anchor\n projAnchorX,\n projAnchorY,\n projAnchorZ,\n\n // a_globe_normal\n normX,\n normY,\n normZ\n );\n}\n\nfunction updateGlobeVertexNormal(array: SymbolGlobeExtArray, vertexIdx: number, normX: number, normY: number, normZ: number) {\n // Modify float32 array directly. 20 bytes per entry, 3xInt16 for position, 3xfloat32 for normal\n const offset = vertexIdx * 5 + 2;\n array.float32[offset + 0] = normX;\n array.float32[offset + 1] = normY;\n array.float32[offset + 2] = normZ;\n}\n\nfunction addDynamicAttributes(dynamicLayoutVertexArray: StructArray, x: number, y: number, z: number, angle: number) {\n dynamicLayoutVertexArray.emplaceBack(x, y, z, angle);\n dynamicLayoutVertexArray.emplaceBack(x, y, z, angle);\n dynamicLayoutVertexArray.emplaceBack(x, y, z, angle);\n dynamicLayoutVertexArray.emplaceBack(x, y, z, angle);\n}\n\nfunction containsRTLText(formattedText: Formatted): boolean {\n for (const section of formattedText.sections) {\n if (stringContainsRTLText(section.text)) {\n return true;\n }\n }\n return false;\n}\n\nexport class SymbolBuffers {\n layoutVertexArray: SymbolLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n programConfigurations: ProgramConfigurationSet<SymbolStyleLayer>;\n segments: SegmentVector;\n\n dynamicLayoutVertexArray: SymbolDynamicLayoutArray;\n dynamicLayoutVertexBuffer: VertexBuffer;\n\n opacityVertexArray: SymbolOpacityArray;\n opacityVertexBuffer: VertexBuffer;\n\n globeExtVertexArray: SymbolGlobeExtArray;\n globeExtVertexBuffer: VertexBuffer;\n\n placedSymbolArray: PlacedSymbolArray;\n\n constructor(programConfigurations: ProgramConfigurationSet<SymbolStyleLayer>) {\n this.layoutVertexArray = new SymbolLayoutArray();\n this.indexArray = new TriangleIndexArray();\n this.programConfigurations = programConfigurations;\n this.segments = new SegmentVector();\n this.dynamicLayoutVertexArray = new SymbolDynamicLayoutArray();\n this.opacityVertexArray = new SymbolOpacityArray();\n this.placedSymbolArray = new PlacedSymbolArray();\n this.globeExtVertexArray = new SymbolGlobeExtArray();\n }\n\n isEmpty(): boolean {\n return this.layoutVertexArray.length === 0 &&\n this.indexArray.length === 0 &&\n this.dynamicLayoutVertexArray.length === 0 &&\n this.opacityVertexArray.length === 0;\n }\n\n upload(context: Context, dynamicIndexBuffer: boolean, upload?: boolean, update?: boolean) {\n if (this.isEmpty()) {\n return;\n }\n\n if (upload) {\n this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, symbolLayoutAttributes.members);\n this.indexBuffer = context.createIndexBuffer(this.indexArray, dynamicIndexBuffer);\n this.dynamicLayoutVertexBuffer = context.createVertexBuffer(this.dynamicLayoutVertexArray, dynamicLayoutAttributes.members, true);\n this.opacityVertexBuffer = context.createVertexBuffer(this.opacityVertexArray, shaderOpacityAttributes, true);\n if (this.globeExtVertexArray.length > 0) {\n this.globeExtVertexBuffer = context.createVertexBuffer(this.globeExtVertexArray, symbolGlobeExtAttributes.members, true);\n }\n // This is a performance hack so that we can write to opacityVertexArray with uint32s\n // even though the shaders read uint8s\n this.opacityVertexBuffer.itemSize = 1;\n }\n if (upload || update) {\n this.programConfigurations.upload(context);\n }\n }\n\n destroy() {\n if (!this.layoutVertexBuffer) return;\n this.layoutVertexBuffer.destroy();\n this.indexBuffer.destroy();\n this.programConfigurations.destroy();\n this.segments.destroy();\n this.dynamicLayoutVertexBuffer.destroy();\n this.opacityVertexBuffer.destroy();\n if (this.globeExtVertexBuffer) {\n this.globeExtVertexBuffer.destroy();\n }\n }\n}\n\nregister(SymbolBuffers, 'SymbolBuffers');\n\nclass CollisionBuffers {\n layoutVertexArray: StructArray;\n layoutAttributes: Array<StructArrayMember>;\n layoutVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray | LineIndexArray;\n indexBuffer: IndexBuffer;\n\n segments: SegmentVector;\n\n collisionVertexArray: CollisionVertexArray;\n collisionVertexBuffer: VertexBuffer;\n\n collisionVertexArrayExt: CollisionVertexExtArray;\n collisionVertexBufferExt: VertexBuffer;\n\n constructor(LayoutArray: Class<StructArray>,\n layoutAttributes: Array<StructArrayMember>,\n IndexArray: Class<TriangleIndexArray | LineIndexArray>) {\n this.layoutVertexArray = new LayoutArray();\n this.layoutAttributes = layoutAttributes;\n this.indexArray = new IndexArray();\n this.segments = new SegmentVector();\n this.collisionVertexArray = new CollisionVertexArray();\n this.collisionVertexArrayExt = new CollisionVertexExtArray();\n }\n\n upload(context: Context) {\n this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes);\n this.indexBuffer = context.createIndexBuffer(this.indexArray);\n this.collisionVertexBuffer = context.createVertexBuffer(this.collisionVertexArray, collisionVertexAttributes.members, true);\n this.collisionVertexBufferExt = context.createVertexBuffer(this.collisionVertexArrayExt, collisionVertexAttributesExt.members, true);\n }\n\n destroy() {\n if (!this.layoutVertexBuffer) return;\n this.layoutVertexBuffer.destroy();\n this.indexBuffer.destroy();\n this.segments.destroy();\n this.collisionVertexBuffer.destroy();\n this.collisionVertexBufferExt.destroy();\n }\n}\n\nregister(CollisionBuffers, 'CollisionBuffers');\n\n/**\n * Unlike other buckets, which simply implement #addFeature with type-specific\n * logic for (essentially) triangulating feature geometries, SymbolBucket\n * requires specialized behavior:\n *\n * 1. WorkerTile#parse(), the logical owner of the bucket creation process,\n * calls SymbolBucket#populate(), which resolves text and icon tokens on\n * each feature, adds each glyphs and symbols needed to the passed-in\n * collections options.glyphDependencies and options.iconDependencies, and\n * stores the feature data for use in subsequent step (this.features).\n *\n * 2. WorkerTile asynchronously requests from the main thread all of the glyphs\n * and icons needed (by this bucket and any others). When glyphs and icons\n * have been received, the WorkerTile creates a CollisionIndex and invokes:\n *\n * 3. performSymbolLayout(bucket, stacks, icons) perform texts shaping and\n * layout on a Symbol Bucket. This step populates:\n * `this.symbolInstances`: metadata on generated symbols\n * `collisionBoxArray`: collision data for use by foreground\n * `this.text`: SymbolBuffers for text symbols\n * `this.icons`: SymbolBuffers for icons\n * `this.iconCollisionBox`: Debug SymbolBuffers for icon collision boxes\n * `this.textCollisionBox`: Debug SymbolBuffers for text collision boxes\n * The results are sent to the foreground for rendering\n *\n * 4. Placement.updateBucketOpacities() is run on the foreground,\n * and uses the CollisionIndex along with current camera settings to determine\n * which symbols can actually show on the map. Collided symbols are hidden\n * using a dynamic \"OpacityVertexArray\".\n *\n * @private\n */\nclass SymbolBucket implements Bucket {\n static MAX_GLYPHS: number;\n static addDynamicAttributes: typeof addDynamicAttributes;\n\n collisionBoxArray: CollisionBoxArray;\n zoom: number;\n overscaling: number;\n layers: Array<SymbolStyleLayer>;\n layerIds: Array<string>;\n stateDependentLayers: Array<SymbolStyleLayer>;\n stateDependentLayerIds: Array<string>;\n\n index: number;\n sdfIcons: boolean;\n iconsInText: boolean;\n iconsNeedLinear: boolean;\n bucketInstanceId: number;\n justReloaded: boolean;\n hasPattern: boolean;\n fullyClipped: boolean;\n\n textSizeData: SizeData;\n iconSizeData: SizeData;\n\n glyphOffsetArray: GlyphOffsetArray;\n lineVertexArray: SymbolLineVertexArray;\n features: Array<SymbolFeature>;\n symbolInstances: SymbolInstanceArray;\n collisionArrays: Array<CollisionArrays>;\n sortKeyRanges: Array<SortKeyRange>;\n pixelRatio: number;\n tilePixelRatio: number;\n compareText: {[_: string]: Array<Point>};\n fadeStartTime: number;\n sortFeaturesByKey: boolean;\n sortFeaturesByY: boolean;\n canOverlap: boolean;\n sortedAngle: number;\n featureSortOrder: Array<number>;\n\n collisionCircleArray: Array<number>;\n placementInvProjMatrix: Mat4;\n placementViewportMatrix: Mat4;\n\n text: SymbolBuffers;\n icon: SymbolBuffers;\n textCollisionBox: CollisionBuffers;\n iconCollisionBox: CollisionBuffers;\n uploaded: boolean;\n sourceLayerIndex: number;\n sourceID: string;\n symbolInstanceIndexes: Array<number>;\n writingModes: Array<number>;\n allowVerticalPlacement: boolean;\n hasRTLText: boolean;\n projection: ProjectionSpecification;\n projectionInstance: ?Projection;\n\n constructor(options: BucketParameters<SymbolStyleLayer>) {\n this.collisionBoxArray = options.collisionBoxArray;\n this.zoom = options.zoom;\n this.overscaling = options.overscaling;\n this.layers = options.layers;\n this.layerIds = this.layers.map(layer => layer.id);\n this.index = options.index;\n this.pixelRatio = options.pixelRatio;\n this.sourceLayerIndex = options.sourceLayerIndex;\n this.hasPattern = false;\n this.hasRTLText = false;\n this.fullyClipped = false;\n this.sortKeyRanges = [];\n\n this.collisionCircleArray = [];\n this.placementInvProjMatrix = mat4.identity([]);\n this.placementViewportMatrix = mat4.identity([]);\n\n const layer = this.layers[0];\n const unevaluatedLayoutValues = layer._unevaluatedLayout._values;\n\n this.textSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['text-size']);\n this.iconSizeData = getSizeData(this.zoom, unevaluatedLayoutValues['icon-size']);\n\n const layout = this.layers[0].layout;\n const sortKey = layout.get('symbol-sort-key');\n const zOrder = layout.get('symbol-z-order');\n this.canOverlap =\n layout.get('text-allow-overlap') ||\n layout.get('icon-allow-overlap') ||\n layout.get('text-ignore-placement') ||\n layout.get('icon-ignore-placement');\n this.sortFeaturesByKey = zOrder !== 'viewport-y' && sortKey.constantOr(1) !== undefined;\n const zOrderByViewportY = zOrder === 'viewport-y' || (zOrder === 'auto' && !this.sortFeaturesByKey);\n this.sortFeaturesByY = zOrderByViewportY && this.canOverlap;\n\n this.writingModes = layout.get('text-writing-mode').map(wm => WritingMode[wm]);\n\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n\n this.sourceID = options.sourceID;\n this.projection = options.projection;\n }\n\n createArrays() {\n this.text = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^text/.test(property)));\n this.icon = new SymbolBuffers(new ProgramConfigurationSet(this.layers, this.zoom, property => /^icon/.test(property)));\n\n this.glyphOffsetArray = new GlyphOffsetArray();\n this.lineVertexArray = new SymbolLineVertexArray();\n this.symbolInstances = new SymbolInstanceArray();\n }\n\n calculateGlyphDependencies(text: string, stack: {[_: number]: boolean}, textAlongLine: boolean, allowVerticalPlacement: boolean, doesAllowVerticalWritingMode: boolean) {\n for (let i = 0; i < text.length; i++) {\n stack[text.charCodeAt(i)] = true;\n if (allowVerticalPlacement && doesAllowVerticalWritingMode) {\n const verticalChar = verticalizedCharacterMap[text.charAt(i)];\n if (verticalChar) {\n stack[verticalChar.charCodeAt(0)] = true;\n }\n }\n }\n }\n\n populate(features: Array<IndexedFeature>, options: PopulateParameters, canonical: CanonicalTileID, tileTransform: TileTransform) {\n const layer = this.layers[0];\n const layout = layer.layout;\n const isGlobe = this.projection.name === 'globe';\n\n const textFont = layout.get('text-font');\n const textField = layout.get('text-field');\n const iconImage = layout.get('icon-image');\n const hasText =\n (textField.value.kind !== 'constant' ||\n (textField.value.value instanceof Formatted && !textField.value.value.isEmpty()) ||\n textField.value.value.toString().length > 0) &&\n (textFont.value.kind !== 'constant' || textFont.value.value.length > 0);\n // we should always resolve the icon-image value if the property was defined in the style\n // this allows us to fire the styleimagemissing event if image evaluation returns null\n // the only way to distinguish between null returned from a coalesce statement with no valid images\n // and null returned because icon-image wasn't defined is to check whether or not iconImage.parameters is an empty object\n const hasIcon = iconImage.value.kind !== 'constant' || !!iconImage.value.value || Object.keys(iconImage.parameters).length > 0;\n const symbolSortKey = layout.get('symbol-sort-key');\n\n this.features = [];\n\n if (!hasText && !hasIcon) {\n return;\n }\n\n const icons = options.iconDependencies;\n const stacks = options.glyphDependencies;\n const availableImages = options.availableImages;\n const globalProperties = new EvaluationParameters(this.zoom);\n\n for (const {feature, id, index, sourceLayerIndex} of features) {\n\n const needGeometry = layer._featureFilter.needGeometry;\n const evaluationFeature = toEvaluationFeature(feature, needGeometry);\n // $FlowFixMe[method-unbinding]\n if (!layer._featureFilter.filter(globalProperties, evaluationFeature, canonical)) {\n continue;\n }\n\n if (!needGeometry) evaluationFeature.geometry = loadGeometry(feature, canonical, tileTransform);\n\n if (isGlobe && feature.type !== 1 && canonical.z <= 5) {\n // Resample long lines and polygons in globe view so that their length wont exceed ~0.19 radians (360/32 degrees).\n // Otherwise lines could clip through the globe as the resolution is not enough to represent curved paths.\n // The threshold value follows subdivision size used with fill extrusions\n const geom = evaluationFeature.geometry;\n\n // cos(11.25 degrees) = 0.98078528056\n const cosAngleThreshold = 0.98078528056;\n const predicate = (a: Point, b: Point) => {\n const v0 = tileCoordToECEF(a.x, a.y, canonical, 1);\n const v1 = tileCoordToECEF(b.x, b.y, canonical, 1);\n return vec3.dot(v0, v1) < cosAngleThreshold;\n };\n\n for (let i = 0; i < geom.length; i++) {\n geom[i] = resamplePred(geom[i], predicate);\n }\n }\n\n let text: Formatted | void;\n if (hasText) {\n // Expression evaluation will automatically coerce to Formatted\n // but plain string token evaluation skips that pathway so do the\n // conversion here.\n const resolvedTokens = layer.getValueAndResolveTokens('text-field', evaluationFeature, canonical, availableImages);\n const formattedText = Formatted.factory(resolvedTokens);\n if (containsRTLText(formattedText)) {\n this.hasRTLText = true;\n }\n if (\n !this.hasRTLText || // non-rtl text so can proceed safely\n getRTLTextPluginStatus() === 'unavailable' || // We don't intend to lazy-load the rtl text plugin, so proceed with incorrect shaping\n (this.hasRTLText && globalRTLTextPlugin.isParsed()) // Use the rtlText plugin to shape text\n ) {\n text = transformText(formattedText, layer, evaluationFeature);\n }\n }\n\n let icon: ?ResolvedImage;\n if (hasIcon) {\n // Expression evaluation will automatically coerce to Image\n // but plain string token evaluation skips that pathway so do the\n // conversion here.\n const resolvedTokens = layer.getValueAndResolveTokens('icon-image', evaluationFeature, canonical, availableImages);\n if (resolvedTokens instanceof ResolvedImage) {\n icon = resolvedTokens;\n } else {\n icon = ResolvedImage.fromString(resolvedTokens);\n }\n }\n\n if (!text && !icon) {\n continue;\n }\n const sortKey = this.sortFeaturesByKey ?\n symbolSortKey.evaluate(evaluationFeature, {}, canonical) :\n undefined;\n\n const symbolFeature: SymbolFeature = {\n id,\n text,\n icon,\n index,\n sourceLayerIndex,\n geometry: evaluationFeature.geometry,\n properties: feature.properties,\n type: vectorTileFeatureTypes[feature.type],\n sortKey\n };\n this.features.push(symbolFeature);\n\n if (icon) {\n icons[icon.name] = true;\n }\n\n if (text) {\n const fontStack = textFont.evaluate(evaluationFeature, {}, canonical).join(',');\n const textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point';\n this.allowVerticalPlacement = this.writingModes && this.writingModes.indexOf(WritingMode.vertical) >= 0;\n for (const section of text.sections) {\n if (!section.image) {\n const doesAllowVerticalWritingMode = allowsVerticalWritingMode(text.toString());\n const sectionFont = section.fontStack || fontStack;\n const sectionStack = stacks[sectionFont] = stacks[sectionFont] || {};\n this.calculateGlyphDependencies(section.text, sectionStack, textAlongLine, this.allowVerticalPlacement, doesAllowVerticalWritingMode);\n } else {\n // Add section image to the list of dependencies.\n icons[section.image.name] = true;\n }\n }\n }\n }\n\n if (layout.get('symbol-placement') === 'line') {\n // Merge adjacent lines with the same text to improve labelling.\n // It's better to place labels on one long line than on many short segments.\n this.features = mergeLines(this.features);\n }\n\n if (this.sortFeaturesByKey) {\n this.features.sort((a, b) => {\n // a.sortKey is always a number when sortFeaturesByKey is true\n return ((a.sortKey: any): number) - ((b.sortKey: any): number);\n });\n }\n }\n\n update(states: FeatureStates, vtLayer: IVectorTileLayer, availableImages: Array<string>, imagePositions: SpritePositions) {\n if (!this.stateDependentLayers.length) return;\n this.text.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, availableImages, imagePositions);\n this.icon.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, availableImages, imagePositions);\n }\n\n isEmpty(): boolean {\n // When the bucket encounters only rtl-text but the plugin isn't loaded, no symbol instances will be created.\n // In order for the bucket to be serialized, and not discarded as an empty bucket both checks are necessary.\n return this.symbolInstances.length === 0 && !this.hasRTLText;\n }\n\n uploadPending(): boolean {\n return !this.uploaded || this.text.programConfigurations.needsUpload || this.icon.programConfigurations.needsUpload;\n }\n\n upload(context: Context) {\n if (!this.uploaded && this.hasDebugData()) {\n this.textCollisionBox.upload(context);\n this.iconCollisionBox.upload(context);\n }\n this.text.upload(context, this.sortFeaturesByY, !this.uploaded, this.text.programConfigurations.needsUpload);\n this.icon.upload(context, this.sortFeaturesByY, !this.uploaded, this.icon.programConfigurations.needsUpload);\n this.uploaded = true;\n }\n\n destroyDebugData() {\n this.textCollisionBox.destroy();\n this.iconCollisionBox.destroy();\n }\n\n getProjection(): Projection {\n if (!this.projectionInstance) {\n this.projectionInstance = getProjection(this.projection);\n }\n return this.projectionInstance;\n }\n\n destroy() {\n this.text.destroy();\n this.icon.destroy();\n\n if (this.hasDebugData()) {\n this.destroyDebugData();\n }\n }\n\n addToLineVertexArray(anchor: Anchor, line: Array<Point>): LineVertexRange {\n const lineStartIndex = this.lineVertexArray.length;\n if (anchor.segment !== undefined) {\n for (const {x, y} of line) {\n this.lineVertexArray.emplaceBack(x, y);\n }\n }\n return {\n lineStartIndex,\n lineLength: this.lineVertexArray.length - lineStartIndex\n };\n }\n\n addSymbols(arrays: SymbolBuffers,\n quads: Array<SymbolQuad>,\n sizeVertex: any,\n lineOffset: [number, number],\n alongLine: boolean,\n feature: SymbolFeature,\n writingMode: any,\n globe: ?{ anchor: Anchor, up: Vec3 },\n tileAnchor: Anchor,\n lineStartIndex: number,\n lineLength: number,\n associatedIconIndex: number,\n availableImages: Array<string>,\n canonical: CanonicalTileID) {\n const indexArray = arrays.indexArray;\n const layoutVertexArray = arrays.layoutVertexArray;\n const globeExtVertexArray = arrays.globeExtVertexArray;\n\n const segment = arrays.segments.prepareSegment(4 * quads.length, layoutVertexArray, indexArray, this.canOverlap ? feature.sortKey : undefined);\n const glyphOffsetArrayStart = this.glyphOffsetArray.length;\n const vertexStartIndex = segment.vertexLength;\n\n const angle = (this.allowVerticalPlacement && writingMode === WritingMode.vertical) ? Math.PI / 2 : 0;\n\n const sections = feature.text && feature.text.sections;\n\n for (let i = 0; i < quads.length; i++) {\n const {tl, tr, bl, br, tex, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, glyphOffset, isSDF, sectionIndex} = quads[i];\n const index = segment.vertexLength;\n\n const y = glyphOffset[1];\n addVertex(layoutVertexArray, tileAnchor.x, tileAnchor.y, tl.x, y + tl.y, tex.x, tex.y, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY);\n addVertex(layoutVertexArray, tileAnchor.x, tileAnchor.y, tr.x, y + tr.y, tex.x + tex.w, tex.y, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY);\n addVertex(layoutVertexArray, tileAnchor.x, tileAnchor.y, bl.x, y + bl.y, tex.x, tex.y + tex.h, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY);\n addVertex(layoutVertexArray, tileAnchor.x, tileAnchor.y, br.x, y + br.y, tex.x + tex.w, tex.y + tex.h, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY);\n\n if (globe) {\n const {x, y, z} = globe.anchor;\n const [ux, uy, uz] = globe.up;\n addGlobeVertex(globeExtVertexArray, x, y, z, ux, uy, uz);\n addGlobeVertex(globeExtVertexArray, x, y, z, ux, uy, uz);\n addGlobeVertex(globeExtVertexArray, x, y, z, ux, uy, uz);\n addGlobeVertex(globeExtVertexArray, x, y, z, ux, uy, uz);\n\n addDynamicAttributes(arrays.dynamicLayoutVertexArray, x, y, z, angle);\n } else {\n addDynamicAttributes(arrays.dynamicLayoutVertexArray, tileAnchor.x, tileAnchor.y, tileAnchor.z, angle);\n }\n\n indexArray.emplaceBack(index, index + 1, index + 2);\n indexArray.emplaceBack(index + 1, index + 2, index + 3);\n\n segment.vertexLength += 4;\n segment.primitiveLength += 2;\n\n this.glyphOffsetArray.emplaceBack(glyphOffset[0]);\n\n if (i === quads.length - 1 || sectionIndex !== quads[i + 1].sectionIndex) {\n arrays.programConfigurations.populatePaintArrays(layoutVertexArray.length, feature, feature.index, {}, availableImages, canonical, sections && sections[sectionIndex]);\n }\n }\n\n const projectedAnchor = globe ? globe.anchor : tileAnchor;\n\n arrays.placedSymbolArray.emplaceBack(projectedAnchor.x, projectedAnchor.y, projectedAnchor.z, tileAnchor.x, tileAnchor.y,\n glyphOffsetArrayStart, this.glyphOffsetArray.length - glyphOffsetArrayStart, vertexStartIndex,\n lineStartIndex, lineLength, (tileAnchor.segment: any),\n sizeVertex ? sizeVertex[0] : 0, sizeVertex ? sizeVertex[1] : 0,\n lineOffset[0], lineOffset[1],\n writingMode,\n // placedOrientation is null initially; will be updated to horizontal(1)/vertical(2) if placed\n 0,\n (false: any),\n // The crossTileID is only filled/used on the foreground for dynamic text anchors\n 0,\n associatedIconIndex,\n // flipState is unknown initially; will be updated to flipRequired(1)/flipNotRequired(2) during line label reprojection\n 0\n );\n }\n\n _commitLayoutVertex(array: StructArray, boxTileAnchorX: number, boxTileAnchorY: number, boxTileAnchorZ: number, tileAnchorX: number, tileAnchorY: number, extrude: Point) {\n array.emplaceBack(\n // pos\n boxTileAnchorX,\n boxTileAnchorY,\n boxTileAnchorZ,\n // a_anchor_pos\n tileAnchorX,\n tileAnchorY,\n // extrude\n Math.round(extrude.x),\n Math.round(extrude.y));\n }\n\n _addCollisionDebugVertices(box: CollisionBox, scale: number, arrays: CollisionBuffers, boxTileAnchorX: number, boxTileAnchorY: number, boxTileAnchorZ: number, symbolInstance: SymbolInstance) {\n const segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray);\n const index = segment.vertexLength;\n const symbolTileAnchorX = symbolInstance.tileAnchorX;\n const symbolTileAnchorY = symbolInstance.tileAnchorY;\n\n for (let i = 0; i < 4; i++) {\n arrays.collisionVertexArray.emplaceBack(0, 0, 0, 0);\n }\n\n arrays.collisionVertexArrayExt.emplaceBack(scale, -box.padding, -box.padding);\n arrays.collisionVertexArrayExt.emplaceBack(scale, box.padding, -box.padding);\n arrays.collisionVertexArrayExt.emplaceBack(scale, box.padding, box.padding);\n arrays.collisionVertexArrayExt.emplaceBack(scale, -box.padding, box.padding);\n\n this._commitLayoutVertex(arrays.layoutVertexArray, boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, symbolTileAnchorX, symbolTileAnchorY, new Point(box.x1, box.y1));\n this._commitLayoutVertex(arrays.layoutVertexArray, boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, symbolTileAnchorX, symbolTileAnchorY, new Point(box.x2, box.y1));\n this._commitLayoutVertex(arrays.layoutVertexArray, boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, symbolTileAnchorX, symbolTileAnchorY, new Point(box.x2, box.y2));\n this._commitLayoutVertex(arrays.layoutVertexArray, boxTileAnchorX, boxTileAnchorY, boxTileAnchorZ, symbolTileAnchorX, symbolTileAnchorY, new Point(box.x1, box.y2));\n\n segment.vertexLength += 4;\n\n const indexArray: LineIndexArray = (arrays.indexArray: any);\n indexArray.emplaceBack(index, index + 1);\n indexArray.emplaceBack(index + 1, index + 2);\n indexArray.emplaceBack(index + 2, index + 3);\n indexArray.emplaceBack(index + 3, index);\n\n segment.primitiveLength += 4;\n }\n\n _addTextDebugCollisionBoxes(size: any, zoom: number, collisionBoxArray: CollisionBoxArray, startIndex: number, endIndex: number, instance: SymbolInstance) {\n for (let b = startIndex; b < endIndex; b++) {\n const box: CollisionBox = (collisionBoxArray.get(b): any);\n const scale = this.getSymbolInstanceTextSize(size, instance, zoom, b);\n\n this._addCollisionDebugVertices(box, scale, this.textCollisionBox, box.projectedAnchorX, box.projectedAnchorY, box.projectedAnchorZ, instance);\n }\n }\n\n _addIconDebugCollisionBoxes(size: any, zoom: number, collisionBoxArray: CollisionBoxArray, startIndex: number, endIndex: number, instance: SymbolInstance) {\n for (let b = startIndex; b < endIndex; b++) {\n const box: CollisionBox = (collisionBoxArray.get(b): any);\n const scale = this.getSymbolInstanceIconSize(size, zoom, instance.placedIconSymbolIndex);\n\n this._addCollisionDebugVertices(box, scale, this.iconCollisionBox, box.projectedAnchorX, box.projectedAnchorY, box.projectedAnchorZ, instance);\n }\n }\n\n generateCollisionDebugBuffers(zoom: number, collisionBoxArray: CollisionBoxArray) {\n if (this.hasDebugData()) {\n this.destroyDebugData();\n }\n\n this.textCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray);\n this.iconCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray);\n\n const iconSize = symbolSize.evaluateSizeForZoom(this.iconSizeData, zoom);\n const textSize = symbolSize.evaluateSizeForZoom(this.textSizeData, zoom);\n\n for (let i = 0; i < this.symbolInstances.length; i++) {\n const symbolInstance = this.symbolInstances.get(i);\n this._addTextDebugCollisionBoxes(textSize, zoom, collisionBoxArray, symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance);\n this._addTextDebugCollisionBoxes(textSize, zoom, collisionBoxArray, symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance);\n this._addIconDebugCollisionBoxes(iconSize, zoom, collisionBoxArray, symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance);\n this._addIconDebugCollisionBoxes(iconSize, zoom, collisionBoxArray, symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance);\n }\n }\n\n getSymbolInstanceTextSize(textSize: any, instance: SymbolInstance, zoom: number, boxIndex: number): number {\n const symbolIndex = instance.rightJustifiedTextSymbolIndex >= 0 ?\n instance.rightJustifiedTextSymbolIndex : instance.centerJustifiedTextSymbolIndex >= 0 ?\n instance.centerJustifiedTextSymbolIndex : instance.leftJustifiedTextSymbolIndex >= 0 ?\n instance.leftJustifiedTextSymbolIndex : instance.verticalPlacedTextSymbolIndex >= 0 ?\n instance.verticalPlacedTextSymbolIndex : boxIndex;\n\n const symbol = this.text.placedSymbolArray.get(symbolIndex);\n const featureSize = symbolSize.evaluateSizeForFeature(this.textSizeData, textSize, symbol) / ONE_EM;\n\n return this.tilePixelRatio * featureSize;\n }\n\n getSymbolInstanceIconSize(iconSize: any, zoom: number, iconIndex: number): number {\n const symbol = this.icon.placedSymbolArray.get(iconIndex);\n const featureSize = symbolSize.evaluateSizeForFeature(this.iconSizeData, iconSize, symbol);\n\n return this.tilePixelRatio * featureSize;\n }\n\n _commitDebugCollisionVertexUpdate(array: StructArray, scale: number, padding: number) {\n array.emplaceBack(scale, -padding, -padding);\n array.emplaceBack(scale, padding, -padding);\n array.emplaceBack(scale, padding, padding);\n array.emplaceBack(scale, -padding, padding);\n }\n\n _updateTextDebugCollisionBoxes(size: any, zoom: number, collisionBoxArray: CollisionBoxArray, startIndex: number, endIndex: number, instance: SymbolInstance) {\n for (let b = startIndex; b < endIndex; b++) {\n const box: CollisionBox = (collisionBoxArray.get(b): any);\n const scale = this.getSymbolInstanceTextSize(size, instance, zoom, b);\n const array = this.textCollisionBox.collisionVertexArrayExt;\n this._commitDebugCollisionVertexUpdate(array, scale, box.padding);\n }\n }\n\n _updateIconDebugCollisionBoxes(size: any, zoom: number, collisionBoxArray: CollisionBoxArray, startIndex: number, endIndex: number, symbolIndex: number) {\n for (let b = startIndex; b < endIndex; b++) {\n const box = (collisionBoxArray.get(b));\n const scale = this.getSymbolInstanceIconSize(size, zoom, symbolIndex);\n const array = this.iconCollisionBox.collisionVertexArrayExt;\n this._commitDebugCollisionVertexUpdate(array, scale, box.padding);\n }\n }\n\n updateCollisionDebugBuffers(zoom: number, collisionBoxArray: CollisionBoxArray) {\n if (!this.hasDebugData()) {\n return;\n }\n\n if (this.hasTextCollisionBoxData()) this.textCollisionBox.collisionVertexArrayExt.clear();\n if (this.hasIconCollisionBoxData()) this.iconCollisionBox.collisionVertexArrayExt.clear();\n\n const iconSize = symbolSize.evaluateSizeForZoom(this.iconSizeData, zoom);\n const textSize = symbolSize.evaluateSizeForZoom(this.textSizeData, zoom);\n\n for (let i = 0; i < this.symbolInstances.length; i++) {\n const symbolInstance = this.symbolInstances.get(i);\n this._updateTextDebugCollisionBoxes(textSize, zoom, collisionBoxArray, symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance);\n this._updateTextDebugCollisionBoxes(textSize, zoom, collisionBoxArray, symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance);\n this._updateIconDebugCollisionBoxes(iconSize, zoom, collisionBoxArray, symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance.placedIconSymbolIndex);\n this._updateIconDebugCollisionBoxes(iconSize, zoom, collisionBoxArray, symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance.placedIconSymbolIndex);\n }\n\n if (this.hasTextCollisionBoxData() && this.textCollisionBox.collisionVertexBufferExt) {\n this.textCollisionBox.collisionVertexBufferExt.updateData(this.textCollisionBox.collisionVertexArrayExt);\n }\n if (this.hasIconCollisionBoxData() && this.iconCollisionBox.collisionVertexBufferExt) {\n this.iconCollisionBox.collisionVertexBufferExt.updateData(this.iconCollisionBox.collisionVertexArrayExt);\n }\n }\n\n // These flat arrays are meant to be quicker to iterate over than the source\n // CollisionBoxArray\n _deserializeCollisionBoxesForSymbol(collisionBoxArray: CollisionBoxArray,\n textStartIndex: number, textEndIndex: number,\n verticalTextStartIndex: number, verticalTextEndIndex: number,\n iconStartIndex: number, iconEndIndex: number,\n verticalIconStartIndex: number, verticalIconEndIndex: number): CollisionArrays {\n\n // Only one box allowed per instance\n const collisionArrays = {};\n if (textStartIndex < textEndIndex) {\n const {x1, y1, x2, y2, padding, projectedAnchorX, projectedAnchorY, projectedAnchorZ, tileAnchorX, tileAnchorY, featureIndex} = collisionBoxArray.get(textStartIndex);\n collisionArrays.textBox = {x1, y1, x2, y2, padding, projectedAnchorX, projectedAnchorY, projectedAnchorZ, tileAnchorX, tileAnchorY};\n collisionArrays.textFeatureIndex = featureIndex;\n }\n if (verticalTextStartIndex < verticalTextEndIndex) {\n const {x1, y1, x2, y2, padding, projectedAnchorX, projectedAnchorY, projectedAnchorZ, tileAnchorX, tileAnchorY, featureIndex} = collisionBoxArray.get(verticalTextStartIndex);\n collisionArrays.verticalTextBox = {x1, y1, x2, y2, padding, projectedAnchorX, projectedAnchorY, projectedAnchorZ, tileAnchorX, tileAnchorY};\n collisionArrays.verticalTextFeatureIndex = featureIndex;\n }\n if (iconStartIndex < iconEndIndex) {\n const {x1, y1, x2, y2, padding, projectedAnchorX, projectedAnchorY, projectedAnchorZ, tileAnchorX, tileAnchorY, featureIndex} = collisionBoxArray.get(iconStartIndex);\n collisionArrays.iconBox = {x1, y1, x2, y2, padding, projectedAnchorX, projectedAnchorY, projectedAnchorZ, tileAnchorX, tileAnchorY};\n collisionArrays.iconFeatureIndex = featureIndex;\n }\n if (verticalIconStartIndex < verticalIconEndIndex) {\n const {x1, y1, x2, y2, padding, projectedAnchorX, projectedAnchorY, projectedAnchorZ, tileAnchorX, tileAnchorY, featureIndex} = collisionBoxArray.get(verticalIconStartIndex);\n collisionArrays.verticalIconBox = {x1, y1, x2, y2, padding, projectedAnchorX, projectedAnchorY, projectedAnchorZ, tileAnchorX, tileAnchorY};\n collisionArrays.verticalIconFeatureIndex = featureIndex;\n }\n return collisionArrays;\n }\n\n deserializeCollisionBoxes(collisionBoxArray: CollisionBoxArray) {\n this.collisionArrays = [];\n for (let i = 0; i < this.symbolInstances.length; i++) {\n const symbolInstance = this.symbolInstances.get(i);\n this.collisionArrays.push(this._deserializeCollisionBoxesForSymbol(\n collisionBoxArray,\n symbolInstance.textBoxStartIndex,\n symbolInstance.textBoxEndIndex,\n symbolInstance.verticalTextBoxStartIndex,\n symbolInstance.verticalTextBoxEndIndex,\n symbolInstance.iconBoxStartIndex,\n symbolInstance.iconBoxEndIndex,\n symbolInstance.verticalIconBoxStartIndex,\n symbolInstance.verticalIconBoxEndIndex\n ));\n }\n }\n\n hasTextData(): boolean {\n return this.text.segments.get().length > 0;\n }\n\n hasIconData(): boolean {\n return this.icon.segments.get().length > 0;\n }\n\n hasDebugData(): CollisionBuffers {\n return this.textCollisionBox && this.iconCollisionBox;\n }\n\n hasTextCollisionBoxData(): boolean {\n return this.hasDebugData() && this.textCollisionBox.segments.get().length > 0;\n }\n\n hasIconCollisionBoxData(): boolean {\n return this.hasDebugData() && this.iconCollisionBox.segments.get().length > 0;\n }\n\n addIndicesForPlacedSymbol(iconOrText: SymbolBuffers, placedSymbolIndex: number) {\n const placedSymbol = iconOrText.placedSymbolArray.get(placedSymbolIndex);\n\n const endIndex = placedSymbol.vertexStartIndex + placedSymbol.numGlyphs * 4;\n for (let vertexIndex = placedSymbol.vertexStartIndex; vertexIndex < endIndex; vertexIndex += 4) {\n iconOrText.indexArray.emplaceBack(vertexIndex, vertexIndex + 1, vertexIndex + 2);\n iconOrText.indexArray.emplaceBack(vertexIndex + 1, vertexIndex + 2, vertexIndex + 3);\n }\n }\n\n getSortedSymbolIndexes(angle: number): Array<number> {\n if (this.sortedAngle === angle && this.symbolInstanceIndexes !== undefined) {\n return this.symbolInstanceIndexes;\n }\n const sin = Math.sin(angle);\n const cos = Math.cos(angle);\n const rotatedYs = [];\n const featureIndexes = [];\n const result = [];\n\n for (let i = 0; i < this.symbolInstances.length; ++i) {\n result.push(i);\n const symbolInstance = this.symbolInstances.get(i);\n rotatedYs.push(Math.round(sin * symbolInstance.tileAnchorX + cos * symbolInstance.tileAnchorY) | 0);\n featureIndexes.push(symbolInstance.featureIndex);\n }\n\n result.sort((aIndex, bIndex) => (rotatedYs[aIndex] - rotatedYs[bIndex]) || (featureIndexes[bIndex] - featureIndexes[aIndex]));\n\n return result;\n }\n\n addToSortKeyRanges(symbolInstanceIndex: number, sortKey: number) {\n const last = this.sortKeyRanges[this.sortKeyRanges.length - 1];\n if (last && last.sortKey === sortKey) {\n last.symbolInstanceEnd = symbolInstanceIndex + 1;\n } else {\n this.sortKeyRanges.push({\n sortKey,\n symbolInstanceStart: symbolInstanceIndex,\n symbolInstanceEnd: symbolInstanceIndex + 1\n });\n }\n }\n\n sortFeatures(angle: number) {\n if (!this.sortFeaturesByY) return;\n if (this.sortedAngle === angle) return;\n\n // The current approach to sorting doesn't sort across segments so don't try.\n // Sorting within segments separately seemed not to be worth the complexity.\n if (this.text.segments.get().length > 1 || this.icon.segments.get().length > 1) return;\n\n // If the symbols are allowed to overlap sort them by their vertical screen position.\n // The index array buffer is rewritten to reference the (unchanged) vertices in the\n // sorted order.\n\n // To avoid sorting the actual symbolInstance array we sort an array of indexes.\n this.symbolInstanceIndexes = this.getSortedSymbolIndexes(angle);\n this.sortedAngle = angle;\n\n this.text.indexArray.clear();\n this.icon.indexArray.clear();\n\n this.featureSortOrder = [];\n\n for (const i of this.symbolInstanceIndexes) {\n const symbol = this.symbolInstances.get(i);\n this.featureSortOrder.push(symbol.featureIndex);\n const {\n rightJustifiedTextSymbolIndex: right, centerJustifiedTextSymbolIndex: center,\n leftJustifiedTextSymbolIndex: left, verticalPlacedTextSymbolIndex: vertical,\n placedIconSymbolIndex: icon, verticalPlacedIconSymbolIndex: iconVertical\n } = symbol;\n\n // Only add a given index the first time it shows up, to avoid duplicate\n // opacity entries when multiple justifications share the same glyphs.\n if (right >= 0) this.addIndicesForPlacedSymbol(this.text, right);\n if (center >= 0 && center !== right) this.addIndicesForPlacedSymbol(this.text, center);\n if (left >= 0 && left !== center && left !== right) this.addIndicesForPlacedSymbol(this.text, left);\n\n if (vertical >= 0) this.addIndicesForPlacedSymbol(this.text, vertical);\n if (icon >= 0) this.addIndicesForPlacedSymbol(this.icon, icon);\n if (iconVertical >= 0) this.addIndicesForPlacedSymbol(this.icon, iconVertical);\n }\n\n if (this.text.indexBuffer) this.text.indexBuffer.updateData(this.text.indexArray);\n if (this.icon.indexBuffer) this.icon.indexBuffer.updateData(this.icon.indexArray);\n }\n}\n\nregister(SymbolBucket, 'SymbolBucket', {\n omit: ['layers', 'collisionBoxArray', 'features', 'compareText']\n});\n\n// this constant is based on the size of StructArray indexes used in a symbol\n// bucket--namely, glyphOffsetArrayStart\n// eg the max valid UInt16 is 65,535\n// See https://github.com/mapbox/mapbox-gl-js/issues/2907 for motivation\n// lineStartIndex and textBoxStartIndex could potentially be concerns\n// but we expect there to be many fewer boxes/lines than glyphs\nSymbolBucket.MAX_GLYPHS = 65535;\n\nSymbolBucket.addDynamicAttributes = addDynamicAttributes;\n\nexport default SymbolBucket;\nexport {addDynamicAttributes, updateGlobeVertexNormal};\n","// @flow\n\nimport type Point from '@mapbox/point-geometry';\nimport type {SymbolFeature} from '../data/bucket/symbol_bucket.js';\n\nexport default function (features: Array<SymbolFeature>): Array<SymbolFeature> {\n const leftIndex: {[_: string]: number} = {};\n const rightIndex: {[_: string]: number} = {};\n const mergedFeatures = [];\n let mergedIndex = 0;\n\n function add(k: number) {\n mergedFeatures.push(features[k]);\n mergedIndex++;\n }\n\n function mergeFromRight(leftKey: string, rightKey: string, geom: Array<Array<Point>>) {\n const i = rightIndex[leftKey];\n delete rightIndex[leftKey];\n rightIndex[rightKey] = i;\n\n mergedFeatures[i].geometry[0].pop();\n mergedFeatures[i].geometry[0] = mergedFeatures[i].geometry[0].concat(geom[0]);\n return i;\n }\n\n function mergeFromLeft(leftKey: string, rightKey: string, geom: Array<Array<Point>>) {\n const i = leftIndex[rightKey];\n delete leftIndex[rightKey];\n leftIndex[leftKey] = i;\n\n mergedFeatures[i].geometry[0].shift();\n mergedFeatures[i].geometry[0] = geom[0].concat(mergedFeatures[i].geometry[0]);\n return i;\n }\n\n function getKey(text: string, geom: Array<Array<Point>>, onRight: ?boolean) {\n const point = onRight ? geom[0][geom[0].length - 1] : geom[0][0];\n return `${text}:${point.x}:${point.y}`;\n }\n\n for (let k = 0; k < features.length; k++) {\n const feature = features[k];\n const geom = feature.geometry;\n const text = feature.text ? feature.text.toString() : null;\n\n if (!text) {\n add(k);\n continue;\n }\n\n const leftKey = getKey(text, geom),\n rightKey = getKey(text, geom, true);\n\n if ((leftKey in rightIndex) && (rightKey in leftIndex) && (rightIndex[leftKey] !== leftIndex[rightKey])) {\n // found lines with the same text adjacent to both ends of the current line, merge all three\n const j = mergeFromLeft(leftKey, rightKey, geom);\n const i = mergeFromRight(leftKey, rightKey, mergedFeatures[j].geometry);\n\n delete leftIndex[leftKey];\n delete rightIndex[rightKey];\n\n rightIndex[getKey(text, mergedFeatures[i].geometry, true)] = i;\n mergedFeatures[j].geometry = (null: any);\n\n } else if (leftKey in rightIndex) {\n // found mergeable line adjacent to the start of the current line, merge\n mergeFromRight(leftKey, rightKey, geom);\n\n } else if (rightKey in leftIndex) {\n // found mergeable line adjacent to the end of the current line, merge\n mergeFromLeft(leftKey, rightKey, geom);\n\n } else {\n // no adjacent lines, add as a new item\n add(k);\n leftIndex[leftKey] = mergedIndex - 1;\n rightIndex[rightKey] = mergedIndex - 1;\n }\n }\n\n return mergedFeatures.filter((f) => f.geometry);\n}\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest.js';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n ColorRampProperty\n} from '../properties.js';\n\nimport type Color from '../../style-spec/util/color.js';\n\nimport type Formatted from '../../style-spec/expression/types/formatted.js';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image.js';\n\nimport {\n ColorType\n} from '../../style-spec/expression/types.js';\n\nexport type LayoutProps = {|\n \"symbol-placement\": DataConstantProperty<\"point\" | \"line\" | \"line-center\">,\n \"symbol-spacing\": DataConstantProperty<number>,\n \"symbol-avoid-edges\": DataConstantProperty<boolean>,\n \"symbol-sort-key\": DataDrivenProperty<number>,\n \"symbol-z-order\": DataConstantProperty<\"auto\" | \"viewport-y\" | \"source\">,\n \"icon-allow-overlap\": DataConstantProperty<boolean>,\n \"icon-ignore-placement\": DataConstantProperty<boolean>,\n \"icon-optional\": DataConstantProperty<boolean>,\n \"icon-rotation-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"auto\">,\n \"icon-size\": DataDrivenProperty<number>,\n \"icon-text-fit\": DataConstantProperty<\"none\" | \"width\" | \"height\" | \"both\">,\n \"icon-text-fit-padding\": DataConstantProperty<[number, number, number, number]>,\n \"icon-image\": DataDrivenProperty<ResolvedImage>,\n \"icon-rotate\": DataDrivenProperty<number>,\n \"icon-padding\": DataConstantProperty<number>,\n \"icon-keep-upright\": DataConstantProperty<boolean>,\n \"icon-offset\": DataDrivenProperty<[number, number]>,\n \"icon-anchor\": DataDrivenProperty<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n \"icon-pitch-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"auto\">,\n \"text-pitch-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"auto\">,\n \"text-rotation-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"auto\">,\n \"text-field\": DataDrivenProperty<Formatted>,\n \"text-font\": DataDrivenProperty<Array<string>>,\n \"text-size\": DataDrivenProperty<number>,\n \"text-max-width\": DataDrivenProperty<number>,\n \"text-line-height\": DataDrivenProperty<number>,\n \"text-letter-spacing\": DataDrivenProperty<number>,\n \"text-justify\": DataDrivenProperty<\"auto\" | \"left\" | \"center\" | \"right\">,\n \"text-radial-offset\": DataDrivenProperty<number>,\n \"text-variable-anchor\": DataConstantProperty<Array<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">>,\n \"text-anchor\": DataDrivenProperty<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n \"text-max-angle\": DataConstantProperty<number>,\n \"text-writing-mode\": DataConstantProperty<Array<\"horizontal\" | \"vertical\">>,\n \"text-rotate\": DataDrivenProperty<number>,\n \"text-padding\": DataConstantProperty<number>,\n \"text-keep-upright\": DataConstantProperty<boolean>,\n \"text-transform\": DataDrivenProperty<\"none\" | \"uppercase\" | \"lowercase\">,\n \"text-offset\": DataDrivenProperty<[number, number]>,\n \"text-allow-overlap\": DataConstantProperty<boolean>,\n \"text-ignore-placement\": DataConstantProperty<boolean>,\n \"text-optional\": DataConstantProperty<boolean>,\n|};\n\nconst layout: Properties<LayoutProps> = new Properties({\n \"symbol-placement\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-placement\"]),\n \"symbol-spacing\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-spacing\"]),\n \"symbol-avoid-edges\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-avoid-edges\"]),\n \"symbol-sort-key\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"symbol-sort-key\"]),\n \"symbol-z-order\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-z-order\"]),\n \"icon-allow-overlap\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-allow-overlap\"]),\n \"icon-ignore-placement\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-ignore-placement\"]),\n \"icon-optional\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-optional\"]),\n \"icon-rotation-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-rotation-alignment\"]),\n \"icon-size\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-size\"]),\n \"icon-text-fit\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-text-fit\"]),\n \"icon-text-fit-padding\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-text-fit-padding\"]),\n \"icon-image\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-image\"]),\n \"icon-rotate\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-rotate\"]),\n \"icon-padding\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-padding\"]),\n \"icon-keep-upright\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-keep-upright\"]),\n \"icon-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-offset\"]),\n \"icon-anchor\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-anchor\"]),\n \"icon-pitch-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-pitch-alignment\"]),\n \"text-pitch-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-pitch-alignment\"]),\n \"text-rotation-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-rotation-alignment\"]),\n \"text-field\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-field\"]),\n \"text-font\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-font\"]),\n \"text-size\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-size\"]),\n \"text-max-width\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-max-width\"]),\n \"text-line-height\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-line-height\"]),\n \"text-letter-spacing\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-letter-spacing\"]),\n \"text-justify\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-justify\"]),\n \"text-radial-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-radial-offset\"]),\n \"text-variable-anchor\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-variable-anchor\"]),\n \"text-anchor\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-anchor\"]),\n \"text-max-angle\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-max-angle\"]),\n \"text-writing-mode\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-writing-mode\"]),\n \"text-rotate\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-rotate\"]),\n \"text-padding\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-padding\"]),\n \"text-keep-upright\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-keep-upright\"]),\n \"text-transform\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-transform\"]),\n \"text-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-offset\"]),\n \"text-allow-overlap\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-allow-overlap\"]),\n \"text-ignore-placement\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-ignore-placement\"]),\n \"text-optional\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-optional\"]),\n});\n\nexport type PaintProps = {|\n \"icon-opacity\": DataDrivenProperty<number>,\n \"icon-color\": DataDrivenProperty<Color>,\n \"icon-halo-color\": DataDrivenProperty<Color>,\n \"icon-halo-width\": DataDrivenProperty<number>,\n \"icon-halo-blur\": DataDrivenProperty<number>,\n \"icon-translate\": DataConstantProperty<[number, number]>,\n \"icon-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"text-opacity\": DataDrivenProperty<number>,\n \"text-color\": DataDrivenProperty<Color>,\n \"text-halo-color\": DataDrivenProperty<Color>,\n \"text-halo-width\": DataDrivenProperty<number>,\n \"text-halo-blur\": DataDrivenProperty<number>,\n \"text-translate\": DataConstantProperty<[number, number]>,\n \"text-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"icon-opacity\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-opacity\"]),\n \"icon-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-color\"]),\n \"icon-halo-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-color\"]),\n \"icon-halo-width\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-width\"]),\n \"icon-halo-blur\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-blur\"]),\n \"icon-translate\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"icon-translate\"]),\n \"icon-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"icon-translate-anchor\"]),\n \"text-opacity\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-opacity\"]),\n \"text-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-color\"], { runtimeType: ColorType, getOverride: (o) => o.textColor, hasOverride: (o) => !!o.textColor }),\n \"text-halo-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-color\"]),\n \"text-halo-width\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-width\"]),\n \"text-halo-blur\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-blur\"]),\n \"text-translate\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"text-translate\"]),\n \"text-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"text-translate-anchor\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint, layout }: $Exact<{\n paint: Properties<PaintProps>, layout: Properties<LayoutProps>\n}>);\n","// @flow\n\nimport assert from 'assert';\nimport type {Expression} from '../style-spec/expression/expression.js';\nimport type EvaluationContext from '../style-spec/expression/evaluation_context.js';\nimport type {Type} from '../style-spec/expression/types.js';\nimport type {ZoomConstantExpression} from '../style-spec/expression/index.js';\nimport {NullType} from '../style-spec/expression/types.js';\nimport {PossiblyEvaluatedPropertyValue} from './properties.js';\nimport {register} from '../util/web_worker_transfer.js';\n\n// This is an internal expression class. It is only used in GL JS and\n// has GL JS dependencies which can break the standalone style-spec module\nexport default class FormatSectionOverride<T> implements Expression {\n type: Type;\n defaultValue: PossiblyEvaluatedPropertyValue<T>;\n\n constructor(defaultValue: PossiblyEvaluatedPropertyValue<T>) {\n assert(defaultValue.property.overrides !== undefined);\n this.type = defaultValue.property.overrides ? defaultValue.property.overrides.runtimeType : NullType;\n this.defaultValue = defaultValue;\n }\n\n evaluate(ctx: EvaluationContext): T {\n if (ctx.formattedSection) {\n const overrides = this.defaultValue.property.overrides;\n if (overrides && overrides.hasOverride(ctx.formattedSection)) {\n return overrides.getOverride(ctx.formattedSection);\n }\n }\n\n if (ctx.feature && ctx.featureState) {\n return this.defaultValue.evaluate(ctx.feature, ctx.featureState);\n }\n\n // not sure how to make Flow refine the type properly here — will need investigation\n return ((this.defaultValue.property.specification.default: any): T);\n }\n\n eachChild(fn: (_: Expression) => void) {\n if (!this.defaultValue.isConstant()) {\n const expr: ZoomConstantExpression<'source'> = ((this.defaultValue.value): any);\n fn(expr._styleExpression.expression);\n }\n }\n\n // Cannot be statically evaluated, as the output depends on the evaluation context.\n outputDefined(): boolean {\n return false;\n }\n\n serialize(): null {\n return null;\n }\n}\n\nregister(FormatSectionOverride, 'FormatSectionOverride', {omit: ['defaultValue']});\n","// @flow\n\nimport StyleLayer from '../style_layer.js';\n\nimport assert from 'assert';\nimport SymbolBucket from '../../data/bucket/symbol_bucket.js';\nimport resolveTokens from '../../util/resolve_tokens.js';\nimport properties from './symbol_style_layer_properties.js';\nimport type {FormattedSection} from '../../style-spec/expression/types/formatted.js';\nimport type {FormattedSectionExpression} from '../../style-spec/expression/definitions/format.js';\n\nimport {\n Transitionable,\n Transitioning,\n Layout,\n PossiblyEvaluated,\n PossiblyEvaluatedPropertyValue,\n PropertyValue\n} from '../properties.js';\n\nimport {\n isExpression,\n StyleExpression,\n ZoomConstantExpression,\n ZoomDependentExpression\n} from '../../style-spec/expression/index.js';\n\nimport type {BucketParameters} from '../../data/bucket.js';\nimport type {LayoutProps, PaintProps} from './symbol_style_layer_properties.js';\nimport type EvaluationParameters from '../evaluation_parameters.js';\nimport type {LayerSpecification} from '../../style-spec/types.js';\nimport type {Feature, SourceExpression, CompositeExpression} from '../../style-spec/expression/index.js';\nimport type {Expression} from '../../style-spec/expression/expression.js';\nimport type {CanonicalTileID} from '../../source/tile_id.js';\nimport {FormattedType} from '../../style-spec/expression/types.js';\nimport {typeOf} from '../../style-spec/expression/values.js';\nimport Formatted from '../../style-spec/expression/types/formatted.js';\nimport FormatSectionOverride from '../format_section_override.js';\nimport FormatExpression from '../../style-spec/expression/definitions/format.js';\nimport Literal from '../../style-spec/expression/definitions/literal.js';\nimport ProgramConfiguration from '../../data/program_configuration.js';\n\nclass SymbolStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout<LayoutProps>;\n layout: PossiblyEvaluated<LayoutProps>;\n\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n recalculate(parameters: EvaluationParameters, availableImages: Array<string>) {\n super.recalculate(parameters, availableImages);\n\n if (this.layout.get('icon-rotation-alignment') === 'auto') {\n if (this.layout.get('symbol-placement') !== 'point') {\n this.layout._values['icon-rotation-alignment'] = 'map';\n } else {\n this.layout._values['icon-rotation-alignment'] = 'viewport';\n }\n }\n\n if (this.layout.get('text-rotation-alignment') === 'auto') {\n if (this.layout.get('symbol-placement') !== 'point') {\n this.layout._values['text-rotation-alignment'] = 'map';\n } else {\n this.layout._values['text-rotation-alignment'] = 'viewport';\n }\n }\n\n // If unspecified, `*-pitch-alignment` inherits `*-rotation-alignment`\n if (this.layout.get('text-pitch-alignment') === 'auto') {\n this.layout._values['text-pitch-alignment'] = this.layout.get('text-rotation-alignment');\n }\n if (this.layout.get('icon-pitch-alignment') === 'auto') {\n this.layout._values['icon-pitch-alignment'] = this.layout.get('icon-rotation-alignment');\n }\n\n const writingModes = this.layout.get('text-writing-mode');\n if (writingModes) {\n // remove duplicates, preserving order\n const deduped = [];\n for (const m of writingModes) {\n if (deduped.indexOf(m) < 0) deduped.push(m);\n }\n this.layout._values['text-writing-mode'] = deduped;\n } else if (this.layout.get('symbol-placement') === 'point') {\n // default value for 'point' placement symbols\n this.layout._values['text-writing-mode'] = ['horizontal'];\n } else {\n // default value for 'line' placement symbols\n this.layout._values['text-writing-mode'] = ['horizontal', 'vertical'];\n }\n\n this._setPaintOverrides();\n }\n\n getValueAndResolveTokens(name: any, feature: Feature, canonical: CanonicalTileID, availableImages: Array<string>): string {\n const value = this.layout.get(name).evaluate(feature, {}, canonical, availableImages);\n const unevaluated = this._unevaluatedLayout._values[name];\n if (!unevaluated.isDataDriven() && !isExpression(unevaluated.value) && value) {\n return resolveTokens(feature.properties, value);\n }\n\n return value;\n }\n\n createBucket(parameters: BucketParameters<SymbolStyleLayer>): SymbolBucket {\n return new SymbolBucket(parameters);\n }\n\n // $FlowFixMe[method-unbinding]\n queryRadius(): number {\n return 0;\n }\n\n // $FlowFixMe[method-unbinding]\n queryIntersectsFeature(): boolean {\n assert(false); // Should take a different path in FeatureIndex\n return false;\n }\n\n _setPaintOverrides() {\n for (const overridable of properties.paint.overridableProperties) {\n if (!SymbolStyleLayer.hasPaintOverride(this.layout, overridable)) {\n continue;\n }\n const overriden = this.paint.get(overridable);\n const override = new FormatSectionOverride(overriden);\n const styleExpression = new StyleExpression(override, overriden.property.specification);\n let expression = null;\n if (overriden.value.kind === 'constant' || overriden.value.kind === 'source') {\n // $FlowFixMe[method-unbinding]\n expression = (new ZoomConstantExpression('source', styleExpression): SourceExpression);\n } else {\n // $FlowFixMe[method-unbinding]\n expression = (new ZoomDependentExpression('composite',\n styleExpression,\n overriden.value.zoomStops,\n overriden.value._interpolationType): CompositeExpression);\n }\n // $FlowFixMe[prop-missing]\n this.paint._values[overridable] = new PossiblyEvaluatedPropertyValue(overriden.property,\n expression,\n overriden.parameters);\n }\n }\n\n _handleOverridablePaintPropertyUpdate<T, R>(name: string, oldValue: PropertyValue<T, R>, newValue: PropertyValue<T, R>): boolean {\n if (!this.layout || oldValue.isDataDriven() || newValue.isDataDriven()) {\n return false;\n }\n return SymbolStyleLayer.hasPaintOverride(this.layout, name);\n }\n\n static hasPaintOverride(layout: PossiblyEvaluated<LayoutProps>, propertyName: string): boolean {\n const textField = layout.get('text-field');\n const property = properties.paint.properties[propertyName];\n let hasOverrides = false;\n\n const checkSections = (sections: Array<FormattedSection> | Array<FormattedSectionExpression>) => {\n for (const section of sections) {\n if (property.overrides && property.overrides.hasOverride(section)) {\n hasOverrides = true;\n return;\n }\n }\n };\n\n if (textField.value.kind === 'constant' && textField.value.value instanceof Formatted) {\n checkSections(textField.value.value.sections);\n } else if (textField.value.kind === 'source') {\n\n const checkExpression = (expression: Expression) => {\n if (hasOverrides) return;\n\n if (expression instanceof Literal && typeOf(expression.value) === FormattedType) {\n const formatted: Formatted = ((expression.value): any);\n checkSections(formatted.sections);\n } else if (expression instanceof FormatExpression) {\n checkSections(expression.sections);\n } else {\n expression.eachChild(checkExpression);\n }\n };\n\n const expr: ZoomConstantExpression<'source'> = ((textField.value): any);\n if (expr._styleExpression) {\n checkExpression(expr._styleExpression.expression);\n }\n }\n\n return hasOverrides;\n }\n\n getProgramConfiguration(zoom: number): ProgramConfiguration {\n return new ProgramConfiguration(this, zoom);\n }\n}\n\nexport default SymbolStyleLayer;\n","// @flow\nexport default resolveTokens;\n\n/**\n * Replace tokens in a string template with values in an object\n *\n * @param properties a key/value relationship between tokens and replacements\n * @param text the template string\n * @returns the template with tokens replaced\n * @private\n */\nfunction resolveTokens(properties: {+[string]: mixed}, text: string): string {\n return text.replace(/{([^{}]+)}/g, (match, key: string) => {\n return key in properties ? String(properties[key]) : '';\n });\n}\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest.js';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n ColorRampProperty\n} from '../properties.js';\n\nimport type Color from '../../style-spec/util/color.js';\n\nimport type Formatted from '../../style-spec/expression/types/formatted.js';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image.js';\n\n\nexport type PaintProps = {|\n \"background-color\": DataConstantProperty<Color>,\n \"background-pattern\": DataConstantProperty<?ResolvedImage>,\n \"background-opacity\": DataConstantProperty<number>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"background-color\": new DataConstantProperty(styleSpec[\"paint_background\"][\"background-color\"]),\n \"background-pattern\": new DataConstantProperty(styleSpec[\"paint_background\"][\"background-pattern\"]),\n \"background-opacity\": new DataConstantProperty(styleSpec[\"paint_background\"][\"background-opacity\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint }: $Exact<{\n paint: Properties<PaintProps>\n}>);\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest.js';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n ColorRampProperty\n} from '../properties.js';\n\nimport type Color from '../../style-spec/util/color.js';\n\nimport type Formatted from '../../style-spec/expression/types/formatted.js';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image.js';\n\n\nexport type PaintProps = {|\n \"raster-opacity\": DataConstantProperty<number>,\n \"raster-hue-rotate\": DataConstantProperty<number>,\n \"raster-brightness-min\": DataConstantProperty<number>,\n \"raster-brightness-max\": DataConstantProperty<number>,\n \"raster-saturation\": DataConstantProperty<number>,\n \"raster-contrast\": DataConstantProperty<number>,\n \"raster-resampling\": DataConstantProperty<\"linear\" | \"nearest\">,\n \"raster-fade-duration\": DataConstantProperty<number>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"raster-opacity\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-opacity\"]),\n \"raster-hue-rotate\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-hue-rotate\"]),\n \"raster-brightness-min\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-brightness-min\"]),\n \"raster-brightness-max\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-brightness-max\"]),\n \"raster-saturation\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-saturation\"]),\n \"raster-contrast\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-contrast\"]),\n \"raster-resampling\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-resampling\"]),\n \"raster-fade-duration\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-fade-duration\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint }: $Exact<{\n paint: Properties<PaintProps>\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer.js';\nimport MercatorCoordinate from '../../geo/mercator_coordinate.js';\nimport type Map from '../../ui/map.js';\nimport assert from 'assert';\nimport type {ValidationErrors} from '../validate_style.js';\nimport type {ProjectionSpecification} from '../../style-spec/types.js';\n\ntype CustomRenderMethod = (gl: WebGLRenderingContext, matrix: Array<number>, projection: ?ProjectionSpecification, projectionToMercatorMatrix: ?Array<number>, projectionToMercatorTransition: ?number, centerInMercator: ?Array<number>, pixelsPerMeterRatio: ?number) => void;\n\n/**\n * Interface for custom style layers. This is a specification for\n * implementers to model: it is not an exported method or class.\n *\n * Custom layers allow a user to render directly into the map's GL context using the map's camera.\n * These layers can be added between any regular layers using {@link Map#addLayer}.\n *\n * Custom layers must have a unique `id` and must have the `type` of `\"custom\"`.\n * They must implement `render` and may implement `prerender`, `onAdd` and `onRemove`.\n * They can trigger rendering using {@link Map#triggerRepaint}\n * and they should appropriately handle {@link Map.event:webglcontextlost} and\n * {@link Map.event:webglcontextrestored}.\n *\n * The `renderingMode` property controls whether the layer is treated as a `\"2d\"` or `\"3d\"` map layer. Use:\n * - `\"renderingMode\": \"3d\"` to use the depth buffer and share it with other layers\n * - `\"renderingMode\": \"2d\"` to add a layer with no depth. If you need to use the depth buffer for a `\"2d\"` layer you must use an offscreen\n * framebuffer and {@link CustomLayerInterface#prerender}.\n *\n * @interface CustomLayerInterface\n * @property {string} id A unique layer id.\n * @property {string} type The layer's type. Must be `\"custom\"`.\n * @property {string} renderingMode Either `\"2d\"` or `\"3d\"`. Defaults to `\"2d\"`.\n * @example\n * // Custom layer implemented as ES6 class\n * class NullIslandLayer {\n * constructor() {\n * this.id = 'null-island';\n * this.type = 'custom';\n * this.renderingMode = '2d';\n * }\n *\n * onAdd(map, gl) {\n * const vertexSource = `\n * uniform mat4 u_matrix;\n * void main() {\n * gl_Position = u_matrix * vec4(0.5, 0.5, 0.0, 1.0);\n * gl_PointSize = 20.0;\n * }`;\n *\n * const fragmentSource = `\n * void main() {\n * gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n * }`;\n *\n * const vertexShader = gl.createShader(gl.VERTEX_SHADER);\n * gl.shaderSource(vertexShader, vertexSource);\n * gl.compileShader(vertexShader);\n * const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n * gl.shaderSource(fragmentShader, fragmentSource);\n * gl.compileShader(fragmentShader);\n *\n * this.program = gl.createProgram();\n * gl.attachShader(this.program, vertexShader);\n * gl.attachShader(this.program, fragmentShader);\n * gl.linkProgram(this.program);\n * }\n *\n * render(gl, matrix) {\n * gl.useProgram(this.program);\n * gl.uniformMatrix4fv(gl.getUniformLocation(this.program, \"u_matrix\"), false, matrix);\n * gl.drawArrays(gl.POINTS, 0, 1);\n * }\n * }\n *\n * map.on('load', () => {\n * map.addLayer(new NullIslandLayer());\n * });\n * @see [Example: Add a custom style layer](https://docs.mapbox.com/mapbox-gl-js/example/custom-style-layer/)\n * @see [Example: Add a 3D model](https://docs.mapbox.com/mapbox-gl-js/example/add-3d-model/)\n */\n\n/**\n * Optional method called when the layer has been added to the Map with {@link Map#addLayer}. This\n * gives the layer a chance to initialize gl resources and register event listeners.\n *\n * @function\n * @memberof CustomLayerInterface\n * @instance\n * @name onAdd\n * @param {Map} map The Map this custom layer was just added to.\n * @param {WebGLRenderingContext} gl The gl context for the map.\n */\n\n/**\n * Optional method called when the layer has been removed from the Map with {@link Map#removeLayer}. This\n * gives the layer a chance to clean up gl resources and event listeners.\n *\n * @function\n * @memberof CustomLayerInterface\n * @instance\n * @name onRemove\n * @param {Map} map The Map this custom layer was just added to.\n * @param {WebGLRenderingContext} gl The gl context for the map.\n */\n\n/**\n * Optional method called during a render frame to allow a layer to prepare resources or render into a texture.\n *\n * The layer cannot make any assumptions about the current GL state and must bind a framebuffer before rendering.\n *\n * @function\n * @memberof CustomLayerInterface\n * @instance\n * @name prerender\n * @param {WebGLRenderingContext} gl The map's gl context.\n * @param {Array<number>} matrix The map's camera matrix. It projects spherical mercator\n * coordinates to gl coordinates. The mercator coordinate `[0, 0]` represents the\n * top left corner of the mercator world and `[1, 1]` represents the bottom right corner. When\n * the `renderingMode` is `\"3d\"`, the z coordinate is conformal. A box with identical x, y, and z\n * lengths in mercator units would be rendered as a cube. {@link MercatorCoordinate}.fromLngLat\n * can be used to project a `LngLat` to a mercator coordinate.\n */\n\n/**\n * Called during a render frame allowing the layer to draw into the GL context.\n *\n * The layer can assume blending and depth state is set to allow the layer to properly\n * blend and clip other layers. The layer cannot make any other assumptions about the\n * current GL state.\n *\n * If the layer needs to render to a texture, it should implement the `prerender` method\n * to do this and only use the `render` method for drawing directly into the main framebuffer.\n *\n * The blend function is set to `gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`. This expects\n * colors to be provided in premultiplied alpha form where the `r`, `g` and `b` values are already\n * multiplied by the `a` value. If you are unable to provide colors in premultiplied form you\n * may want to change the blend function to\n * `gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`.\n *\n * @function\n * @memberof CustomLayerInterface\n * @instance\n * @name render\n * @param {WebGLRenderingContext} gl The map's gl context.\n * @param {Array<number>} matrix The map's camera matrix. It projects spherical mercator\n * coordinates to gl coordinates. The spherical mercator coordinate `[0, 0]` represents the\n * top left corner of the mercator world and `[1, 1]` represents the bottom right corner. When\n * the `renderingMode` is `\"3d\"`, the z coordinate is conformal. A box with identical x, y, and z\n * lengths in mercator units would be rendered as a cube. {@link MercatorCoordinate}.fromLngLat\n * can be used to project a `LngLat` to a mercator coordinate.\n */\nexport type CustomLayerInterface = {\n id: string,\n type: \"custom\",\n renderingMode: \"2d\" | \"3d\",\n render: CustomRenderMethod,\n prerender: ?CustomRenderMethod,\n renderToTile: ?(gl: WebGLRenderingContext, tileId: MercatorCoordinate) => void,\n shouldRerenderTiles: ?() => boolean,\n onAdd: ?(map: Map, gl: WebGLRenderingContext) => void,\n onRemove: ?(map: Map, gl: WebGLRenderingContext) => void\n}\n\nexport function validateCustomStyleLayer(layerObject: CustomLayerInterface): ValidationErrors {\n const errors = [];\n const id = layerObject.id;\n\n if (id === undefined) {\n errors.push({\n message: `layers.${id}: missing required property \"id\"`\n });\n }\n\n if (layerObject.render === undefined) {\n errors.push({\n message: `layers.${id}: missing required method \"render\"`\n });\n }\n\n if (layerObject.renderingMode &&\n layerObject.renderingMode !== '2d' &&\n layerObject.renderingMode !== '3d') {\n errors.push({\n message: `layers.${id}: property \"renderingMode\" must be either \"2d\" or \"3d\"`\n });\n }\n\n return errors;\n}\n\nclass CustomStyleLayer extends StyleLayer {\n\n implementation: CustomLayerInterface;\n\n constructor(implementation: CustomLayerInterface) {\n super(implementation, {});\n this.implementation = implementation;\n }\n\n is3D(): boolean {\n return this.implementation.renderingMode === '3d';\n }\n\n hasOffscreenPass(): boolean {\n return this.implementation.prerender !== undefined;\n }\n\n isLayerDraped(): boolean {\n return this.implementation.renderToTile !== undefined;\n }\n\n shouldRedrape(): boolean {\n return !!this.implementation.shouldRerenderTiles && this.implementation.shouldRerenderTiles();\n }\n\n recalculate() {}\n updateTransitions() {}\n hasTransition(): boolean {\n return false;\n }\n\n // $FlowFixMe[incompatible-extend] - CustomStyleLayer is not serializable\n serialize() {\n assert(false, \"Custom layers cannot be serialized\");\n }\n\n // $FlowFixMe[method-unbinding]\n onAdd(map: Map) {\n if (this.implementation.onAdd) {\n this.implementation.onAdd(map, map.painter.context.gl);\n }\n }\n\n // $FlowFixMe[method-unbinding]\n onRemove(map: Map) {\n if (this.implementation.onRemove) {\n this.implementation.onRemove(map, map.painter.context.gl);\n }\n }\n}\n\nexport default CustomStyleLayer;\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest.js';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n ColorRampProperty\n} from '../properties.js';\n\nimport type Color from '../../style-spec/util/color.js';\n\nimport type Formatted from '../../style-spec/expression/types/formatted.js';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image.js';\n\n\nexport type PaintProps = {|\n \"sky-type\": DataConstantProperty<\"gradient\" | \"atmosphere\">,\n \"sky-atmosphere-sun\": DataConstantProperty<[number, number]>,\n \"sky-atmosphere-sun-intensity\": DataConstantProperty<number>,\n \"sky-gradient-center\": DataConstantProperty<[number, number]>,\n \"sky-gradient-radius\": DataConstantProperty<number>,\n \"sky-gradient\": ColorRampProperty,\n \"sky-atmosphere-halo-color\": DataConstantProperty<Color>,\n \"sky-atmosphere-color\": DataConstantProperty<Color>,\n \"sky-opacity\": DataConstantProperty<number>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"sky-type\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-type\"]),\n \"sky-atmosphere-sun\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-atmosphere-sun\"]),\n \"sky-atmosphere-sun-intensity\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-atmosphere-sun-intensity\"]),\n \"sky-gradient-center\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-gradient-center\"]),\n \"sky-gradient-radius\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-gradient-radius\"]),\n \"sky-gradient\": new ColorRampProperty(styleSpec[\"paint_sky\"][\"sky-gradient\"]),\n \"sky-atmosphere-halo-color\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-atmosphere-halo-color\"]),\n \"sky-atmosphere-color\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-atmosphere-color\"]),\n \"sky-opacity\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-opacity\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint }: $Exact<{\n paint: Properties<PaintProps>\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer.js';\nimport properties from './sky_style_layer_properties.js';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties.js';\nimport {renderColorRamp} from '../../util/color_ramp.js';\nimport type {PaintProps} from './sky_style_layer_properties.js';\nimport type Texture from '../../render/texture.js';\nimport type Painter from '../../render/painter.js';\nimport type {LayerSpecification} from '../../style-spec/types.js';\nimport type Framebuffer from '../../gl/framebuffer.js';\nimport type {RGBAImage} from '../../util/image.js';\nimport type SkyboxGeometry from '../../render/skybox_geometry.js';\nimport type {LightPosition} from '../light.js';\nimport {warnOnce, degToRad} from '../../util/util.js';\nimport {vec3, quat} from 'gl-matrix';\nimport assert from 'assert';\n\nfunction getCelestialDirection(azimuth: number, altitude: number, leftHanded: boolean) {\n const up = [0, 0, 1];\n const rotation = quat.identity([]);\n\n quat.rotateY(rotation, rotation, leftHanded ? -degToRad(azimuth) + Math.PI : degToRad(azimuth));\n quat.rotateX(rotation, rotation, -degToRad(altitude));\n vec3.transformQuat(up, up, rotation);\n\n return vec3.normalize(up, up);\n}\n\nclass SkyLayer extends StyleLayer {\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n _lightPosition: LightPosition;\n\n skyboxFbo: ?Framebuffer;\n skyboxTexture: ?WebGLTexture;\n _skyboxInvalidated: ?boolean;\n\n colorRamp: RGBAImage;\n colorRampTexture: ?Texture;\n\n skyboxGeometry: SkyboxGeometry;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n this._updateColorRamp();\n }\n\n _handleSpecialPaintPropertyUpdate(name: string) {\n if (name === 'sky-gradient') {\n this._updateColorRamp();\n } else if (name === 'sky-atmosphere-sun' ||\n name === 'sky-atmosphere-halo-color' ||\n name === 'sky-atmosphere-color' ||\n name === 'sky-atmosphere-sun-intensity') {\n this._skyboxInvalidated = true;\n }\n }\n\n _updateColorRamp() {\n const expression = this._transitionablePaint._values['sky-gradient'].value.expression;\n this.colorRamp = renderColorRamp({\n expression,\n evaluationKey: 'skyRadialProgress'\n });\n if (this.colorRampTexture) {\n this.colorRampTexture.destroy();\n this.colorRampTexture = null;\n }\n }\n\n needsSkyboxCapture(painter: Painter): boolean {\n if (!!this._skyboxInvalidated || !this.skyboxTexture || !this.skyboxGeometry) {\n return true;\n }\n if (!this.paint.get('sky-atmosphere-sun')) {\n const lightPosition = painter.style.light.properties.get('position');\n return this._lightPosition.azimuthal !== lightPosition.azimuthal ||\n this._lightPosition.polar !== lightPosition.polar;\n }\n return false;\n }\n\n getCenter(painter: Painter, leftHanded: boolean): [number, number, number] {\n const type = this.paint.get('sky-type');\n if (type === 'atmosphere') {\n const sunPosition = this.paint.get('sky-atmosphere-sun');\n const useLightPosition = !sunPosition;\n const light = painter.style.light;\n const lightPosition = light.properties.get('position');\n\n if (useLightPosition && light.properties.get('anchor') === 'viewport') {\n warnOnce('The sun direction is attached to a light with viewport anchor, lighting may behave unexpectedly.');\n }\n\n return useLightPosition ?\n getCelestialDirection(lightPosition.azimuthal, -lightPosition.polar + 90, leftHanded) :\n getCelestialDirection(sunPosition[0], -sunPosition[1] + 90, leftHanded);\n }\n assert(type === 'gradient');\n const direction = this.paint.get('sky-gradient-center');\n return getCelestialDirection(direction[0], -direction[1] + 90, leftHanded);\n }\n\n is3D(): boolean {\n return false;\n }\n\n isSky(): boolean {\n return true;\n }\n\n markSkyboxValid(painter: Painter) {\n this._skyboxInvalidated = false;\n this._lightPosition = painter.style.light.properties.get('position');\n }\n\n hasOffscreenPass(): boolean {\n return true;\n }\n\n getProgramIds(): string[] | null {\n const type = this.paint.get('sky-type');\n if (type === 'atmosphere') {\n return ['skyboxCapture', 'skybox'];\n } else if (type === 'gradient') {\n return ['skyboxGradient'];\n }\n return null;\n }\n}\n\nexport default SkyLayer;\n","// @flow\n\nimport type StyleLayer from './style_layer.js';\nimport circle from './style_layer/circle_style_layer.js';\nimport heatmap from './style_layer/heatmap_style_layer.js';\nimport hillshade from './style_layer/hillshade_style_layer.js';\nimport fill from './style_layer/fill_style_layer.js';\nimport fillExtrusion from './style_layer/fill_extrusion_style_layer.js';\nimport line from './style_layer/line_style_layer.js';\nimport symbol from './style_layer/symbol_style_layer.js';\nimport background from './style_layer/background_style_layer.js';\nimport raster from './style_layer/raster_style_layer.js';\nimport CustomStyleLayer from './style_layer/custom_style_layer.js';\nimport sky from './style_layer/sky_style_layer.js';\nimport type {CustomLayerInterface} from './style_layer/custom_style_layer.js';\n\nimport type {LayerSpecification} from '../style-spec/types.js';\n\nconst subclasses = {\n circle,\n heatmap,\n hillshade,\n fill,\n 'fill-extrusion': fillExtrusion,\n line,\n symbol,\n background,\n raster,\n sky\n};\n\nexport default function createStyleLayer(layer: LayerSpecification | CustomLayerInterface): StyleLayer | CustomStyleLayer {\n if (layer.type === 'custom') {\n return new CustomStyleLayer(layer);\n } else {\n return new subclasses[layer.type](layer);\n }\n}\n","// @flow\n\nimport StyleLayer from '../style_layer.js';\n\nimport HeatmapBucket from '../../data/bucket/heatmap_bucket.js';\nimport {RGBAImage} from '../../util/image.js';\nimport properties from './heatmap_style_layer_properties.js';\nimport {renderColorRamp} from '../../util/color_ramp.js';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties.js';\nimport {queryIntersectsCircle} from './circle_style_layer.js';\nimport {getMaximumPaintValue} from '../query_utils.js';\nimport Point from '@mapbox/point-geometry';\n\nimport type {Bucket, BucketParameters} from '../../data/bucket.js';\nimport type Texture from '../../render/texture.js';\nimport type Framebuffer from '../../gl/framebuffer.js';\nimport type {PaintProps} from './heatmap_style_layer_properties.js';\nimport type {LayerSpecification} from '../../style-spec/types.js';\nimport ProgramConfiguration from '../../data/program_configuration.js';\nimport type {TilespaceQueryGeometry} from '../query_geometry.js';\nimport type {DEMSampler} from '../../terrain/elevation.js';\nimport type {FeatureState} from '../../style-spec/expression/index.js';\nimport type Transform from '../../geo/transform.js';\nimport type CircleBucket from '../../data/bucket/circle_bucket.js';\nimport type {IVectorTileFeature} from '@mapbox/vector-tile';\n\nclass HeatmapStyleLayer extends StyleLayer {\n\n heatmapFbo: ?Framebuffer;\n colorRamp: RGBAImage;\n colorRampTexture: ?Texture;\n\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n createBucket(parameters: BucketParameters<HeatmapStyleLayer>): HeatmapBucket {\n return new HeatmapBucket(parameters);\n }\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n\n // make sure color ramp texture is generated for default heatmap color too\n this._updateColorRamp();\n }\n\n _handleSpecialPaintPropertyUpdate(name: string) {\n if (name === 'heatmap-color') {\n this._updateColorRamp();\n }\n }\n\n _updateColorRamp() {\n const expression = this._transitionablePaint._values['heatmap-color'].value.expression;\n this.colorRamp = renderColorRamp({\n expression,\n evaluationKey: 'heatmapDensity',\n image: this.colorRamp\n });\n this.colorRampTexture = null;\n }\n\n resize() {\n if (this.heatmapFbo) {\n this.heatmapFbo.destroy();\n this.heatmapFbo = null;\n }\n }\n\n // $FlowFixMe[method-unbinding]\n queryRadius(bucket: Bucket): number {\n return getMaximumPaintValue('heatmap-radius', this, ((bucket: any): CircleBucket<*>));\n }\n\n // $FlowFixMe[method-unbinding]\n queryIntersectsFeature(queryGeometry: TilespaceQueryGeometry,\n feature: IVectorTileFeature,\n featureState: FeatureState,\n geometry: Array<Array<Point>>,\n zoom: number,\n transform: Transform,\n pixelPosMatrix: Float32Array,\n elevationHelper: ?DEMSampler): boolean {\n\n const size = this.paint.get('heatmap-radius').evaluate(feature, featureState);\n return queryIntersectsCircle(\n queryGeometry, geometry, transform, pixelPosMatrix, elevationHelper,\n true, true, new Point(0, 0), size);\n }\n\n hasOffscreenPass(): boolean {\n return this.paint.get('heatmap-opacity') !== 0 && this.visibility !== 'none';\n }\n\n getProgramIds(): Array<string> {\n return ['heatmap', 'heatmapTexture'];\n }\n\n getProgramConfiguration(zoom: number): ProgramConfiguration {\n return new ProgramConfiguration(this, zoom);\n }\n}\n\nexport default HeatmapStyleLayer;\n","// @flow\n\nimport StyleLayer from '../style_layer.js';\n\nimport properties from './hillshade_style_layer_properties.js';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties.js';\n\nimport type {PaintProps} from './hillshade_style_layer_properties.js';\nimport type {LayerSpecification} from '../../style-spec/types.js';\n\nclass HillshadeStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n hasOffscreenPass(): boolean {\n return this.paint.get('hillshade-exaggeration') !== 0 && this.visibility !== 'none';\n }\n\n getProgramIds(): Array<string> {\n return ['hillshade', 'hillshadePrepare'];\n }\n}\n\nexport default HillshadeStyleLayer;\n","// @flow\n\nimport StyleLayer from '../style_layer.js';\n\nimport FillBucket from '../../data/bucket/fill_bucket.js';\nimport {polygonIntersectsMultiPolygon} from '../../util/intersection_tests.js';\nimport {translateDistance, translate} from '../query_utils.js';\nimport properties from './fill_style_layer_properties.js';\nimport {Transitionable, Transitioning, Layout, PossiblyEvaluated} from '../properties.js';\nimport ProgramConfiguration from '../../data/program_configuration.js';\n\nimport type {FeatureState} from '../../style-spec/expression/index.js';\nimport type {BucketParameters} from '../../data/bucket.js';\nimport type Point from '@mapbox/point-geometry';\nimport type {LayoutProps, PaintProps} from './fill_style_layer_properties.js';\nimport type EvaluationParameters from '../evaluation_parameters.js';\nimport type Transform from '../../geo/transform.js';\nimport type {LayerSpecification} from '../../style-spec/types.js';\nimport type {TilespaceQueryGeometry} from '../query_geometry.js';\nimport type {IVectorTileFeature} from '@mapbox/vector-tile';\n\nclass FillStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout<LayoutProps>;\n layout: PossiblyEvaluated<LayoutProps>;\n\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n getProgramIds(): string[] {\n const pattern = this.paint.get('fill-pattern');\n const image = pattern && pattern.constantOr((1: any));\n\n const ids = [image ? 'fillPattern' : 'fill'];\n\n if (this.paint.get('fill-antialias')) {\n ids.push(image && !this.getPaintProperty('fill-outline-color') ? 'fillOutlinePattern' : 'fillOutline');\n }\n\n return ids;\n }\n\n getProgramConfiguration(zoom: number): ProgramConfiguration {\n return new ProgramConfiguration(this, zoom);\n }\n\n recalculate(parameters: EvaluationParameters, availableImages: Array<string>) {\n super.recalculate(parameters, availableImages);\n\n const outlineColor = this.paint._values['fill-outline-color'];\n if (outlineColor.value.kind === 'constant' && outlineColor.value.value === undefined) {\n this.paint._values['fill-outline-color'] = this.paint._values['fill-color'];\n }\n }\n\n createBucket(parameters: BucketParameters<FillStyleLayer>): FillBucket {\n return new FillBucket(parameters);\n }\n\n // $FlowFixMe[method-unbinding]\n queryRadius(): number {\n return translateDistance(this.paint.get('fill-translate'));\n }\n\n // $FlowFixMe[method-unbinding]\n queryIntersectsFeature(queryGeometry: TilespaceQueryGeometry,\n feature: IVectorTileFeature,\n featureState: FeatureState,\n geometry: Array<Array<Point>>,\n zoom: number,\n transform: Transform): boolean {\n if (queryGeometry.queryGeometry.isAboveHorizon) return false;\n\n const translatedPolygon = translate(queryGeometry.tilespaceGeometry,\n this.paint.get('fill-translate'),\n this.paint.get('fill-translate-anchor'),\n transform.angle, queryGeometry.pixelToTileUnitsFactor);\n return polygonIntersectsMultiPolygon(translatedPolygon, geometry);\n }\n\n isTileClipped(): boolean {\n return true;\n }\n}\n\nexport default FillStyleLayer;\n","// @flow\n\nimport StyleLayer from '../style_layer.js';\n\nimport properties from './background_style_layer_properties.js';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties.js';\n\nimport type {PaintProps} from './background_style_layer_properties.js';\nimport type {LayerSpecification} from '../../style-spec/types.js';\n\nclass BackgroundStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n getProgramIds(): Array<string> {\n const image = this.paint.get('background-pattern');\n return [image ? 'backgroundPattern' : 'background'];\n }\n}\n\nexport default BackgroundStyleLayer;\n","// @flow\n\nimport StyleLayer from '../style_layer.js';\n\nimport properties from './raster_style_layer_properties.js';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties.js';\n\nimport type {PaintProps} from './raster_style_layer_properties.js';\nimport type {LayerSpecification} from '../../style-spec/types.js';\n\nclass RasterStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n getProgramIds(): Array<string> {\n return ['raster'];\n }\n}\n\nexport default RasterStyleLayer;\n","// @flow\nexport default ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout'];\n","// @flow\n\nimport type {LayerSpecification} from './types.js';\n\nimport refProperties from './util/ref_properties.js';\n\nfunction stringify(obj: any) {\n if (typeof obj === 'number' || typeof obj === 'boolean' || typeof obj === 'string' || obj === undefined || obj === null)\n return JSON.stringify(obj);\n\n if (Array.isArray(obj)) {\n let str = '[';\n for (const val of obj) {\n str += `${stringify(val)},`;\n }\n return `${str}]`;\n }\n\n let str = '{';\n for (const key of Object.keys(obj).sort()) {\n str += `${key}:${stringify((obj: any)[key])},`;\n }\n return `${str}}`;\n}\n\nfunction getKey(layer: LayerSpecification) {\n let key = '';\n for (const k of refProperties) {\n key += `/${stringify((layer: any)[k])}`;\n }\n return key;\n}\n\n/**\n * Given an array of layers, return an array of arrays of layers where all\n * layers in each group have identical layout-affecting properties. These\n * are the properties that were formerly used by explicit `ref` mechanism\n * for layers: 'type', 'source', 'source-layer', 'minzoom', 'maxzoom',\n * 'filter', and 'layout'.\n *\n * The input is not modified. The output layers are references to the\n * input layers.\n *\n * @private\n * @param {Array<Layer>} layers\n * @param {Object} [cachedKeys] - an object to keep already calculated keys.\n * @returns {Array<Array<Layer>>}\n */\nexport default function groupByLayout(layers: Array<LayerSpecification>, cachedKeys: {[id: string]: string}): Array<Array<LayerSpecification>> {\n const groups = {};\n\n for (let i = 0; i < layers.length; i++) {\n\n const k = (cachedKeys && cachedKeys[layers[i].id]) || getKey(layers[i]);\n // update the cache if there is one\n if (cachedKeys)\n cachedKeys[layers[i].id] = k;\n\n let group = groups[k];\n if (!group) {\n group = groups[k] = [];\n }\n group.push(layers[i]);\n }\n\n const result = [];\n\n for (const k in groups) {\n result.push(groups[k]);\n }\n\n return result;\n}\n","// @flow\n\nimport createStyleLayer from './create_style_layer.js';\n\nimport {values} from '../util/util.js';\nimport groupByLayout from '../style-spec/group_by_layout.js';\n\nimport type {TypedStyleLayer} from './style_layer/typed_style_layer.js';\nimport type {LayerSpecification} from '../style-spec/types.js';\n\nexport type LayerConfigs = {[_: string]: LayerSpecification };\nexport type Family<Layer: TypedStyleLayer> = Array<Layer>;\n\nclass StyleLayerIndex {\n familiesBySource: { [source: string]: { [sourceLayer: string]: Array<Family<TypedStyleLayer>> } };\n keyCache: { [source: string]: string };\n\n _layerConfigs: LayerConfigs;\n _layers: {[_: string]: TypedStyleLayer };\n\n constructor(layerConfigs: ?Array<LayerSpecification>) {\n this.keyCache = {};\n if (layerConfigs) {\n this.replace(layerConfigs);\n }\n }\n\n replace(layerConfigs: Array<LayerSpecification>) {\n this._layerConfigs = {};\n this._layers = {};\n this.update(layerConfigs, []);\n }\n\n update(layerConfigs: Array<LayerSpecification>, removedIds: Array<string>) {\n for (const layerConfig of layerConfigs) {\n this._layerConfigs[layerConfig.id] = layerConfig;\n\n const layer = this._layers[layerConfig.id] = ((createStyleLayer(layerConfig): any): TypedStyleLayer);\n layer.compileFilter();\n if (this.keyCache[layerConfig.id])\n delete this.keyCache[layerConfig.id];\n }\n for (const id of removedIds) {\n delete this.keyCache[id];\n delete this._layerConfigs[id];\n delete this._layers[id];\n }\n\n this.familiesBySource = {};\n\n const groups = groupByLayout(values(this._layerConfigs), this.keyCache);\n\n for (const layerConfigs of groups) {\n const layers = layerConfigs.map((layerConfig) => this._layers[layerConfig.id]);\n\n const layer = layers[0];\n if (layer.visibility === 'none') {\n continue;\n }\n\n const sourceId = layer.source || '';\n let sourceGroup = this.familiesBySource[sourceId];\n if (!sourceGroup) {\n sourceGroup = this.familiesBySource[sourceId] = {};\n }\n\n const sourceLayerId = layer.sourceLayer || '_geojsonTileLayer';\n let sourceLayerFamilies = sourceGroup[sourceLayerId];\n if (!sourceLayerFamilies) {\n sourceLayerFamilies = sourceGroup[sourceLayerId] = [];\n }\n\n sourceLayerFamilies.push(layers);\n }\n }\n}\n\nexport default StyleLayerIndex;\n","// @flow strict\n\nimport assert from 'assert';\n\nclass DictionaryCoder {\n _stringToNumber: {[_: string]: number };\n _numberToString: Array<string>;\n\n constructor(strings: Array<string>) {\n this._stringToNumber = {};\n this._numberToString = [];\n for (let i = 0; i < strings.length; i++) {\n const string = strings[i];\n this._stringToNumber[string] = i;\n this._numberToString[i] = string;\n }\n }\n\n encode(string: string): number {\n assert(string in this._stringToNumber);\n return this._stringToNumber[string];\n }\n\n decode(n: number): string {\n assert(n < this._numberToString.length);\n return this._numberToString[n];\n }\n}\n\nexport default DictionaryCoder;\n","// @flow\nimport type {LayerSpecification, SourceSpecification} from '../style-spec/types.js';\nimport type {GeoJSONGeometry, GeoJSONFeature} from '@mapbox/geojson-types';\nimport type {IVectorTileFeature} from '@mapbox/vector-tile';\n\n// we augment GeoJSON with custom properties in query*Features results\nexport interface QueryFeature extends GeoJSONFeature {\n layer?: ?LayerSpecification;\n source?: ?SourceSpecification | ?mixed;\n sourceLayer?: ?string | ?mixed;\n state: ?mixed;\n [key: string]: mixed;\n}\n\nconst customProps = ['tile', 'layer', 'source', 'sourceLayer', 'state'];\n\nclass Feature {\n type: 'Feature';\n _geometry: ?GeoJSONGeometry;\n properties: ?{};\n id: number | string | void;\n _vectorTileFeature: IVectorTileFeature;\n _x: number;\n _y: number;\n _z: number;\n\n tile: ?mixed;\n layer: ?LayerSpecification;\n source: ?mixed;\n sourceLayer: ?mixed;\n state: ?mixed;\n\n constructor(vectorTileFeature: IVectorTileFeature, z: number, x: number, y: number, id: string | number | void) {\n this.type = 'Feature';\n\n this._vectorTileFeature = vectorTileFeature;\n this._z = z;\n this._x = x;\n this._y = y;\n\n this.properties = vectorTileFeature.properties;\n this.id = id;\n }\n\n get geometry(): ?GeoJSONGeometry {\n if (this._geometry === undefined) {\n this._geometry = this._vectorTileFeature.toGeoJSON(this._x, this._y, this._z).geometry;\n }\n return this._geometry;\n }\n\n set geometry(g: ?GeoJSONGeometry) {\n this._geometry = g;\n }\n\n toJSON(): QueryFeature {\n const json: QueryFeature = {\n type: 'Feature',\n state: undefined,\n geometry: this.geometry,\n properties: this.properties\n };\n if (this.id !== undefined) json.id = this.id;\n for (const key of customProps) {\n // Flow doesn't support indexed access for classes https://github.com/facebook/flow/issues/1323\n if ((this: any)[key] !== undefined) json[key] = (this: any)[key];\n }\n return json;\n }\n}\n\nexport default Feature;\n","// @flow\n\nimport window from '../util/window.js';\n\nimport type Context from '../gl/context.js';\nimport type {RGBAImage, AlphaImage} from '../util/image.js';\n\nexport type TextureFormat =\n | $PropertyType<WebGLRenderingContext, 'RGBA'>\n | $PropertyType<WebGLRenderingContext, 'ALPHA'>;\nexport type TextureFilter =\n | $PropertyType<WebGLRenderingContext, 'LINEAR'>\n | $PropertyType<WebGLRenderingContext, 'LINEAR_MIPMAP_NEAREST'>\n | $PropertyType<WebGLRenderingContext, 'NEAREST'>;\nexport type TextureWrap =\n | $PropertyType<WebGLRenderingContext, 'REPEAT'>\n | $PropertyType<WebGLRenderingContext, 'CLAMP_TO_EDGE'>\n | $PropertyType<WebGLRenderingContext, 'MIRRORED_REPEAT'>;\n\ntype EmptyImage = {\n width: number,\n height: number,\n data: null\n}\n\nexport type TextureImage =\n | RGBAImage\n | AlphaImage\n | HTMLImageElement\n | HTMLCanvasElement\n | HTMLVideoElement\n | ImageData\n | EmptyImage\n | ImageBitmap;\n\nclass Texture {\n context: Context;\n size: [number, number];\n texture: WebGLTexture;\n format: TextureFormat;\n filter: ?TextureFilter;\n wrap: ?TextureWrap;\n useMipmap: boolean;\n\n constructor(context: Context, image: TextureImage, format: TextureFormat, options: ?{ premultiply?: boolean, useMipmap?: boolean }) {\n this.context = context;\n this.format = format;\n this.texture = ((context.gl.createTexture(): any): WebGLTexture);\n this.update(image, options);\n }\n\n update(image: TextureImage, options: ?{premultiply?: boolean, useMipmap?: boolean}, position?: { x: number, y: number }) {\n const {width, height} = image;\n const {context} = this;\n const {gl} = context;\n const {HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData, ImageBitmap} = window;\n\n gl.bindTexture(gl.TEXTURE_2D, this.texture);\n\n context.pixelStoreUnpackFlipY.set(false);\n context.pixelStoreUnpack.set(1);\n context.pixelStoreUnpackPremultiplyAlpha.set(this.format === gl.RGBA && (!options || options.premultiply !== false));\n\n if (!position && (!this.size || this.size[0] !== width || this.size[1] !== height)) {\n this.size = [width, height];\n\n if (image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || (ImageBitmap && image instanceof ImageBitmap)) {\n gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, gl.UNSIGNED_BYTE, image);\n } else {\n // $FlowFixMe prop-missing - Flow can't refine image type here\n gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, gl.UNSIGNED_BYTE, image.data);\n }\n\n } else {\n const {x, y} = position || {x: 0, y: 0};\n if (image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || (ImageBitmap && image instanceof ImageBitmap)) {\n gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, gl.RGBA, gl.UNSIGNED_BYTE, image);\n } else {\n // $FlowFixMe prop-missing - Flow can't refine image type here\n gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, image.data);\n }\n }\n\n this.useMipmap = Boolean(options && options.useMipmap && this.isSizePowerOfTwo());\n if (this.useMipmap) {\n gl.generateMipmap(gl.TEXTURE_2D);\n }\n }\n\n bind(filter: TextureFilter, wrap: TextureWrap) {\n const {context} = this;\n const {gl} = context;\n gl.bindTexture(gl.TEXTURE_2D, this.texture);\n\n if (filter !== this.filter) {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER,\n this.useMipmap ? (filter === gl.NEAREST ? gl.NEAREST_MIPMAP_NEAREST : gl.LINEAR_MIPMAP_NEAREST) : filter\n );\n this.filter = filter;\n }\n\n if (wrap !== this.wrap) {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);\n this.wrap = wrap;\n }\n }\n\n isSizePowerOfTwo(): boolean {\n return this.size[0] === this.size[1] && (Math.log(this.size[0]) / Math.LN2) % 1 === 0;\n }\n\n destroy() {\n const {gl} = this.context;\n gl.deleteTexture(this.texture);\n this.texture = (null: any);\n }\n}\n\nexport default Texture;\n","// @flow\n// logic for generating non-Mercator adaptive raster tile reprojection meshes with MARTINI\n\nimport tileTransform from '../geo/projection/tile_transform.js';\nimport EXTENT from '../data/extent.js';\nimport {lngFromMercatorX, latFromMercatorY} from '../geo/mercator_coordinate.js';\nimport {TileBoundsArray, TriangleIndexArray} from '../data/array_types.js';\n\nimport type {CanonicalTileID} from './tile_id.js';\nimport type Projection from '../geo/projection/projection.js';\n\nconst meshSize = 32;\nconst gridSize = meshSize + 1;\n\nconst numTriangles = meshSize * meshSize * 2 - 2;\nconst numParentTriangles = numTriangles - meshSize * meshSize;\n\nconst coords = new Uint16Array(numTriangles * 4);\n\n// precalculate RTIN triangle coordinates\nfor (let i = 0; i < numTriangles; i++) {\n let id = i + 2;\n let ax = 0, ay = 0, bx = 0, by = 0, cx = 0, cy = 0;\n\n if (id & 1) {\n bx = by = cx = meshSize; // bottom-left triangle\n\n } else {\n ax = ay = cy = meshSize; // top-right triangle\n }\n\n while ((id >>= 1) > 1) {\n const mx = (ax + bx) >> 1;\n const my = (ay + by) >> 1;\n\n if (id & 1) { // left half\n bx = ax; by = ay;\n ax = cx; ay = cy;\n\n } else { // right half\n ax = bx; ay = by;\n bx = cx; by = cy;\n }\n\n cx = mx; cy = my;\n }\n\n const k = i * 4;\n coords[k + 0] = ax;\n coords[k + 1] = ay;\n coords[k + 2] = bx;\n coords[k + 3] = by;\n}\n\n// temporary arrays we'll reuse for MARTINI mesh code\nconst reprojectedCoords = new Uint16Array(gridSize * gridSize * 2);\nconst used = new Uint8Array(gridSize * gridSize);\nconst indexMap = new Uint16Array(gridSize * gridSize);\n\ntype TileMesh = {\n vertices: TileBoundsArray,\n indices: TriangleIndexArray\n};\n\n// There can be visible seams between neighbouring tiles because of precision issues\n// and resampling differences. Adding a bit of padding around the edges of tiles hides\n// most of these issues.\nconst commonRasterTileSize = 256;\nconst paddingSize = meshSize / commonRasterTileSize / 4;\nfunction seamPadding(n: number) {\n if (n === 0) return -paddingSize;\n else if (n === gridSize - 1) return paddingSize;\n else return 0;\n}\n\nexport default function getTileMesh(canonical: CanonicalTileID, projection: Projection): TileMesh {\n const cs = tileTransform(canonical, projection);\n const z2 = Math.pow(2, canonical.z);\n\n for (let y = 0; y < gridSize; y++) {\n for (let x = 0; x < gridSize; x++) {\n const lng = lngFromMercatorX((canonical.x + (x + seamPadding(x)) / meshSize) / z2);\n const lat = latFromMercatorY((canonical.y + (y + seamPadding(y)) / meshSize) / z2);\n const p = projection.project(lng, lat);\n const k = y * gridSize + x;\n reprojectedCoords[2 * k + 0] = Math.round((p.x * cs.scale - cs.x) * EXTENT);\n reprojectedCoords[2 * k + 1] = Math.round((p.y * cs.scale - cs.y) * EXTENT);\n }\n }\n\n used.fill(0);\n indexMap.fill(0);\n\n // iterate over all possible triangles, starting from the smallest level\n for (let i = numTriangles - 1; i >= 0; i--) {\n const k = i * 4;\n const ax = coords[k + 0];\n const ay = coords[k + 1];\n const bx = coords[k + 2];\n const by = coords[k + 3];\n const mx = (ax + bx) >> 1;\n const my = (ay + by) >> 1;\n const cx = mx + my - ay;\n const cy = my + ax - mx;\n\n const aIndex = ay * gridSize + ax;\n const bIndex = by * gridSize + bx;\n const mIndex = my * gridSize + mx;\n\n // calculate error in the middle of the long edge of the triangle\n const rax = reprojectedCoords[2 * aIndex + 0];\n const ray = reprojectedCoords[2 * aIndex + 1];\n const rbx = reprojectedCoords[2 * bIndex + 0];\n const rby = reprojectedCoords[2 * bIndex + 1];\n const rmx = reprojectedCoords[2 * mIndex + 0];\n const rmy = reprojectedCoords[2 * mIndex + 1];\n\n // raster tiles are typically 512px, and we use 1px as an error threshold; 8192 / 512 = 16\n const isUsed = Math.hypot((rax + rbx) / 2 - rmx, (ray + rby) / 2 - rmy) >= 16;\n\n used[mIndex] = used[mIndex] || (isUsed ? 1 : 0);\n\n if (i < numParentTriangles) { // bigger triangles; accumulate error with children\n const leftChildIndex = ((ay + cy) >> 1) * gridSize + ((ax + cx) >> 1);\n const rightChildIndex = ((by + cy) >> 1) * gridSize + ((bx + cx) >> 1);\n used[mIndex] = used[mIndex] || used[leftChildIndex] || used[rightChildIndex];\n }\n }\n\n const vertices = new TileBoundsArray();\n const indices = new TriangleIndexArray();\n\n let numVertices = 0;\n\n function addVertex(x: number, y: number) {\n const k = y * gridSize + x;\n\n if (indexMap[k] === 0) {\n vertices.emplaceBack(\n reprojectedCoords[2 * k + 0],\n reprojectedCoords[2 * k + 1],\n x * EXTENT / meshSize,\n y * EXTENT / meshSize);\n\n // save new vertex index so that we can reuse it\n indexMap[k] = ++numVertices;\n }\n\n return indexMap[k] - 1;\n }\n\n function addTriangles(ax: number, ay: number, bx: number, by: number, cx: number, cy: number) {\n const mx = (ax + bx) >> 1;\n const my = (ay + by) >> 1;\n\n if (Math.abs(ax - cx) + Math.abs(ay - cy) > 1 && used[my * gridSize + mx]) {\n // triangle doesn't approximate the surface well enough; drill down further\n addTriangles(cx, cy, ax, ay, mx, my);\n addTriangles(bx, by, cx, cy, mx, my);\n\n } else {\n const ai = addVertex(ax, ay);\n const bi = addVertex(bx, by);\n const ci = addVertex(cx, cy);\n indices.emplaceBack(ai, bi, ci);\n }\n }\n\n addTriangles(0, 0, meshSize, meshSize, meshSize, 0);\n addTriangles(meshSize, meshSize, 0, 0, 0, meshSize);\n\n return {vertices, indices};\n}\n","// @flow\nimport {createLayout} from '../util/struct_array.js';\n\nimport type {StructArrayLayout} from '../util/struct_array.js';\n\nexport default (createLayout([\n {name: 'a_pos', type: 'Int16', components: 2},\n {name: 'a_texture_pos', type: 'Int16', components: 2}\n]): StructArrayLayout);\n","// @flow\n\nimport {uniqueId, parseCacheControl} from '../util/util.js';\nimport {deserialize as deserializeBucket} from '../data/bucket.js';\nimport FeatureIndex from '../data/feature_index.js';\nimport GeoJSONFeature from '../util/vectortile_to_geojson.js';\nimport featureFilter from '../style-spec/feature_filter/index.js';\nimport SymbolBucket from '../data/bucket/symbol_bucket.js';\nimport FillBucket from '../data/bucket/fill_bucket.js';\nimport LineBucket from '../data/bucket/line_bucket.js';\nimport {CollisionBoxArray, TileBoundsArray, PosArray, TriangleIndexArray, LineStripIndexArray, PosGlobeExtArray} from '../data/array_types.js';\nimport Texture from '../render/texture.js';\nimport browser from '../util/browser.js';\nimport {Debug} from '../util/debug.js';\nimport toEvaluationFeature from '../data/evaluation_feature.js';\nimport EvaluationParameters from '../style/evaluation_parameters.js';\nimport SourceFeatureState from '../source/source_state.js';\nimport {lazyLoadRTLTextPlugin} from './rtl_text_plugin.js';\nimport {TileSpaceDebugBuffer} from '../data/debug_viz.js';\nimport Color from '../style-spec/util/color.js';\nimport loadGeometry from '../data/load_geometry.js';\nimport earcut from 'earcut';\nimport getTileMesh from './tile_mesh.js';\nimport tileTransform from '../geo/projection/tile_transform.js';\nimport {mercatorXfromLng, mercatorYfromLat} from '../geo/mercator_coordinate.js';\nimport boundsAttributes from '../data/bounds_attributes.js';\nimport posAttributes, {posAttributesGlobeExt} from '../data/pos_attributes.js';\nimport EXTENT from '../data/extent.js';\nimport Point from '@mapbox/point-geometry';\nimport SegmentVector from '../data/segment.js';\nimport {transitionTileAABBinECEF, globeNormalizeECEF, tileCoordToECEF, globeToMercatorTransition, interpolateVec3} from '../geo/projection/globe_util.js';\nimport {vec3, mat4} from 'gl-matrix';\n\nimport type {Bucket} from '../data/bucket.js';\nimport type StyleLayer from '../style/style_layer.js';\nimport type {WorkerTileResult} from './worker_source.js';\nimport type Actor from '../util/actor.js';\nimport type DEMData from '../data/dem_data.js';\nimport type {AlphaImage, SpritePositions} from '../util/image.js';\nimport type ImageAtlas from '../render/image_atlas.js';\nimport type LineAtlas from '../render/line_atlas.js';\nimport type ImageManager from '../render/image_manager.js';\nimport type Context from '../gl/context.js';\nimport type {CanonicalTileID, OverscaledTileID} from './tile_id.js';\nimport type Framebuffer from '../gl/framebuffer.js';\nimport type Transform from '../geo/transform.js';\nimport type {LayerFeatureStates} from './source_state.js';\nimport type {Cancelable} from '../types/cancelable.js';\nimport type {FilterSpecification} from '../style-spec/types.js';\nimport type {TilespaceQueryGeometry} from '../style/query_geometry.js';\nimport type VertexBuffer from '../gl/vertex_buffer.js';\nimport type IndexBuffer from '../gl/index_buffer.js';\nimport type Projection from '../geo/projection/projection.js';\nimport type {TileTransform} from '../geo/projection/tile_transform.js';\nimport type {QueryResult} from '../data/feature_index.js';\nimport type Painter from '../render/painter.js';\nimport type {QueryFeature} from '../util/vectortile_to_geojson.js';\nimport type {Vec3} from 'gl-matrix';\nimport type {TextureImage} from '../render/texture.js';\nimport type {VectorTileLayer} from '@mapbox/vector-tile';\n\nconst CLOCK_SKEW_RETRY_TIMEOUT = 30000;\nexport type TileState =\n | 'loading' // Tile data is in the process of loading.\n | 'loaded' // Tile data has been loaded. Tile can be rendered.\n | 'reloading' // Tile data has been loaded and is being updated. Tile can be rendered.\n | 'unloaded' // Tile data has been deleted.\n | 'errored' // Tile data was not loaded because of an error.\n | 'expired'; /* Tile data was previously loaded, but has expired per its\n * HTTP headers and is in the process of refreshing. */\n\n// a tile bounds outline used for getting reprojected tile geometry in non-mercator projections\nconst BOUNDS_FEATURE = (() => {\n return {\n type: 2,\n extent: EXTENT,\n loadGeometry() {\n return [[\n new Point(0, 0),\n new Point(EXTENT + 1, 0),\n new Point(EXTENT + 1, EXTENT + 1),\n new Point(0, EXTENT + 1),\n new Point(0, 0)\n ]];\n }\n };\n})();\n\n/**\n * A tile object is the combination of a Coordinate, which defines\n * its place, as well as a unique ID and data tracking for its content\n *\n * @private\n */\nclass Tile {\n tileID: OverscaledTileID;\n uid: number;\n uses: number;\n tileSize: number;\n tileZoom: number;\n buckets: {[_: string]: Bucket};\n latestFeatureIndex: ?FeatureIndex;\n latestRawTileData: ?ArrayBuffer;\n imageAtlas: ?ImageAtlas;\n imageAtlasTexture: Texture;\n lineAtlas: ?LineAtlas;\n lineAtlasTexture: Texture;\n glyphAtlasImage: ?AlphaImage;\n glyphAtlasTexture: Texture;\n expirationTime: any;\n expiredRequestCount: number;\n state: TileState;\n timeAdded: any;\n fadeEndTime: any;\n collisionBoxArray: ?CollisionBoxArray;\n redoWhenDone: boolean;\n showCollisionBoxes: boolean;\n placementSource: any;\n actor: ?Actor;\n vtLayers: {[_: string]: VectorTileLayer};\n isSymbolTile: ?boolean;\n isRaster: ?boolean;\n _tileTransform: TileTransform;\n\n neighboringTiles: ?Object;\n dem: ?DEMData;\n aborted: ?boolean;\n needsHillshadePrepare: ?boolean;\n needsDEMTextureUpload: ?boolean;\n request: ?Cancelable;\n texture: any;\n fbo: ?Framebuffer;\n demTexture: ?Texture;\n refreshedUponExpiration: boolean;\n reloadCallback: any;\n resourceTiming: ?Array<PerformanceResourceTiming>;\n queryPadding: number;\n\n symbolFadeHoldUntil: ?number;\n hasSymbolBuckets: boolean;\n hasRTLText: boolean;\n dependencies: Object;\n projection: Projection;\n\n queryGeometryDebugViz: ?TileSpaceDebugBuffer;\n queryBoundsDebugViz: ?TileSpaceDebugBuffer;\n\n _tileDebugBuffer: ?VertexBuffer;\n _tileBoundsBuffer: ?VertexBuffer;\n _tileDebugIndexBuffer: ?IndexBuffer;\n _tileBoundsIndexBuffer: IndexBuffer;\n _tileDebugSegments: SegmentVector;\n _tileBoundsSegments: SegmentVector;\n _globeTileDebugBorderBuffer: ?VertexBuffer;\n _tileDebugTextBuffer: ?VertexBuffer;\n _tileDebugTextSegments: SegmentVector;\n _tileDebugTextIndexBuffer: IndexBuffer;\n _globeTileDebugTextBuffer: ?VertexBuffer;\n\n /**\n * @param {OverscaledTileID} tileID\n * @param size\n * @private\n */\n constructor(tileID: OverscaledTileID, size: number, tileZoom: number, painter: any, isRaster?: boolean) {\n this.tileID = tileID;\n this.uid = uniqueId();\n this.uses = 0;\n this.tileSize = size;\n this.tileZoom = tileZoom;\n this.buckets = {};\n this.expirationTime = null;\n this.queryPadding = 0;\n this.hasSymbolBuckets = false;\n this.hasRTLText = false;\n this.dependencies = {};\n this.isRaster = isRaster;\n\n // Counts the number of times a response was already expired when\n // received. We're using this to add a delay when making a new request\n // so we don't have to keep retrying immediately in case of a server\n // serving expired tiles.\n this.expiredRequestCount = 0;\n\n this.state = 'loading';\n\n if (painter && painter.transform) {\n this.projection = painter.transform.projection;\n }\n }\n\n registerFadeDuration(duration: number) {\n const fadeEndTime = duration + this.timeAdded;\n if (fadeEndTime < browser.now()) return;\n if (this.fadeEndTime && fadeEndTime < this.fadeEndTime) return;\n\n this.fadeEndTime = fadeEndTime;\n }\n\n wasRequested(): boolean {\n return this.state === 'errored' || this.state === 'loaded' || this.state === 'reloading';\n }\n\n get tileTransform(): TileTransform {\n if (!this._tileTransform) {\n this._tileTransform = tileTransform(this.tileID.canonical, this.projection);\n }\n return this._tileTransform;\n }\n\n /**\n * Given a data object with a 'buffers' property, load it into\n * this tile's elementGroups and buffers properties and set loaded\n * to true. If the data is null, like in the case of an empty\n * GeoJSON tile, no-op but still set loaded to true.\n * @param {Object} data\n * @param painter\n * @returns {undefined}\n * @private\n */\n loadVectorData(data: ?WorkerTileResult, painter: any, justReloaded: ?boolean) {\n this.unloadVectorData();\n\n this.state = 'loaded';\n\n // empty GeoJSON tile\n if (!data) {\n this.collisionBoxArray = new CollisionBoxArray();\n return;\n }\n\n if (data.featureIndex) {\n this.latestFeatureIndex = data.featureIndex;\n if (data.rawTileData) {\n // Only vector tiles have rawTileData, and they won't update it for\n // 'reloadTile'\n this.latestRawTileData = data.rawTileData;\n this.latestFeatureIndex.rawTileData = data.rawTileData;\n } else if (this.latestRawTileData) {\n // If rawTileData hasn't updated, hold onto a pointer to the last\n // one we received\n this.latestFeatureIndex.rawTileData = this.latestRawTileData;\n }\n }\n this.collisionBoxArray = data.collisionBoxArray;\n this.buckets = deserializeBucket(data.buckets, painter.style);\n\n this.hasSymbolBuckets = false;\n for (const id in this.buckets) {\n const bucket = this.buckets[id];\n if (bucket instanceof SymbolBucket) {\n this.hasSymbolBuckets = true;\n if (justReloaded) {\n bucket.justReloaded = true;\n } else {\n break;\n }\n }\n }\n\n this.hasRTLText = false;\n if (this.hasSymbolBuckets) {\n for (const id in this.buckets) {\n const bucket = this.buckets[id];\n if (bucket instanceof SymbolBucket) {\n if (bucket.hasRTLText) {\n this.hasRTLText = true;\n lazyLoadRTLTextPlugin();\n break;\n }\n }\n }\n }\n\n this.queryPadding = 0;\n for (const id in this.buckets) {\n const bucket = this.buckets[id];\n this.queryPadding = Math.max(this.queryPadding, painter.style.getLayer(id).queryRadius(bucket));\n }\n\n if (data.imageAtlas) {\n this.imageAtlas = data.imageAtlas;\n }\n if (data.glyphAtlasImage) {\n this.glyphAtlasImage = data.glyphAtlasImage;\n }\n if (data.lineAtlas) {\n this.lineAtlas = data.lineAtlas;\n }\n }\n\n /**\n * Release any data or WebGL resources referenced by this tile.\n * @returns {undefined}\n * @private\n */\n unloadVectorData() {\n if (!this.hasData()) return;\n\n for (const id in this.buckets) {\n this.buckets[id].destroy();\n }\n this.buckets = {};\n\n if (this.imageAtlas) {\n this.imageAtlas = null;\n }\n\n if (this.lineAtlas) {\n this.lineAtlas = null;\n }\n\n if (this.imageAtlasTexture) {\n this.imageAtlasTexture.destroy();\n }\n\n if (this.glyphAtlasTexture) {\n this.glyphAtlasTexture.destroy();\n }\n\n if (this.lineAtlasTexture) {\n this.lineAtlasTexture.destroy();\n }\n\n if (this._tileBoundsBuffer) {\n this._tileBoundsBuffer.destroy();\n this._tileBoundsIndexBuffer.destroy();\n this._tileBoundsSegments.destroy();\n this._tileBoundsBuffer = null;\n }\n\n if (this._tileDebugBuffer) {\n this._tileDebugBuffer.destroy();\n this._tileDebugSegments.destroy();\n this._tileDebugBuffer = null;\n }\n\n if (this._tileDebugIndexBuffer) {\n this._tileDebugIndexBuffer.destroy();\n this._tileDebugIndexBuffer = null;\n }\n\n if (this._globeTileDebugBorderBuffer) {\n this._globeTileDebugBorderBuffer.destroy();\n this._globeTileDebugBorderBuffer = null;\n }\n\n if (this._tileDebugTextBuffer) {\n this._tileDebugTextBuffer.destroy();\n this._tileDebugTextSegments.destroy();\n this._tileDebugTextIndexBuffer.destroy();\n this._tileDebugTextBuffer = null;\n }\n\n if (this._globeTileDebugTextBuffer) {\n this._globeTileDebugTextBuffer.destroy();\n this._globeTileDebugTextBuffer = null;\n }\n\n Debug.run(() => {\n if (this.queryGeometryDebugViz) {\n this.queryGeometryDebugViz.unload();\n delete this.queryGeometryDebugViz;\n }\n if (this.queryBoundsDebugViz) {\n this.queryBoundsDebugViz.unload();\n delete this.queryBoundsDebugViz;\n }\n });\n this.latestFeatureIndex = null;\n this.state = 'unloaded';\n }\n\n getBucket(layer: StyleLayer): Bucket {\n return this.buckets[layer.id];\n }\n\n upload(context: Context) {\n for (const id in this.buckets) {\n const bucket = this.buckets[id];\n if (bucket.uploadPending()) {\n bucket.upload(context);\n }\n }\n\n const gl = context.gl;\n if (this.imageAtlas && !this.imageAtlas.uploaded) {\n this.imageAtlasTexture = new Texture(context, this.imageAtlas.image, gl.RGBA);\n ((this.imageAtlas: any): ImageAtlas).uploaded = true;\n }\n\n if (this.glyphAtlasImage) {\n this.glyphAtlasTexture = new Texture(context, this.glyphAtlasImage, gl.ALPHA);\n this.glyphAtlasImage = null;\n }\n\n if (this.lineAtlas && !this.lineAtlas.uploaded) {\n this.lineAtlasTexture = new Texture(context, this.lineAtlas.image, gl.ALPHA);\n ((this.lineAtlas: any): LineAtlas).uploaded = true;\n }\n }\n\n prepare(imageManager: ImageManager) {\n if (this.imageAtlas) {\n this.imageAtlas.patchUpdatedImages(imageManager, this.imageAtlasTexture);\n }\n }\n\n // Queries non-symbol features rendered for this tile.\n // Symbol features are queried globally\n queryRenderedFeatures(layers: {[_: string]: StyleLayer},\n serializedLayers: {[string]: Object},\n sourceFeatureState: SourceFeatureState,\n tileResult: TilespaceQueryGeometry,\n params: { filter: FilterSpecification, layers: Array<string>, availableImages: Array<string> },\n transform: Transform,\n pixelPosMatrix: Float32Array,\n visualizeQueryGeometry: boolean): QueryResult {\n Debug.run(() => {\n if (visualizeQueryGeometry) {\n let geometryViz = this.queryGeometryDebugViz;\n let boundsViz = this.queryBoundsDebugViz;\n if (!geometryViz) {\n geometryViz = this.queryGeometryDebugViz = new TileSpaceDebugBuffer(this.tileSize);\n }\n if (!boundsViz) {\n boundsViz = this.queryBoundsDebugViz = new TileSpaceDebugBuffer(this.tileSize, Color.blue);\n }\n\n geometryViz.addPoints(tileResult.tilespaceGeometry);\n boundsViz.addPoints(tileResult.bufferedTilespaceGeometry);\n }\n });\n\n if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData)\n return {};\n\n return this.latestFeatureIndex.query({\n tileResult,\n pixelPosMatrix,\n transform,\n params,\n tileTransform: this.tileTransform\n }, layers, serializedLayers, sourceFeatureState);\n }\n\n querySourceFeatures(result: Array<QueryFeature>, params: any) {\n const featureIndex = this.latestFeatureIndex;\n if (!featureIndex || !featureIndex.rawTileData) return;\n\n const vtLayers = featureIndex.loadVTLayers();\n\n const sourceLayer = params ? params.sourceLayer : '';\n const layer = vtLayers._geojsonTileLayer || vtLayers[sourceLayer];\n\n if (!layer) return;\n\n const filter = featureFilter(params && params.filter);\n const {z, x, y} = this.tileID.canonical;\n const coord = {z, x, y};\n\n for (let i = 0; i < layer.length; i++) {\n const feature = layer.feature(i);\n if (filter.needGeometry) {\n const evaluationFeature = toEvaluationFeature(feature, true);\n // $FlowFixMe[method-unbinding]\n if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) continue;\n // $FlowFixMe[method-unbinding]\n } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) {\n continue;\n }\n const id = featureIndex.getId(feature, sourceLayer);\n const geojsonFeature = new GeoJSONFeature(feature, z, x, y, id);\n geojsonFeature.tile = coord;\n\n result.push(geojsonFeature);\n }\n }\n\n hasData(): boolean {\n return this.state === 'loaded' || this.state === 'reloading' || this.state === 'expired';\n }\n\n patternsLoaded(): boolean {\n return !!this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length;\n }\n\n setExpiryData(data: any) {\n const prior = this.expirationTime;\n\n if (data.cacheControl) {\n const parsedCC = parseCacheControl(data.cacheControl);\n if (parsedCC['max-age']) this.expirationTime = Date.now() + parsedCC['max-age'] * 1000;\n } else if (data.expires) {\n this.expirationTime = new Date(data.expires).getTime();\n }\n\n if (this.expirationTime) {\n const now = Date.now();\n let isExpired = false;\n\n if (this.expirationTime > now) {\n isExpired = false;\n } else if (!prior) {\n isExpired = true;\n } else if (this.expirationTime < prior) {\n // Expiring date is going backwards:\n // fall back to exponential backoff\n isExpired = true;\n\n } else {\n const delta = this.expirationTime - prior;\n\n if (!delta) {\n // Server is serving the same expired resource over and over: fall\n // back to exponential backoff.\n isExpired = true;\n\n } else {\n // Assume that either the client or the server clock is wrong and\n // try to interpolate a valid expiration date (from the client POV)\n // observing a minimum timeout.\n this.expirationTime = now + Math.max(delta, CLOCK_SKEW_RETRY_TIMEOUT);\n\n }\n }\n\n if (isExpired) {\n this.expiredRequestCount++;\n this.state = 'expired';\n } else {\n this.expiredRequestCount = 0;\n }\n }\n }\n\n getExpiryTimeout(): void | number {\n if (this.expirationTime) {\n if (this.expiredRequestCount) {\n return 1000 * (1 << Math.min(this.expiredRequestCount - 1, 31));\n } else {\n // Max value for `setTimeout` implementations is a 32 bit integer; cap this accordingly\n return Math.min(this.expirationTime - new Date().getTime(), Math.pow(2, 31) - 1);\n }\n }\n }\n\n setFeatureState(states: LayerFeatureStates, painter: ?Painter) {\n if (!this.latestFeatureIndex ||\n !this.latestFeatureIndex.rawTileData ||\n Object.keys(states).length === 0 ||\n !painter) {\n return;\n }\n\n const vtLayers = this.latestFeatureIndex.loadVTLayers();\n const availableImages = painter.style.listImages();\n\n for (const id in this.buckets) {\n if (!painter.style.hasLayer(id)) continue;\n\n const bucket = this.buckets[id];\n // Buckets are grouped by common source-layer\n const sourceLayerId = bucket.layers[0]['sourceLayer'] || '_geojsonTileLayer';\n const sourceLayer = vtLayers[sourceLayerId];\n const sourceLayerStates = states[sourceLayerId];\n if (!sourceLayer || !sourceLayerStates || Object.keys(sourceLayerStates).length === 0) continue;\n\n // $FlowFixMe[incompatible-type] Flow can't interpret ImagePosition as SpritePosition for some reason here\n const imagePositions: SpritePositions = (this.imageAtlas && this.imageAtlas.patternPositions) || {};\n bucket.update(sourceLayerStates, sourceLayer, availableImages, imagePositions);\n if (bucket instanceof LineBucket || bucket instanceof FillBucket) {\n const sourceCache = painter.style._getSourceCache(bucket.layers[0].source);\n if (painter._terrain && painter._terrain.enabled && sourceCache && bucket.programConfigurations.needsUpload) {\n painter._terrain._clearRenderCacheForTile(sourceCache.id, this.tileID);\n }\n }\n const layer = painter && painter.style && painter.style.getLayer(id);\n if (layer) {\n this.queryPadding = Math.max(this.queryPadding, layer.queryRadius(bucket));\n }\n }\n }\n\n holdingForFade(): boolean {\n return this.symbolFadeHoldUntil !== undefined;\n }\n\n symbolFadeFinished(): boolean {\n return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < browser.now();\n }\n\n clearFadeHold() {\n this.symbolFadeHoldUntil = undefined;\n }\n\n setHoldDuration(duration: number) {\n this.symbolFadeHoldUntil = browser.now() + duration;\n }\n\n setTexture(img: TextureImage, painter: Painter) {\n const context = painter.context;\n const gl = context.gl;\n this.texture = this.texture || painter.getTileTexture(img.width);\n if (this.texture) {\n this.texture.update(img, {useMipmap: true});\n } else {\n this.texture = new Texture(context, img, gl.RGBA, {useMipmap: true});\n this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n }\n }\n\n setDependencies(namespace: string, dependencies: Array<string>) {\n const index = {};\n for (const dep of dependencies) {\n index[dep] = true;\n }\n this.dependencies[namespace] = index;\n }\n\n hasDependency(namespaces: Array<string>, keys: Array<string>): boolean {\n for (const namespace of namespaces) {\n const dependencies = this.dependencies[namespace];\n if (dependencies) {\n for (const key of keys) {\n if (dependencies[key]) {\n return true;\n }\n }\n }\n }\n return false;\n }\n\n clearQueryDebugViz() {\n Debug.run(() => {\n if (this.queryGeometryDebugViz) {\n this.queryGeometryDebugViz.clearPoints();\n }\n if (this.queryBoundsDebugViz) {\n this.queryBoundsDebugViz.clearPoints();\n }\n });\n }\n\n _makeDebugTileBoundsBuffers(context: Context, projection: Projection) {\n if (!projection || projection.name === 'mercator' || this._tileDebugBuffer) return;\n\n // reproject tile outline with adaptive resampling\n const boundsLine = loadGeometry(BOUNDS_FEATURE, this.tileID.canonical, this.tileTransform)[0];\n\n // generate vertices for debugging tile boundaries\n const debugVertices = new PosArray();\n const debugIndices = new LineStripIndexArray();\n\n for (let i = 0; i < boundsLine.length; i++) {\n const {x, y} = boundsLine[i];\n debugVertices.emplaceBack(x, y);\n debugIndices.emplaceBack(i);\n }\n debugIndices.emplaceBack(0);\n\n this._tileDebugIndexBuffer = context.createIndexBuffer(debugIndices);\n this._tileDebugBuffer = context.createVertexBuffer(debugVertices, posAttributes.members);\n this._tileDebugSegments = SegmentVector.simpleSegment(0, 0, debugVertices.length, debugIndices.length);\n }\n\n _makeTileBoundsBuffers(context: Context, projection: Projection) {\n if (this._tileBoundsBuffer || !projection || projection.name === 'mercator') return;\n\n // reproject tile outline with adaptive resampling\n const boundsLine = loadGeometry(BOUNDS_FEATURE, this.tileID.canonical, this.tileTransform)[0];\n\n let boundsVertices, boundsIndices;\n if (this.isRaster) {\n // for raster tiles, generate an adaptive MARTINI mesh\n const mesh = getTileMesh(this.tileID.canonical, projection);\n boundsVertices = mesh.vertices;\n boundsIndices = mesh.indices;\n\n } else {\n // for vector tiles, generate an Earcut triangulation of the outline\n boundsVertices = new TileBoundsArray();\n boundsIndices = new TriangleIndexArray();\n\n for (const {x, y} of boundsLine) {\n boundsVertices.emplaceBack(x, y, 0, 0);\n }\n const indices = earcut(boundsVertices.int16, undefined, 4);\n for (let i = 0; i < indices.length; i += 3) {\n boundsIndices.emplaceBack(indices[i], indices[i + 1], indices[i + 2]);\n }\n }\n this._tileBoundsBuffer = context.createVertexBuffer(boundsVertices, boundsAttributes.members);\n this._tileBoundsIndexBuffer = context.createIndexBuffer(boundsIndices);\n this._tileBoundsSegments = SegmentVector.simpleSegment(0, 0, boundsVertices.length, boundsIndices.length);\n }\n\n _makeGlobeTileDebugBuffers(context: Context, transform: Transform) {\n const projection = transform.projection;\n if (!projection || projection.name !== 'globe' || transform.freezeTileCoverage) return;\n\n const id = this.tileID.canonical;\n const bounds = transitionTileAABBinECEF(id, transform);\n const normalizationMatrix = globeNormalizeECEF(bounds);\n\n const phase = globeToMercatorTransition(transform.zoom);\n let worldToECEFMatrix;\n if (phase > 0.0) {\n worldToECEFMatrix = mat4.invert(new Float64Array(16), transform.globeMatrix);\n }\n\n this._makeGlobeTileDebugBorderBuffer(context, id, transform, normalizationMatrix, worldToECEFMatrix, phase);\n this._makeGlobeTileDebugTextBuffer(context, id, transform, normalizationMatrix, worldToECEFMatrix, phase);\n }\n\n _globePoint(x: number, y: number, id: CanonicalTileID, tr: Transform, normalizationMatrix: Float64Array, worldToECEFMatrix?: Float64Array, phase: number): Vec3 {\n // The following is equivalent to doing globe.projectTilePoint.\n // This way we don't recompute the normalization matrix everytime since it remains the same for all points.\n let ecef = tileCoordToECEF(x, y, id);\n if (worldToECEFMatrix) {\n // When in globe-to-Mercator transition, interpolate between globe and Mercator positions in ECEF\n const tileCount = 1 << id.z;\n\n // Wrap tiles to ensure that that Mercator interpolation is in the right direction\n const camX = mercatorXfromLng(tr.center.lng);\n const camY = mercatorYfromLat(tr.center.lat);\n\n const tileCenterX = (id.x + .5) / tileCount;\n const dx = tileCenterX - camX;\n let wrap = 0;\n if (dx > .5) {\n wrap = -1;\n } else if (dx < -.5) {\n wrap = 1;\n }\n\n let mercatorX = (x / EXTENT + id.x) / tileCount + wrap;\n let mercatorY = (y / EXTENT + id.y) / tileCount;\n mercatorX = (mercatorX - camX) * tr._pixelsPerMercatorPixel + camX;\n mercatorY = (mercatorY - camY) * tr._pixelsPerMercatorPixel + camY;\n const mercatorPos = [mercatorX * tr.worldSize, mercatorY * tr.worldSize, 0];\n vec3.transformMat4(mercatorPos, mercatorPos, worldToECEFMatrix);\n ecef = interpolateVec3(ecef, mercatorPos, phase);\n }\n const gp = vec3.transformMat4(ecef, ecef, normalizationMatrix);\n return gp;\n }\n\n _makeGlobeTileDebugBorderBuffer(context: Context, id: CanonicalTileID, tr: Transform, normalizationMatrix: Float64Array, worldToECEFMatrix?: Float64Array, phase: number) {\n const vertices = new PosArray();\n const indices = new LineStripIndexArray();\n const extraGlobe = new PosGlobeExtArray();\n\n const addLine = (sx: number, sy: number, ex: number, ey: number, pointCount: number) => {\n const stepX = (ex - sx) / (pointCount - 1);\n const stepY = (ey - sy) / (pointCount - 1);\n\n const vOffset = vertices.length;\n\n for (let i = 0; i < pointCount; i++) {\n const x = sx + i * stepX;\n const y = sy + i * stepY;\n vertices.emplaceBack(x, y);\n\n const gp = this._globePoint(x, y, id, tr, normalizationMatrix, worldToECEFMatrix, phase);\n\n extraGlobe.emplaceBack(gp[0], gp[1], gp[2]);\n indices.emplaceBack(vOffset + i);\n }\n };\n\n const e = EXTENT;\n addLine(0, 0, e, 0, 16);\n addLine(e, 0, e, e, 16);\n addLine(e, e, 0, e, 16);\n addLine(0, e, 0, 0, 16);\n\n this._tileDebugIndexBuffer = context.createIndexBuffer(indices);\n this._tileDebugBuffer = context.createVertexBuffer(vertices, posAttributes.members);\n this._globeTileDebugBorderBuffer = context.createVertexBuffer(extraGlobe, posAttributesGlobeExt.members);\n this._tileDebugSegments = SegmentVector.simpleSegment(0, 0, vertices.length, indices.length);\n }\n\n _makeGlobeTileDebugTextBuffer(context: Context, id: CanonicalTileID, tr: Transform, normalizationMatrix: Float64Array, worldToECEFMatrix?: Float64Array, phase: number) {\n const SEGMENTS = 4;\n const numVertices = SEGMENTS + 1;\n const step = EXTENT / SEGMENTS;\n\n const vertices = new PosArray();\n const indices = new TriangleIndexArray();\n const extraGlobe = new PosGlobeExtArray();\n\n const totalVertices = numVertices * numVertices;\n const totalTriangles = SEGMENTS * SEGMENTS * 2;\n indices.reserve(totalTriangles);\n vertices.reserve(totalVertices);\n extraGlobe.reserve(totalVertices);\n\n const toIndex = (j: number, i: number): number => {\n return totalVertices * j + i;\n };\n\n // add vertices.\n for (let j = 0; j < totalVertices; j++) {\n const y = j * step;\n for (let i = 0; i < totalVertices; i++) {\n const x = i * step;\n vertices.emplaceBack(x, y);\n\n const gp = this._globePoint(x, y, id, tr, normalizationMatrix, worldToECEFMatrix, phase);\n extraGlobe.emplaceBack(gp[0], gp[1], gp[2]);\n }\n }\n\n // add indices.\n for (let j = 0; j < SEGMENTS; j++) {\n for (let i = 0; i < SEGMENTS; i++) {\n const tl = toIndex(j, i);\n const tr = toIndex(j, i + 1);\n const bl = toIndex(j + 1, i);\n const br = toIndex(j + 1, i + 1);\n\n // first triangle of the sub-patch.\n indices.emplaceBack(tl, tr, bl);\n\n // second triangle of the sub-patch.\n indices.emplaceBack(bl, tr, br);\n }\n }\n\n this._tileDebugTextIndexBuffer = context.createIndexBuffer(indices);\n this._tileDebugTextBuffer = context.createVertexBuffer(vertices, posAttributes.members);\n this._globeTileDebugTextBuffer = context.createVertexBuffer(extraGlobe, posAttributesGlobeExt.members);\n this._tileDebugTextSegments = SegmentVector.simpleSegment(0, 0, totalVertices, totalTriangles);\n }\n}\n\nexport default Tile;\n","// @flow\n\nimport type {CollisionBoxArray} from './array_types.js';\nimport type Style from '../style/style.js';\nimport type {TypedStyleLayer} from '../style/style_layer/typed_style_layer.js';\nimport type FeatureIndex from './feature_index.js';\nimport type Context from '../gl/context.js';\nimport type {FeatureStates} from '../source/source_state.js';\nimport type {SpritePositions} from '../util/image.js';\nimport type LineAtlas from '../render/line_atlas.js';\nimport type {CanonicalTileID} from '../source/tile_id.js';\nimport type {TileTransform} from '../geo/projection/tile_transform.js';\nimport type Point from '@mapbox/point-geometry';\nimport type {ProjectionSpecification} from '../style-spec/types.js';\nimport type {IVectorTileFeature, IVectorTileLayer} from '@mapbox/vector-tile';\n\nexport type BucketParameters<Layer: TypedStyleLayer> = {\n index: number,\n layers: Array<Layer>,\n zoom: number,\n canonical: CanonicalTileID,\n pixelRatio: number,\n overscaling: number,\n collisionBoxArray: CollisionBoxArray,\n sourceLayerIndex: number,\n sourceID: string,\n enableTerrain: boolean,\n projection: ProjectionSpecification\n}\n\nexport type PopulateParameters = {\n featureIndex: FeatureIndex,\n iconDependencies: {},\n patternDependencies: {},\n glyphDependencies: {},\n availableImages: Array<string>,\n lineAtlas: LineAtlas\n}\n\nexport type IndexedFeature = {\n feature: IVectorTileFeature,\n id: number | string | void,\n index: number,\n sourceLayerIndex: number,\n}\n\nexport type BucketFeature = {|\n index: number,\n sourceLayerIndex: number,\n geometry: Array<Array<Point>>,\n properties: Object,\n type: 1 | 2 | 3,\n id?: any,\n +patterns: {[_: string]: string},\n sortKey?: number\n|};\n\n/**\n * The `Bucket` interface is the single point of knowledge about turning vector\n * tiles into WebGL buffers.\n *\n * `Bucket` is an abstract interface. An implementation exists for each style layer type.\n * Create a bucket via the `StyleLayer#createBucket` method.\n *\n * The concrete bucket types, using layout options from the style layer,\n * transform feature geometries into vertex and index data for use by the\n * vertex shader. They also (via `ProgramConfiguration`) use feature\n * properties and the zoom level to populate the attributes needed for\n * data-driven styling.\n *\n * Buckets are designed to be built on a worker thread and then serialized and\n * transferred back to the main thread for rendering. On the worker side, a\n * bucket's vertex, index, and attribute data is stored in `bucket.arrays:\n * ArrayGroup`. When a bucket's data is serialized and sent back to the main\n * thread, is gets deserialized (using `new Bucket(serializedBucketData)`, with\n * the array data now stored in `bucket.buffers: BufferGroup`. BufferGroups\n * hold the same data as ArrayGroups, but are tuned for consumption by WebGL.\n *\n * @private\n */\nexport interface Bucket {\n layerIds: Array<string>;\n hasPattern: boolean;\n +layers: Array<any>;\n +stateDependentLayers: Array<any>;\n +stateDependentLayerIds: Array<string>;\n populate(features: Array<IndexedFeature>, options: PopulateParameters, canonical: CanonicalTileID, tileTransform: TileTransform): void;\n update(states: FeatureStates, vtLayer: IVectorTileLayer, availableImages: Array<string>, imagePositions: SpritePositions): void;\n isEmpty(): boolean;\n\n upload(context: Context): void;\n uploadPending(): boolean;\n\n /**\n * Release the WebGL resources associated with the buffers. Note that because\n * buckets are shared between layers having the same layout properties, they\n * must be destroyed in groups (all buckets for a tile, or all symbol buckets).\n *\n * @private\n */\n destroy(): void;\n}\n\nexport function deserialize(input: Array<Bucket>, style: Style): {[_: string]: Bucket} {\n const output = {};\n\n // Guard against the case where the map's style has been set to null while\n // this bucket has been parsing.\n if (!style) return output;\n\n for (const bucket of input) {\n const layers = bucket.layerIds\n .map((id) => style.getLayer(id))\n .filter(Boolean);\n\n if (layers.length === 0) {\n continue;\n }\n\n // look up StyleLayer objects from layer ids (since we don't\n // want to waste time serializing/copying them from the worker)\n (bucket: any).layers = layers;\n if ((bucket: any).stateDependentLayerIds) {\n (bucket: any).stateDependentLayers = (bucket: any).stateDependentLayerIds.map((lId) => layers.filter((l) => l.id === lId)[0]);\n }\n for (const layer of layers) {\n output[layer.id] = bucket;\n }\n }\n\n return output;\n}\n","// @flow\n\nimport {extend} from '../util/util.js';\nimport Tile from './tile.js';\nimport type {FeatureState} from '../style-spec/expression/index.js';\nimport type Painter from '../render/painter.js';\n\nexport type FeatureStates = {[feature_id: string]: FeatureState};\nexport type LayerFeatureStates = {[layer: string]: FeatureStates};\n\n/**\n * SourceFeatureState manages the state and pending changes\n * to features in a source, separated by source layer.\n * stateChanges and deletedStates batch all changes to the tile (updates and removes, respectively)\n * between coalesce() events. addFeatureState() and removeFeatureState() also update their counterpart's\n * list of changes, such that coalesce() can apply the proper state changes while agnostic to the order of operations.\n * In deletedStates, all null's denote complete removal of state at that scope\n * @private\n*/\nclass SourceFeatureState {\n state: LayerFeatureStates;\n stateChanges: LayerFeatureStates;\n deletedStates: {};\n\n constructor() {\n this.state = {};\n this.stateChanges = {};\n this.deletedStates = {};\n }\n\n updateState(sourceLayer: string, featureId: number | string, newState: Object) {\n const feature = String(featureId);\n this.stateChanges[sourceLayer] = this.stateChanges[sourceLayer] || {};\n this.stateChanges[sourceLayer][feature] = this.stateChanges[sourceLayer][feature] || {};\n extend(this.stateChanges[sourceLayer][feature], newState);\n\n if (this.deletedStates[sourceLayer] === null) {\n this.deletedStates[sourceLayer] = {};\n for (const ft in this.state[sourceLayer]) {\n if (ft !== feature) this.deletedStates[sourceLayer][ft] = null;\n }\n } else {\n const featureDeletionQueued = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] === null;\n if (featureDeletionQueued) {\n this.deletedStates[sourceLayer][feature] = {};\n for (const prop in this.state[sourceLayer][feature]) {\n if (!newState[prop]) this.deletedStates[sourceLayer][feature][prop] = null;\n }\n } else {\n for (const key in newState) {\n const deletionInQueue = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] && this.deletedStates[sourceLayer][feature][key] === null;\n if (deletionInQueue) delete this.deletedStates[sourceLayer][feature][key];\n }\n }\n }\n }\n\n removeFeatureState(sourceLayer: string, featureId?: number | string, key?: string) {\n const sourceLayerDeleted = this.deletedStates[sourceLayer] === null;\n if (sourceLayerDeleted) return;\n\n const feature = String(featureId);\n\n this.deletedStates[sourceLayer] = this.deletedStates[sourceLayer] || {};\n\n if (key && featureId !== undefined) {\n if (this.deletedStates[sourceLayer][feature] !== null) {\n this.deletedStates[sourceLayer][feature] = this.deletedStates[sourceLayer][feature] || {};\n this.deletedStates[sourceLayer][feature][key] = null;\n }\n } else if (featureId !== undefined) {\n const updateInQueue = this.stateChanges[sourceLayer] && this.stateChanges[sourceLayer][feature];\n if (updateInQueue) {\n this.deletedStates[sourceLayer][feature] = {};\n for (key in this.stateChanges[sourceLayer][feature]) this.deletedStates[sourceLayer][feature][key] = null;\n\n } else {\n this.deletedStates[sourceLayer][feature] = null;\n }\n } else {\n this.deletedStates[sourceLayer] = null;\n }\n }\n\n getState(sourceLayer: string, featureId: number | string): FeatureStates {\n const feature = String(featureId);\n const base = this.state[sourceLayer] || {};\n const changes = this.stateChanges[sourceLayer] || {};\n\n const reconciledState = extend({}, base[feature], changes[feature]);\n\n //return empty object if the whole source layer is awaiting deletion\n if (this.deletedStates[sourceLayer] === null) return {};\n else if (this.deletedStates[sourceLayer]) {\n const featureDeletions = this.deletedStates[sourceLayer][featureId];\n if (featureDeletions === null) return {};\n for (const prop in featureDeletions) delete reconciledState[prop];\n }\n return reconciledState;\n }\n\n initializeTileState(tile: Tile, painter: ?Painter) {\n tile.setFeatureState(this.state, painter);\n }\n\n coalesceChanges(tiles: {[_: any]: Tile}, painter: any) {\n //track changes with full state objects, but only for features that got modified\n const featuresChanged: LayerFeatureStates = {};\n\n for (const sourceLayer in this.stateChanges) {\n this.state[sourceLayer] = this.state[sourceLayer] || {};\n const layerStates = {};\n for (const feature in this.stateChanges[sourceLayer]) {\n if (!this.state[sourceLayer][feature]) this.state[sourceLayer][feature] = {};\n extend(this.state[sourceLayer][feature], this.stateChanges[sourceLayer][feature]);\n layerStates[feature] = this.state[sourceLayer][feature];\n }\n featuresChanged[sourceLayer] = layerStates;\n }\n\n for (const sourceLayer in this.deletedStates) {\n this.state[sourceLayer] = this.state[sourceLayer] || {};\n const layerStates = {};\n\n if (this.deletedStates[sourceLayer] === null) {\n for (const ft in this.state[sourceLayer]) {\n layerStates[ft] = {};\n this.state[sourceLayer][ft] = {};\n }\n } else {\n for (const feature in this.deletedStates[sourceLayer]) {\n const deleteWholeFeatureState = this.deletedStates[sourceLayer][feature] === null;\n if (deleteWholeFeatureState) this.state[sourceLayer][feature] = {};\n else if (this.state[sourceLayer][feature]) {\n for (const key of Object.keys(this.deletedStates[sourceLayer][feature])) {\n delete this.state[sourceLayer][feature][key];\n }\n }\n layerStates[feature] = this.state[sourceLayer][feature];\n }\n }\n\n featuresChanged[sourceLayer] = featuresChanged[sourceLayer] || {};\n extend(featuresChanged[sourceLayer], layerStates);\n }\n\n this.stateChanges = {};\n this.deletedStates = {};\n\n if (Object.keys(featuresChanged).length === 0) return;\n\n for (const id in tiles) {\n const tile = tiles[id];\n tile.setFeatureState(featuresChanged, painter);\n }\n }\n}\n\nexport default SourceFeatureState;\n","// @flow\n\nimport DEMData from \"./dem_data.js\";\nimport {vec3} from 'gl-matrix';\nimport {number as interpolate} from '../style-spec/util/interpolate.js';\nimport {clamp} from '../util/util.js';\n\nimport type {Vec3} from 'gl-matrix';\n\nclass MipLevel {\n size: number;\n minimums: Array<number>;\n maximums: Array<number>;\n leaves: Array<number>;\n\n constructor(size_: number) {\n this.size = size_;\n this.minimums = [];\n this.maximums = [];\n this.leaves = [];\n }\n\n getElevation(x: number, y: number): { min: number, max: number} {\n const idx = this.toIdx(x, y);\n return {\n min: this.minimums[idx],\n max: this.maximums[idx]\n };\n }\n\n isLeaf(x: number, y: number): number {\n return this.leaves[this.toIdx(x, y)];\n }\n\n toIdx(x: number, y: number): number {\n return y * this.size + x;\n }\n}\n\nfunction aabbRayIntersect(min: Vec3, max: Vec3, pos: Vec3, dir: Vec3): ?number {\n let tMin = 0;\n let tMax = Number.MAX_VALUE;\n\n const epsilon = 1e-15;\n\n for (let i = 0; i < 3; i++) {\n if (Math.abs(dir[i]) < epsilon) {\n // Parallel ray\n if (pos[i] < min[i] || pos[i] > max[i])\n return null;\n } else {\n const ood = 1.0 / dir[i];\n let t1 = (min[i] - pos[i]) * ood;\n let t2 = (max[i] - pos[i]) * ood;\n if (t1 > t2) {\n const temp = t1;\n t1 = t2;\n t2 = temp;\n }\n if (t1 > tMin)\n tMin = t1;\n if (t2 < tMax)\n tMax = t2;\n if (tMin > tMax)\n return null;\n }\n }\n\n return tMin;\n}\n\nfunction triangleRayIntersect(ax: number, ay: number, az: number, bx: number, by: number, bz: number, cx: number, cy: number, cz: number, pos: Vec3, dir: Vec3): ?number {\n // Compute barycentric coordinates u and v to find the intersection\n const abX = bx - ax;\n const abY = by - ay;\n const abZ = bz - az;\n\n const acX = cx - ax;\n const acY = cy - ay;\n const acZ = cz - az;\n\n // pvec = cross(dir, a), det = dot(ab, pvec)\n const pvecX = dir[1] * acZ - dir[2] * acY;\n const pvecY = dir[2] * acX - dir[0] * acZ;\n const pvecZ = dir[0] * acY - dir[1] * acX;\n const det = abX * pvecX + abY * pvecY + abZ * pvecZ;\n\n if (Math.abs(det) < 1e-15)\n return null;\n\n const invDet = 1.0 / det;\n const tvecX = pos[0] - ax;\n const tvecY = pos[1] - ay;\n const tvecZ = pos[2] - az;\n const u = (tvecX * pvecX + tvecY * pvecY + tvecZ * pvecZ) * invDet;\n\n if (u < 0.0 || u > 1.0)\n return null;\n\n // qvec = cross(tvec, ab)\n const qvecX = tvecY * abZ - tvecZ * abY;\n const qvecY = tvecZ * abX - tvecX * abZ;\n const qvecZ = tvecX * abY - tvecY * abX;\n const v = (dir[0] * qvecX + dir[1] * qvecY + dir[2] * qvecZ) * invDet;\n\n if (v < 0.0 || u + v > 1.0)\n return null;\n\n return (acX * qvecX + acY * qvecY + acZ * qvecZ) * invDet;\n}\n\nfunction frac(v: number, lo: number, hi: number) {\n return (v - lo) / (hi - lo);\n}\n\nfunction decodeBounds(x: number, y: number, depth: number, boundsMinx: number, boundsMiny: number, boundsMaxx: number, boundsMaxy: number, outMin: Array<number>, outMax: Array<number>) {\n const scale = 1 << depth;\n const rangex = boundsMaxx - boundsMinx;\n const rangey = boundsMaxy - boundsMiny;\n\n const minX = (x + 0) / scale * rangex + boundsMinx;\n const maxX = (x + 1) / scale * rangex + boundsMinx;\n const minY = (y + 0) / scale * rangey + boundsMiny;\n const maxY = (y + 1) / scale * rangey + boundsMiny;\n\n outMin[0] = minX;\n outMin[1] = minY;\n outMax[0] = maxX;\n outMax[1] = maxY;\n}\n\n// A small padding value is used with bounding boxes to extend the bottom below sea level\nconst aabbSkirtPadding = 100;\n\n// A sparse min max quad tree for performing accelerated queries against dem elevation data.\n// Each tree node stores the minimum and maximum elevation of its children nodes and a flag whether the node is a leaf.\n// Node data is stored in non-interleaved arrays where the root is at index 0.\nexport default class DemMinMaxQuadTree {\n maximums: Array<number>;\n minimums: Array<number>;\n leaves: Array<number>;\n childOffsets: Array<number>;\n nodeCount: number;\n dem: DEMData;\n _siblingOffset: Array<Array<number>>;\n\n constructor(dem_: DEMData) {\n this.maximums = [];\n this.minimums = [];\n this.leaves = [];\n this.childOffsets = [];\n this.nodeCount = 0;\n this.dem = dem_;\n\n // Precompute the order of 4 sibling nodes in the memory. Top-left, top-right, bottom-left, bottom-right\n this._siblingOffset = [\n [0, 0],\n [1, 0],\n [0, 1],\n [1, 1]\n ];\n\n if (!this.dem)\n return;\n\n const mips = buildDemMipmap(this.dem);\n const maxLvl = mips.length - 1;\n\n // Create the root node\n const rootMip = mips[maxLvl];\n const min = rootMip.minimums;\n const max = rootMip.maximums;\n const leaves = rootMip.leaves;\n this._addNode(min[0], max[0], leaves[0]);\n\n // Construct the rest of the tree recursively\n this._construct(mips, 0, 0, maxLvl, 0);\n }\n\n // Performs raycast against the tree root only. Min and max coordinates defines the size of the root node\n raycastRoot(minx: number, miny: number, maxx: number, maxy: number, p: Vec3, d: Vec3, exaggeration: number = 1): ?number {\n const min = [minx, miny, -aabbSkirtPadding];\n const max = [maxx, maxy, this.maximums[0] * exaggeration];\n return aabbRayIntersect(min, max, p, d);\n }\n\n raycast(rootMinx: number, rootMiny: number, rootMaxx: number, rootMaxy: number, p: Vec3, d: Vec3, exaggeration: number = 1): ?number {\n if (!this.nodeCount)\n return null;\n\n const t = this.raycastRoot(rootMinx, rootMiny, rootMaxx, rootMaxy, p, d, exaggeration);\n if (t == null)\n return null;\n\n const tHits = [];\n const sortedHits = [];\n const boundsMin = [];\n const boundsMax = [];\n\n const stack = [{\n idx: 0,\n t,\n nodex: 0,\n nodey: 0,\n depth: 0\n }];\n\n // Traverse the tree until something is hit or the ray escapes\n while (stack.length > 0) {\n const {idx, t, nodex, nodey, depth} = stack.pop();\n\n if (this.leaves[idx]) {\n // Create 2 triangles to approximate the surface plane for more precise tests\n decodeBounds(nodex, nodey, depth, rootMinx, rootMiny, rootMaxx, rootMaxy, boundsMin, boundsMax);\n\n const scale = 1 << depth;\n const minxUv = (nodex + 0) / scale;\n const maxxUv = (nodex + 1) / scale;\n const minyUv = (nodey + 0) / scale;\n const maxyUv = (nodey + 1) / scale;\n\n // 4 corner points A, B, C and D defines the (quad) area covered by this node\n const az = sampleElevation(minxUv, minyUv, this.dem) * exaggeration;\n const bz = sampleElevation(maxxUv, minyUv, this.dem) * exaggeration;\n const cz = sampleElevation(maxxUv, maxyUv, this.dem) * exaggeration;\n const dz = sampleElevation(minxUv, maxyUv, this.dem) * exaggeration;\n\n const t0: any = triangleRayIntersect(\n boundsMin[0], boundsMin[1], az, // A\n boundsMax[0], boundsMin[1], bz, // B\n boundsMax[0], boundsMax[1], cz, // C\n p, d);\n\n const t1: any = triangleRayIntersect(\n boundsMax[0], boundsMax[1], cz,\n boundsMin[0], boundsMax[1], dz,\n boundsMin[0], boundsMin[1], az,\n p, d);\n\n const tMin = Math.min(\n t0 !== null ? t0 : Number.MAX_VALUE,\n t1 !== null ? t1 : Number.MAX_VALUE);\n\n // The ray might go below the two surface triangles but hit one of the sides.\n // This covers the case of skirt geometry between two dem tiles of different zoom level\n if (tMin === Number.MAX_VALUE) {\n const hitPos = vec3.scaleAndAdd([], p, d, t);\n const fracx = frac(hitPos[0], boundsMin[0], boundsMax[0]);\n const fracy = frac(hitPos[1], boundsMin[1], boundsMax[1]);\n\n if (bilinearLerp(az, bz, dz, cz, fracx, fracy) >= hitPos[2])\n return t;\n } else {\n return tMin;\n }\n\n continue;\n }\n\n // Perform intersection tests agains each of the 4 child nodes and store results from closest to furthest.\n let hitCount = 0;\n\n for (let i = 0; i < this._siblingOffset.length; i++) {\n\n const childNodeX = (nodex << 1) + this._siblingOffset[i][0];\n const childNodeY = (nodey << 1) + this._siblingOffset[i][1];\n\n // Decode node aabb from the morton code\n decodeBounds(childNodeX, childNodeY, depth + 1, rootMinx, rootMiny, rootMaxx, rootMaxy, boundsMin, boundsMax);\n\n boundsMin[2] = -aabbSkirtPadding;\n boundsMax[2] = this.maximums[this.childOffsets[idx] + i] * exaggeration;\n\n const result = aabbRayIntersect(boundsMin, boundsMax, p, d);\n if (result != null) {\n // Build the result list from furthest to closest hit.\n // The order will be inversed when building the stack\n const tHit: number = result;\n tHits[i] = tHit;\n\n let added = false;\n for (let j = 0; j < hitCount && !added; j++) {\n if (tHit >= tHits[sortedHits[j]]) {\n sortedHits.splice(j, 0, i);\n added = true;\n }\n }\n if (!added)\n sortedHits[hitCount] = i;\n hitCount++;\n }\n }\n\n // Continue recursion from closest to furthest\n for (let i = 0; i < hitCount; i++) {\n const hitIdx = sortedHits[i];\n stack.push({\n idx: this.childOffsets[idx] + hitIdx,\n t: tHits[hitIdx],\n nodex: (nodex << 1) + this._siblingOffset[hitIdx][0],\n nodey: (nodey << 1) + this._siblingOffset[hitIdx][1],\n depth: depth + 1\n });\n }\n }\n\n return null;\n }\n\n _addNode(min: number, max: number, leaf: number): number {\n this.minimums.push(min);\n this.maximums.push(max);\n this.leaves.push(leaf);\n this.childOffsets.push(0);\n return this.nodeCount++;\n }\n\n _construct(mips: Array<MipLevel>, x: number, y: number, lvl: number, parentIdx: number) {\n if (mips[lvl].isLeaf(x, y) === 1) {\n return;\n }\n\n // Update parent offset\n if (!this.childOffsets[parentIdx])\n this.childOffsets[parentIdx] = this.nodeCount;\n\n // Construct all 4 children and place them next to each other in memory\n const childLvl = lvl - 1;\n const childMip = mips[childLvl];\n\n let leafMask = 0;\n let firstNodeIdx = 0;\n\n for (let i = 0; i < this._siblingOffset.length; i++) {\n const childX = x * 2 + this._siblingOffset[i][0];\n const childY = y * 2 + this._siblingOffset[i][1];\n\n const elevation = childMip.getElevation(childX, childY);\n const leaf = childMip.isLeaf(childX, childY);\n const nodeIdx = this._addNode(elevation.min, elevation.max, leaf);\n\n if (leaf)\n leafMask |= 1 << i;\n if (!firstNodeIdx)\n firstNodeIdx = nodeIdx;\n }\n\n // Continue construction of the tree recursively to non-leaf nodes.\n for (let i = 0; i < this._siblingOffset.length; i++) {\n if (!(leafMask & (1 << i))) {\n this._construct(mips, x * 2 + this._siblingOffset[i][0], y * 2 + this._siblingOffset[i][1], childLvl, firstNodeIdx + i);\n }\n }\n }\n}\n\nfunction bilinearLerp(p00: any, p10: any, p01: any, p11: any, x: number, y: number): any {\n return interpolate(\n interpolate(p00, p01, y),\n interpolate(p10, p11, y),\n x);\n}\n\n// Sample elevation in normalized uv-space ([0, 0] is the top left)\n// This function does not account for exaggeration\nexport function sampleElevation(fx: number, fy: number, dem: DEMData): number {\n // Sample position in texels\n const demSize = dem.dim;\n const x = clamp(fx * demSize - 0.5, 0, demSize - 1);\n const y = clamp(fy * demSize - 0.5, 0, demSize - 1);\n\n // Compute 4 corner points for bilinear interpolation\n const ixMin = Math.floor(x);\n const iyMin = Math.floor(y);\n const ixMax = Math.min(ixMin + 1, demSize - 1);\n const iyMax = Math.min(iyMin + 1, demSize - 1);\n\n const e00 = dem.get(ixMin, iyMin);\n const e10 = dem.get(ixMax, iyMin);\n const e01 = dem.get(ixMin, iyMax);\n const e11 = dem.get(ixMax, iyMax);\n\n return bilinearLerp(e00, e10, e01, e11, x - ixMin, y - iyMin);\n}\n\nexport function buildDemMipmap(dem: DEMData): Array<MipLevel> {\n const demSize = dem.dim;\n\n const elevationDiffThreshold = 5;\n const texelSizeOfMip0 = 8;\n const levelCount = Math.ceil(Math.log2(demSize / texelSizeOfMip0));\n const mips: Array<MipLevel> = [];\n\n let blockCount = Math.ceil(Math.pow(2, levelCount));\n const blockSize = 1 / blockCount;\n\n const blockSamples = (x: number, y: number, size: number, exclusive: boolean, outBounds: Array<number>) => {\n const padding = exclusive ? 1 : 0;\n const minx = x * size;\n const maxx = (x + 1) * size - padding;\n const miny = y * size;\n const maxy = (y + 1) * size - padding;\n\n outBounds[0] = minx;\n outBounds[1] = miny;\n outBounds[2] = maxx;\n outBounds[3] = maxy;\n };\n\n // The first mip (0) is built by sampling 4 corner points of each 8x8 texel block\n let mip = new MipLevel(blockCount);\n const blockBounds = [];\n\n for (let idx = 0; idx < blockCount * blockCount; idx++) {\n const y = Math.floor(idx / blockCount);\n const x = idx % blockCount;\n\n blockSamples(x, y, blockSize, false, blockBounds);\n\n const e0 = sampleElevation(blockBounds[0], blockBounds[1], dem); // minx, miny\n const e1 = sampleElevation(blockBounds[2], blockBounds[1], dem); // maxx, miny\n const e2 = sampleElevation(blockBounds[2], blockBounds[3], dem); // maxx, maxy\n const e3 = sampleElevation(blockBounds[0], blockBounds[3], dem); // minx, maxy\n\n mip.minimums.push(Math.min(e0, e1, e2, e3));\n mip.maximums.push(Math.max(e0, e1, e2, e3));\n mip.leaves.push(1);\n }\n\n mips.push(mip);\n\n // Construct the rest of the mip levels from bottom to up\n for (blockCount /= 2; blockCount >= 1; blockCount /= 2) {\n const prevMip = mips[mips.length - 1];\n\n mip = new MipLevel(blockCount);\n\n for (let idx = 0; idx < blockCount * blockCount; idx++) {\n const y = Math.floor(idx / blockCount);\n const x = idx % blockCount;\n\n // Sample elevation of all 4 children mip texels. 4 leaf nodes can be concatenated into a single\n // leaf if the total elevation difference is below the threshold value\n blockSamples(x, y, 2, true, blockBounds);\n\n const e0 = prevMip.getElevation(blockBounds[0], blockBounds[1]);\n const e1 = prevMip.getElevation(blockBounds[2], blockBounds[1]);\n const e2 = prevMip.getElevation(blockBounds[2], blockBounds[3]);\n const e3 = prevMip.getElevation(blockBounds[0], blockBounds[3]);\n\n const l0 = prevMip.isLeaf(blockBounds[0], blockBounds[1]);\n const l1 = prevMip.isLeaf(blockBounds[2], blockBounds[1]);\n const l2 = prevMip.isLeaf(blockBounds[2], blockBounds[3]);\n const l3 = prevMip.isLeaf(blockBounds[0], blockBounds[3]);\n\n const minElevation = Math.min(e0.min, e1.min, e2.min, e3.min);\n const maxElevation = Math.max(e0.max, e1.max, e2.max, e3.max);\n const canConcatenate = l0 && l1 && l2 && l3;\n\n mip.maximums.push(maxElevation);\n mip.minimums.push(minElevation);\n\n if (maxElevation - minElevation <= elevationDiffThreshold && canConcatenate) {\n // All samples have uniform elevation. Mark this as a leaf\n mip.leaves.push(1);\n } else {\n mip.leaves.push(0);\n }\n }\n\n mips.push(mip);\n }\n\n return mips;\n}\n","// @flow\nimport {RGBAImage} from '../util/image.js';\n\nimport {warnOnce, clamp} from '../util/util.js';\nimport {register} from '../util/web_worker_transfer.js';\nimport DemMinMaxQuadTree from './dem_tree.js';\nimport assert from 'assert';\n\n// DEMData is a data structure for decoding, backfilling, and storing elevation data for processing in the hillshade shaders\n// data can be populated either from a pngraw image tile or from serliazed data sent back from a worker. When data is initially\n// loaded from a image tile, we decode the pixel values using the appropriate decoding formula, but we store the\n// elevation data as an Int32 value. we add 65536 (2^16) to eliminate negative values and enable the use of\n// integer overflow when creating the texture used in the hillshadePrepare step.\n\n// DEMData also handles the backfilling of data from a tile's neighboring tiles. This is necessary because we use a pixel's 8\n// surrounding pixel values to compute the slope at that pixel, and we cannot accurately calculate the slope at pixels on a\n// tile's edge without backfilling from neighboring tiles.\n\nexport type DEMEncoding = \"mapbox\" | \"terrarium\";\n\nconst unpackVectors = {\n mapbox: [6553.6, 25.6, 0.1, 10000.0],\n terrarium: [256.0, 1.0, 1.0 / 256.0, 32768.0]\n};\n\nfunction unpackMapbox(r: number, g: number, b: number): number {\n // unpacking formula for mapbox.terrain-rgb:\n // https://www.mapbox.com/help/access-elevation-data/#mapbox-terrain-rgb\n return ((r * 256 * 256 + g * 256.0 + b) / 10.0 - 10000.0);\n}\n\nfunction unpackTerrarium(r: number, g: number, b: number): number {\n // unpacking formula for mapzen terrarium:\n // https://aws.amazon.com/public-datasets/terrain/\n return ((r * 256 + g + b / 256) - 32768.0);\n}\n\nexport default class DEMData {\n uid: number;\n pixels: Uint8Array;\n stride: number;\n dim: number;\n encoding: DEMEncoding;\n borderReady: boolean;\n _tree: DemMinMaxQuadTree;\n get tree(): DemMinMaxQuadTree {\n if (!this._tree) this._buildQuadTree();\n return this._tree;\n }\n\n // RGBAImage data has uniform 1px padding on all sides: square tile edge size defines stride\n // and dim is calculated as stride - 2.\n constructor(uid: number, data: ImageData, encoding: DEMEncoding, borderReady: boolean = false, buildQuadTree: boolean = false): void {\n this.uid = uid;\n if (data.height !== data.width) throw new RangeError('DEM tiles must be square');\n if (encoding && encoding !== \"mapbox\" && encoding !== \"terrarium\") return warnOnce(\n `\"${encoding}\" is not a valid encoding type. Valid types include \"mapbox\" and \"terrarium\".`\n );\n this.stride = data.height;\n const dim = this.dim = data.height - 2;\n const values = new Uint32Array(data.data.buffer);\n this.pixels = new Uint8Array(data.data.buffer);\n this.encoding = encoding || 'mapbox';\n this.borderReady = borderReady;\n\n if (borderReady) return;\n\n // in order to avoid flashing seams between tiles, here we are initially populating a 1px border of pixels around the image\n // with the data of the nearest pixel from the image. this data is eventually replaced when the tile's neighboring\n // tiles are loaded and the accurate data can be backfilled using DEMData#backfillBorder\n for (let x = 0; x < dim; x++) {\n // left vertical border\n values[this._idx(-1, x)] = values[this._idx(0, x)];\n // right vertical border\n values[this._idx(dim, x)] = values[this._idx(dim - 1, x)];\n // left horizontal border\n values[this._idx(x, -1)] = values[this._idx(x, 0)];\n // right horizontal border\n values[this._idx(x, dim)] = values[this._idx(x, dim - 1)];\n }\n // corners\n values[this._idx(-1, -1)] = values[this._idx(0, 0)];\n values[this._idx(dim, -1)] = values[this._idx(dim - 1, 0)];\n values[this._idx(-1, dim)] = values[this._idx(0, dim - 1)];\n values[this._idx(dim, dim)] = values[this._idx(dim - 1, dim - 1)];\n if (buildQuadTree) this._buildQuadTree();\n }\n\n _buildQuadTree() {\n assert(!this._tree);\n // Construct the implicit sparse quad tree by traversing mips from top to down\n this._tree = new DemMinMaxQuadTree(this);\n }\n\n get(x: number, y: number, clampToEdge: boolean = false): number {\n if (clampToEdge) {\n x = clamp(x, -1, this.dim);\n y = clamp(y, -1, this.dim);\n }\n const index = this._idx(x, y) * 4;\n const unpack = this.encoding === \"terrarium\" ? unpackTerrarium : unpackMapbox;\n return unpack(this.pixels[index], this.pixels[index + 1], this.pixels[index + 2]);\n }\n\n static getUnpackVector(encoding: DEMEncoding): [number, number, number, number] {\n return unpackVectors[encoding];\n }\n\n get unpackVector(): [number, number, number, number] {\n return unpackVectors[this.encoding];\n }\n\n _idx(x: number, y: number): number {\n if (x < -1 || x >= this.dim + 1 || y < -1 || y >= this.dim + 1) throw new RangeError('out of range source coordinates for DEM data');\n return (y + 1) * this.stride + (x + 1);\n }\n\n static pack(altitude: number, encoding: DEMEncoding): [number, number, number, number] {\n const color = [0, 0, 0, 0];\n const vector = DEMData.getUnpackVector(encoding);\n let v = Math.floor((altitude + vector[3]) / vector[2]);\n color[2] = v % 256;\n v = Math.floor(v / 256);\n color[1] = v % 256;\n v = Math.floor(v / 256);\n color[0] = v;\n return color;\n }\n\n getPixels(): RGBAImage {\n return new RGBAImage({width: this.stride, height: this.stride}, this.pixels);\n }\n\n backfillBorder(borderTile: DEMData, dx: number, dy: number): void {\n if (this.dim !== borderTile.dim) throw new Error('dem dimension mismatch');\n\n let xMin = dx * this.dim,\n xMax = dx * this.dim + this.dim,\n yMin = dy * this.dim,\n yMax = dy * this.dim + this.dim;\n\n switch (dx) {\n case -1:\n xMin = xMax - 1;\n break;\n case 1:\n xMax = xMin + 1;\n break;\n }\n\n switch (dy) {\n case -1:\n yMin = yMax - 1;\n break;\n case 1:\n yMax = yMin + 1;\n break;\n }\n\n const ox = -dx * this.dim;\n const oy = -dy * this.dim;\n for (let y = yMin; y < yMax; y++) {\n for (let x = xMin; x < xMax; x++) {\n const i = 4 * this._idx(x, y);\n const j = 4 * this._idx(x + ox, y + oy);\n this.pixels[i + 0] = borderTile.pixels[j + 0];\n this.pixels[i + 1] = borderTile.pixels[j + 1];\n this.pixels[i + 2] = borderTile.pixels[j + 2];\n this.pixels[i + 3] = borderTile.pixels[j + 3];\n }\n }\n }\n\n onDeserialize() {\n if (this._tree) this._tree.dem = this;\n }\n}\n\nregister(DEMData, 'DEMData');\nregister(DemMinMaxQuadTree, 'DemMinMaxQuadTree', {omit: ['dem']});\n","// @flow\n\nimport {OverscaledTileID} from './tile_id.js';\nimport type Tile from './tile.js';\n\n/**\n * A [least-recently-used cache](http://en.wikipedia.org/wiki/Cache_algorithms)\n * with hash lookup made possible by keeping a list of keys in parallel to\n * an array of dictionary of values\n *\n * @private\n */\nclass TileCache {\n max: number;\n data: {[key: string | number]: Array<{ value: Tile, timeout: ?TimeoutID}>};\n order: Array<number>;\n onRemove: (element: Tile) => void;\n /**\n * @param {number} max The max number of permitted values.\n * @private\n * @param {Function} onRemove The callback called with items when they expire.\n */\n constructor(max: number, onRemove: (element: Tile) => void) {\n this.max = max;\n this.onRemove = onRemove;\n this.reset();\n }\n\n /**\n * Clear the cache.\n *\n * @returns {TileCache} Returns itself to allow for method chaining.\n * @private\n */\n reset(): this {\n for (const key in this.data) {\n for (const removedData of this.data[key]) {\n if (removedData.timeout) clearTimeout(removedData.timeout);\n this.onRemove(removedData.value);\n }\n }\n\n this.data = {};\n this.order = [];\n\n return this;\n }\n\n /**\n * Add a key, value combination to the cache, trimming its size if this pushes\n * it over max length.\n *\n * @param {OverscaledTileID} tileID lookup key for the item\n * @param {*} data any value\n *\n * @returns {TileCache} Returns itself to allow for method chaining.\n * @private\n */\n add(tileID: OverscaledTileID, data: Tile, expiryTimeout: number | void): this {\n const key = tileID.wrapped().key;\n if (this.data[key] === undefined) {\n this.data[key] = [];\n }\n\n const dataWrapper = {\n value: data,\n timeout: undefined\n };\n\n if (expiryTimeout !== undefined) {\n dataWrapper.timeout = setTimeout(() => {\n this.remove(tileID, dataWrapper);\n }, expiryTimeout);\n }\n\n this.data[key].push(dataWrapper);\n this.order.push(key);\n\n if (this.order.length > this.max) {\n const removedData = this._getAndRemoveByKey(this.order[0]);\n if (removedData) this.onRemove(removedData);\n }\n\n return this;\n }\n\n /**\n * Determine whether the value attached to `key` is present\n *\n * @param {OverscaledTileID} tileID the key to be looked-up\n * @returns {boolean} whether the cache has this value\n * @private\n */\n has(tileID: OverscaledTileID): boolean {\n return tileID.wrapped().key in this.data;\n }\n\n /**\n * Get the value attached to a specific key and remove data from cache.\n * If the key is not found, returns `null`\n *\n * @param {OverscaledTileID} tileID the key to look up\n * @returns {*} the data, or null if it isn't found\n * @private\n */\n getAndRemove(tileID: OverscaledTileID): ?Tile {\n if (!this.has(tileID)) { return null; }\n return this._getAndRemoveByKey(tileID.wrapped().key);\n }\n\n /*\n * Get and remove the value with the specified key.\n */\n _getAndRemoveByKey(key: number): ?Tile {\n const data = this.data[key].shift();\n if (data.timeout) clearTimeout(data.timeout);\n\n if (this.data[key].length === 0) {\n delete this.data[key];\n }\n this.order.splice(this.order.indexOf(key), 1);\n\n return data.value;\n }\n\n /*\n * Get the value with the specified (wrapped tile) key.\n */\n getByKey(key: number): ?Tile {\n const data = this.data[key];\n return data ? data[0].value : null;\n }\n\n /**\n * Get the value attached to a specific key without removing data\n * from the cache. If the key is not found, returns `null`\n *\n * @param {OverscaledTileID} tileID the key to look up\n * @returns {*} the data, or null if it isn't found\n * @private\n */\n get(tileID: OverscaledTileID): ?Tile {\n if (!this.has(tileID)) { return null; }\n\n const data = this.data[tileID.wrapped().key][0];\n return data.value;\n }\n\n /**\n * Remove a key/value combination from the cache.\n *\n * @param {OverscaledTileID} tileID the key for the pair to delete\n * @param {Tile} value If a value is provided, remove that exact version of the value.\n * @returns {TileCache} this cache\n * @private\n */\n remove(tileID: OverscaledTileID, value: ?{ value: Tile, timeout: ?TimeoutID}): this {\n if (!this.has(tileID)) { return this; }\n const key = tileID.wrapped().key;\n\n const dataIndex = value === undefined ? 0 : this.data[key].indexOf(value);\n const data = this.data[key][dataIndex];\n this.data[key].splice(dataIndex, 1);\n if (data.timeout) clearTimeout(data.timeout);\n if (this.data[key].length === 0) {\n delete this.data[key];\n }\n this.onRemove(data.value);\n this.order.splice(this.order.indexOf(key), 1);\n\n return this;\n }\n\n /**\n * Change the max size of the cache.\n *\n * @param {number} max the max size of the cache\n * @returns {TileCache} this cache\n * @private\n */\n setMaxSize(max: number): TileCache {\n this.max = max;\n\n while (this.order.length > this.max) {\n const removedData = this._getAndRemoveByKey(this.order[0]);\n if (removedData) this.onRemove(removedData);\n }\n\n return this;\n }\n\n /**\n * Remove entries that do not pass a filter function. Used for removing\n * stale tiles from the cache.\n *\n * @private\n * @param {function} filterFn Determines whether the tile is filtered. If the supplied function returns false, the tile will be filtered out.\n */\n filter(filterFn: (tile: Tile) => boolean) {\n const removed = [];\n for (const key in this.data) {\n for (const entry of this.data[key]) {\n if (!filterFn(entry.value)) {\n removed.push(entry);\n }\n }\n }\n for (const r of removed) {\n this.remove(r.value.tileID, r);\n }\n }\n}\n\nexport default TileCache;\n","// @flow\nimport Color from '../style-spec/util/color.js';\n\nimport type {BlendFuncType, ColorMaskType} from './types.js';\n\nconst ZERO = 0x0000;\nconst ONE = 0x0001;\nconst ONE_MINUS_SRC_ALPHA = 0x0303;\n\nclass ColorMode {\n blendFunction: BlendFuncType;\n blendColor: Color;\n mask: ColorMaskType;\n\n constructor(blendFunction: BlendFuncType, blendColor: Color, mask: ColorMaskType) {\n this.blendFunction = blendFunction;\n this.blendColor = blendColor;\n this.mask = mask;\n }\n\n static Replace: BlendFuncType;\n\n static disabled: $ReadOnly<ColorMode>;\n static unblended: $ReadOnly<ColorMode>;\n static alphaBlended: $ReadOnly<ColorMode>;\n}\n\nColorMode.Replace = [ONE, ZERO];\n\nColorMode.disabled = new ColorMode(ColorMode.Replace, Color.transparent, [false, false, false, false]);\nColorMode.unblended = new ColorMode(ColorMode.Replace, Color.transparent, [true, true, true, true]);\nColorMode.alphaBlended = new ColorMode([ONE, ONE_MINUS_SRC_ALPHA], Color.transparent, [true, true, true, true]);\n\nexport default ColorMode;\n","// @flow\n\nimport Tile from './tile.js';\nimport {Event, ErrorEvent, Evented} from '../util/evented.js';\nimport TileCache from './tile_cache.js';\nimport {asyncAll, keysDifference, values, clamp} from '../util/util.js';\nimport Context from '../gl/context.js';\nimport Point from '@mapbox/point-geometry';\nimport browser from '../util/browser.js';\nimport {OverscaledTileID, CanonicalTileID} from './tile_id.js';\nimport assert from 'assert';\nimport SourceFeatureState from './source_state.js';\nimport {mercatorXfromLng} from '../geo/mercator_coordinate.js';\n\nimport type {Source} from './source.js';\nimport type {SourceSpecification} from '../style-spec/types.js';\nimport type {default as MapboxMap} from '../ui/map.js';\nimport type Style from '../style/style.js';\nimport type Transform from '../geo/transform.js';\nimport type {TileState} from './tile.js';\nimport type {Callback} from '../types/callback.js';\nimport type {FeatureStates} from './source_state.js';\nimport type {QueryGeometry, TilespaceQueryGeometry} from '../style/query_geometry.js';\n\n/**\n * `SourceCache` is responsible for\n *\n * - creating an instance of `Source`\n * - forwarding events from `Source`\n * - caching tiles loaded from an instance of `Source`\n * - loading the tiles needed to render a given viewport\n * - unloading the cached tiles not needed to render a given viewport\n *\n * @private\n */\nclass SourceCache extends Evented {\n id: string;\n map: MapboxMap;\n style: Style;\n\n _source: Source;\n _sourceLoaded: boolean;\n _sourceErrored: boolean;\n _tiles: {[_: string | number]: Tile};\n _prevLng: number | void;\n _cache: TileCache;\n _timers: {[_: any]: TimeoutID};\n _cacheTimers: {[_: any]: TimeoutID};\n _minTileCacheSize: ?number;\n _maxTileCacheSize: ?number;\n _paused: boolean;\n _isRaster: boolean;\n _shouldReloadOnResume: boolean;\n _coveredTiles: {[_: number | string]: boolean};\n transform: Transform;\n used: boolean;\n usedForTerrain: boolean;\n _state: SourceFeatureState;\n _loadedParentTiles: {[_: number | string]: ?Tile};\n _onlySymbols: ?boolean;\n\n static maxUnderzooming: number;\n static maxOverzooming: number;\n\n constructor(id: string, source: Source, onlySymbols?: boolean) {\n super();\n this.id = id;\n this._onlySymbols = onlySymbols;\n\n source.on('data', (e) => {\n // this._sourceLoaded signifies that the TileJSON is loaded if applicable.\n // if the source type does not come with a TileJSON, the flag signifies the\n // source data has loaded (in other words, GeoJSON has been tiled on the worker and is ready)\n if (e.dataType === 'source' && e.sourceDataType === 'metadata') this._sourceLoaded = true;\n\n // for sources with mutable data, this event fires when the underlying data\n // to a source is changed (for example, using [GeoJSONSource#setData](https://docs.mapbox.com/mapbox-gl-js/api/sources/#geojsonsource#setdata) or [ImageSource#setCoordinates](https://docs.mapbox.com/mapbox-gl-js/api/sources/#imagesource#setcoordinates))\n if (this._sourceLoaded && !this._paused && e.dataType === \"source\" && e.sourceDataType === 'content') {\n this.reload();\n if (this.transform) {\n this.update(this.transform);\n }\n }\n });\n\n source.on('error', () => {\n this._sourceErrored = true;\n });\n\n this._source = source;\n this._tiles = {};\n // $FlowFixMe[method-unbinding]\n this._cache = new TileCache(0, this._unloadTile.bind(this));\n this._timers = {};\n this._cacheTimers = {};\n this._minTileCacheSize = source.minTileCacheSize;\n this._maxTileCacheSize = source.maxTileCacheSize;\n this._loadedParentTiles = {};\n\n this._coveredTiles = {};\n this._state = new SourceFeatureState();\n this._isRaster =\n this._source.type === 'raster' ||\n this._source.type === 'raster-dem' ||\n // $FlowFixMe[prop-missing]\n (this._source.type === 'custom' && this._source._dataType === 'raster');\n }\n\n onAdd(map: MapboxMap) {\n this.map = map;\n this._minTileCacheSize = this._minTileCacheSize === undefined && map ? map._minTileCacheSize : this._minTileCacheSize;\n this._maxTileCacheSize = this._maxTileCacheSize === undefined && map ? map._maxTileCacheSize : this._maxTileCacheSize;\n }\n\n /**\n * Return true if no tile data is pending, tiles will not change unless\n * an additional API call is received.\n * @private\n */\n loaded(): boolean {\n if (this._sourceErrored) { return true; }\n if (!this._sourceLoaded) { return false; }\n if (!this._source.loaded()) { return false; }\n for (const t in this._tiles) {\n const tile = this._tiles[t];\n if (tile.state !== 'loaded' && tile.state !== 'errored')\n return false;\n }\n return true;\n }\n\n getSource(): Source {\n return this._source;\n }\n\n pause() {\n this._paused = true;\n }\n\n resume() {\n if (!this._paused) return;\n const shouldReload = this._shouldReloadOnResume;\n this._paused = false;\n this._shouldReloadOnResume = false;\n if (shouldReload) this.reload();\n if (this.transform) this.update(this.transform);\n }\n\n _loadTile(tile: Tile, callback: Callback<void>): void {\n tile.isSymbolTile = this._onlySymbols;\n return this._source.loadTile(tile, callback);\n }\n\n _unloadTile(tile: Tile): void {\n if (this._source.unloadTile)\n return this._source.unloadTile(tile, () => {});\n }\n\n _abortTile(tile: Tile): void {\n if (this._source.abortTile)\n return this._source.abortTile(tile, () => {});\n }\n\n serialize(): SourceSpecification {\n return this._source.serialize();\n }\n\n prepare(context: Context) {\n if (this._source.prepare) {\n this._source.prepare();\n }\n\n this._state.coalesceChanges(this._tiles, this.map ? this.map.painter : null);\n\n for (const i in this._tiles) {\n const tile = this._tiles[i];\n tile.upload(context);\n tile.prepare(this.map.style.imageManager);\n }\n }\n\n /**\n * Return all tile ids ordered with z-order, and cast to numbers\n * @private\n */\n getIds(): Array<number> {\n return values((this._tiles: any)).map((tile: Tile) => tile.tileID).sort(compareTileId).map(id => id.key);\n }\n\n getRenderableIds(symbolLayer?: boolean): Array<number> {\n const renderables: Array<Tile> = [];\n for (const id in this._tiles) {\n if (this._isIdRenderable(+id, symbolLayer)) renderables.push(this._tiles[id]);\n }\n if (symbolLayer) {\n return renderables.sort((a_: Tile, b_: Tile) => {\n const a = a_.tileID;\n const b = b_.tileID;\n const rotatedA = (new Point(a.canonical.x, a.canonical.y))._rotate(this.transform.angle);\n const rotatedB = (new Point(b.canonical.x, b.canonical.y))._rotate(this.transform.angle);\n return a.overscaledZ - b.overscaledZ || rotatedB.y - rotatedA.y || rotatedB.x - rotatedA.x;\n }).map(tile => tile.tileID.key);\n }\n return renderables.map(tile => tile.tileID).sort(compareTileId).map(id => id.key);\n }\n\n hasRenderableParent(tileID: OverscaledTileID): boolean {\n const parentTile = this.findLoadedParent(tileID, 0);\n if (parentTile) {\n return this._isIdRenderable(parentTile.tileID.key);\n }\n return false;\n }\n\n _isIdRenderable(id: number, symbolLayer?: boolean): boolean {\n return this._tiles[id] && this._tiles[id].hasData() &&\n !this._coveredTiles[id] && (symbolLayer || !this._tiles[id].holdingForFade());\n }\n\n reload() {\n if (this._paused) {\n this._shouldReloadOnResume = true;\n return;\n }\n\n this._cache.reset();\n\n for (const i in this._tiles) {\n if (this._tiles[i].state !== \"errored\") this._reloadTile(+i, 'reloading');\n }\n }\n\n _reloadTile(id: number, state: TileState) {\n const tile = this._tiles[id];\n\n // this potentially does not address all underlying\n // issues https://github.com/mapbox/mapbox-gl-js/issues/4252\n // - hard to tell without repro steps\n if (!tile) return;\n\n // The difference between \"loading\" tiles and \"reloading\" or \"expired\"\n // tiles is that \"reloading\"/\"expired\" tiles are \"renderable\".\n // Therefore, a \"loading\" tile cannot become a \"reloading\" tile without\n // first becoming a \"loaded\" tile.\n if (tile.state !== 'loading') {\n tile.state = state;\n }\n\n // $FlowFixMe[method-unbinding]\n this._loadTile(tile, this._tileLoaded.bind(this, tile, id, state));\n }\n\n _tileLoaded(tile: Tile, id: number, previousState: TileState, err: ?Error) {\n if (err) {\n tile.state = 'errored';\n if ((err: any).status !== 404) this._source.fire(new ErrorEvent(err, {tile}));\n else {\n // continue to try loading parent/children tiles if a tile doesn't exist (404)\n const updateForTerrain = this._source.type === 'raster-dem' && this.usedForTerrain;\n if (updateForTerrain && this.map.painter.terrain) {\n const terrain = this.map.painter.terrain;\n this.update(this.transform, terrain.getScaledDemTileSize(), true);\n terrain.resetTileLookupCache(this.id);\n } else {\n this.update(this.transform);\n }\n }\n return;\n }\n\n tile.timeAdded = browser.now();\n if (previousState === 'expired') tile.refreshedUponExpiration = true;\n this._setTileReloadTimer(id, tile);\n if (this._source.type === 'raster-dem' && tile.dem) this._backfillDEM(tile);\n this._state.initializeTileState(tile, this.map ? this.map.painter : null);\n\n this._source.fire(new Event('data', {dataType: 'source', tile, coord: tile.tileID, 'sourceCacheId': this.id}));\n }\n\n /**\n * For raster terrain source, backfill DEM to eliminate visible tile boundaries\n * @private\n */\n _backfillDEM(tile: Tile) {\n const renderables = this.getRenderableIds();\n for (let i = 0; i < renderables.length; i++) {\n const borderId = renderables[i];\n if (tile.neighboringTiles && tile.neighboringTiles[borderId]) {\n const borderTile = this.getTileByID(borderId);\n fillBorder(tile, borderTile);\n fillBorder(borderTile, tile);\n }\n }\n\n function fillBorder(tile: Tile, borderTile: Tile) {\n if (!tile.dem || tile.dem.borderReady) return;\n tile.needsHillshadePrepare = true;\n tile.needsDEMTextureUpload = true;\n let dx = borderTile.tileID.canonical.x - tile.tileID.canonical.x;\n const dy = borderTile.tileID.canonical.y - tile.tileID.canonical.y;\n const dim = Math.pow(2, tile.tileID.canonical.z);\n const borderId = borderTile.tileID.key;\n if (dx === 0 && dy === 0) return;\n\n if (Math.abs(dy) > 1) {\n return;\n }\n if (Math.abs(dx) > 1) {\n // Adjust the delta coordinate for world wraparound.\n if (Math.abs(dx + dim) === 1) {\n dx += dim;\n } else if (Math.abs(dx - dim) === 1) {\n dx -= dim;\n }\n }\n if (!borderTile.dem || !tile.dem) return;\n tile.dem.backfillBorder(borderTile.dem, dx, dy);\n if (tile.neighboringTiles && tile.neighboringTiles[borderId])\n tile.neighboringTiles[borderId].backfilled = true;\n }\n }\n /**\n * Get a specific tile by TileID\n * @private\n */\n getTile(tileID: OverscaledTileID): Tile {\n return this.getTileByID(tileID.key);\n }\n\n /**\n * Get a specific tile by id\n * @private\n */\n getTileByID(id: number): Tile {\n return this._tiles[id];\n }\n\n /**\n * For a given set of tiles, retain children that are loaded and have a zoom\n * between `zoom` (exclusive) and `maxCoveringZoom` (inclusive)\n * @private\n */\n _retainLoadedChildren(\n idealTiles: {[number | string]: OverscaledTileID},\n zoom: number,\n maxCoveringZoom: number,\n retain: {[number | string]: OverscaledTileID}\n ) {\n for (const id in this._tiles) {\n let tile = this._tiles[id];\n\n // only consider renderable tiles up to maxCoveringZoom\n if (retain[id] ||\n !tile.hasData() ||\n tile.tileID.overscaledZ <= zoom ||\n tile.tileID.overscaledZ > maxCoveringZoom\n ) continue;\n\n // loop through parents and retain the topmost loaded one if found\n let topmostLoadedID = tile.tileID;\n while (tile && tile.tileID.overscaledZ > zoom + 1) {\n const parentID = tile.tileID.scaledTo(tile.tileID.overscaledZ - 1);\n\n tile = this._tiles[parentID.key];\n\n if (tile && tile.hasData()) {\n topmostLoadedID = parentID;\n }\n }\n\n // loop through ancestors of the topmost loaded child to see if there's one that needed it\n let tileID = topmostLoadedID;\n while (tileID.overscaledZ > zoom) {\n tileID = tileID.scaledTo(tileID.overscaledZ - 1);\n\n if (idealTiles[tileID.key]) {\n // found a parent that needed a loaded child; retain that child\n retain[topmostLoadedID.key] = topmostLoadedID;\n break;\n }\n }\n }\n }\n\n /**\n * Find a loaded parent of the given tile (up to minCoveringZoom)\n * @private\n */\n findLoadedParent(tileID: OverscaledTileID, minCoveringZoom: number): ?Tile {\n if (tileID.key in this._loadedParentTiles) {\n const parent = this._loadedParentTiles[tileID.key];\n if (parent && parent.tileID.overscaledZ >= minCoveringZoom) {\n return parent;\n } else {\n return null;\n }\n }\n for (let z = tileID.overscaledZ - 1; z >= minCoveringZoom; z--) {\n const parentTileID = tileID.scaledTo(z);\n const tile = this._getLoadedTile(parentTileID);\n if (tile) {\n return tile;\n }\n }\n }\n\n _getLoadedTile(tileID: OverscaledTileID): ?Tile {\n const tile = this._tiles[tileID.key];\n if (tile && tile.hasData()) {\n return tile;\n }\n // TileCache ignores wrap in lookup.\n const cachedTile = this._cache.getByKey(this._source.reparseOverscaled ? tileID.wrapped().key : tileID.canonical.key);\n return cachedTile;\n }\n\n /**\n * Resizes the tile cache based on the current viewport's size\n * or the minTileCacheSize and maxTileCacheSize options passed during map creation\n *\n * Larger viewports use more tiles and need larger caches. Larger viewports\n * are more likely to be found on devices with more memory and on pages where\n * the map is more important.\n * @private\n */\n updateCacheSize(transform: Transform, tileSize?: number) {\n tileSize = tileSize || this._source.tileSize;\n const widthInTiles = Math.ceil(transform.width / tileSize) + 1;\n const heightInTiles = Math.ceil(transform.height / tileSize) + 1;\n const approxTilesInView = widthInTiles * heightInTiles;\n const commonZoomRange = 5;\n\n const viewDependentMaxSize = Math.floor(approxTilesInView * commonZoomRange);\n const minSize = typeof this._minTileCacheSize === 'number' ? Math.max(this._minTileCacheSize, viewDependentMaxSize) : viewDependentMaxSize;\n const maxSize = typeof this._maxTileCacheSize === 'number' ? Math.min(this._maxTileCacheSize, minSize) : minSize;\n\n this._cache.setMaxSize(maxSize);\n }\n\n handleWrapJump(lng: number) {\n // On top of the regular z/x/y values, TileIDs have a `wrap` value that specify\n // which copy of the world the tile belongs to. For example, at `lng: 10` you\n // might render z/x/y/0 while at `lng: 370` you would render z/x/y/1.\n //\n // When lng values get wrapped (going from `lng: 370` to `long: 10`) you expect\n // to see the same thing on the screen (370 degrees and 10 degrees is the same\n // place in the world) but all the TileIDs will have different wrap values.\n //\n // In order to make this transition seamless, we calculate the rounded difference of\n // \"worlds\" between the last frame and the current frame. If the map panned by\n // a world, then we can assign all the tiles new TileIDs with updated wrap values.\n // For example, assign z/x/y/1 a new id: z/x/y/0. It is the same tile, just rendered\n // in a different position.\n //\n // This enables us to reuse the tiles at more ideal locations and prevent flickering.\n const prevLng = this._prevLng === undefined ? lng : this._prevLng;\n const lngDifference = lng - prevLng;\n const worldDifference = lngDifference / 360;\n const wrapDelta = Math.round(worldDifference);\n this._prevLng = lng;\n\n if (wrapDelta) {\n const tiles: {[_: string | number]: Tile} = {};\n for (const key in this._tiles) {\n const tile = this._tiles[key];\n tile.tileID = tile.tileID.unwrapTo(tile.tileID.wrap + wrapDelta);\n tiles[tile.tileID.key] = tile;\n }\n this._tiles = tiles;\n\n // Reset tile reload timers\n for (const id in this._timers) {\n clearTimeout(this._timers[id]);\n delete this._timers[id];\n }\n for (const id in this._tiles) {\n const tile = this._tiles[id];\n this._setTileReloadTimer(+id, tile);\n }\n }\n }\n\n /**\n * Removes tiles that are outside the viewport and adds new tiles that\n * are inside the viewport.\n * @private\n * @param {boolean} updateForTerrain Signals to update tiles even if the\n * source is not used (this.used) by layers: it is used for terrain.\n * @param {tileSize} tileSize If needed to get lower resolution ideal cover,\n * override source.tileSize used in tile cover calculation.\n */\n update(transform: Transform, tileSize?: number, updateForTerrain?: boolean) {\n this.transform = transform;\n if (!this._sourceLoaded || this._paused || this.transform.freezeTileCoverage) { return; }\n assert(!(updateForTerrain && !this.usedForTerrain));\n if (this.usedForTerrain && !updateForTerrain) {\n // If source is used for both terrain and hillshade, don't update it twice.\n return;\n }\n\n this.updateCacheSize(transform, tileSize);\n if (this.transform.projection.name !== 'globe') {\n this.handleWrapJump(this.transform.center.lng);\n }\n\n // Covered is a list of retained tiles who's areas are fully covered by other,\n // better, retained tiles. They are not drawn separately.\n this._coveredTiles = {};\n\n let idealTileIDs;\n if (!this.used && !this.usedForTerrain) {\n idealTileIDs = [];\n } else if (this._source.tileID) {\n idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID)\n .map((unwrapped) => new OverscaledTileID(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y));\n } else {\n idealTileIDs = transform.coveringTiles({\n tileSize: tileSize || this._source.tileSize,\n minzoom: this._source.minzoom,\n maxzoom: this._source.maxzoom,\n roundZoom: this._source.roundZoom && !updateForTerrain,\n reparseOverscaled: this._source.reparseOverscaled,\n isTerrainDEM: this.usedForTerrain\n });\n\n if (this._source.hasTile) {\n idealTileIDs = idealTileIDs.filter((coord) => (this._source.hasTile: any)(coord));\n }\n }\n\n // Retain is a list of tiles that we shouldn't delete, even if they are not\n // the most ideal tile for the current viewport. This may include tiles like\n // parent or child tiles that are *already* loaded.\n const retain = this._updateRetainedTiles(idealTileIDs);\n\n if (isRasterType(this._source.type) && idealTileIDs.length !== 0) {\n const parentsForFading: {[_: string | number]: OverscaledTileID} = {};\n const fadingTiles = {};\n const ids = Object.keys(retain);\n for (const id of ids) {\n const tileID = retain[id];\n assert(tileID.key === +id);\n\n const tile = this._tiles[id];\n if (!tile || (tile.fadeEndTime && tile.fadeEndTime <= browser.now())) continue;\n\n // if the tile is loaded but still fading in, find parents to cross-fade with it\n const parentTile = this.findLoadedParent(tileID, Math.max(tileID.overscaledZ - SourceCache.maxOverzooming, this._source.minzoom));\n if (parentTile) {\n this._addTile(parentTile.tileID);\n parentsForFading[parentTile.tileID.key] = parentTile.tileID;\n }\n\n fadingTiles[id] = tileID;\n }\n\n // for children tiles with parent tiles still fading in,\n // retain the children so the parent can fade on top\n const minZoom = idealTileIDs[idealTileIDs.length - 1].overscaledZ;\n for (const id in this._tiles) {\n const childTile = this._tiles[id];\n if (retain[id] || !childTile.hasData()) {\n continue;\n }\n\n let parentID = childTile.tileID;\n while (parentID.overscaledZ > minZoom) {\n parentID = parentID.scaledTo(parentID.overscaledZ - 1);\n const tile = this._tiles[parentID.key];\n if (tile && tile.hasData() && fadingTiles[parentID.key]) {\n retain[id] = childTile.tileID;\n break;\n }\n }\n }\n\n for (const id in parentsForFading) {\n if (!retain[id]) {\n // If a tile is only needed for fading, mark it as covered so that it isn't rendered on it's own.\n this._coveredTiles[id] = true;\n retain[id] = parentsForFading[id];\n }\n }\n }\n\n for (const retainedId in retain) {\n // Make sure retained tiles always clear any existing fade holds\n // so that if they're removed again their fade timer starts fresh.\n this._tiles[retainedId].clearFadeHold();\n }\n\n // Remove the tiles we don't need anymore.\n const remove = keysDifference((this._tiles: any), (retain: any));\n for (const tileID of remove) {\n const tile = this._tiles[tileID];\n if (tile.hasSymbolBuckets && !tile.holdingForFade()) {\n tile.setHoldDuration(this.map._fadeDuration);\n } else if (!tile.hasSymbolBuckets || tile.symbolFadeFinished()) {\n this._removeTile(+tileID);\n }\n }\n\n // Construct a cache of loaded parents\n this._updateLoadedParentTileCache();\n\n if (this._onlySymbols && this._source.afterUpdate) {\n this._source.afterUpdate();\n }\n }\n\n releaseSymbolFadeTiles() {\n for (const id in this._tiles) {\n if (this._tiles[id].holdingForFade()) {\n this._removeTile(+id);\n }\n }\n }\n\n _updateRetainedTiles(idealTileIDs: Array<OverscaledTileID>): {[_: number | string]: OverscaledTileID} {\n const retain: {[_: number | string]: OverscaledTileID} = {};\n if (idealTileIDs.length === 0) { return retain; }\n\n const checked: {[_: number | string]: boolean } = {};\n const minZoom = idealTileIDs.reduce((min, id) => Math.min(min, id.overscaledZ), Infinity);\n const maxZoom = idealTileIDs[0].overscaledZ;\n assert(minZoom <= maxZoom);\n const minCoveringZoom = Math.max(maxZoom - SourceCache.maxOverzooming, this._source.minzoom);\n const maxCoveringZoom = Math.max(maxZoom + SourceCache.maxUnderzooming, this._source.minzoom);\n\n const missingTiles = {};\n for (const tileID of idealTileIDs) {\n const tile = this._addTile(tileID);\n\n // retain the tile even if it's not loaded because it's an ideal tile.\n retain[tileID.key] = tileID;\n\n if (tile.hasData()) continue;\n\n if (minZoom < this._source.maxzoom) {\n // save missing tiles that potentially have loaded children\n missingTiles[tileID.key] = tileID;\n }\n }\n\n // retain any loaded children of ideal tiles up to maxCoveringZoom\n this._retainLoadedChildren(missingTiles, minZoom, maxCoveringZoom, retain);\n\n for (const tileID of idealTileIDs) {\n let tile = this._tiles[tileID.key];\n\n if (tile.hasData()) continue;\n\n // The tile we require is not yet loaded or does not exist;\n // Attempt to find children that fully cover it.\n\n if (tileID.canonical.z >= this._source.maxzoom) {\n // We're looking for an overzoomed child tile.\n const childCoord = tileID.children(this._source.maxzoom)[0];\n const childTile = this.getTile(childCoord);\n if (!!childTile && childTile.hasData()) {\n retain[childCoord.key] = childCoord;\n continue; // tile is covered by overzoomed child\n }\n } else {\n // Check if all 4 immediate children are loaded (in other words, the missing ideal tile is covered)\n const children = tileID.children(this._source.maxzoom);\n\n if (retain[children[0].key] &&\n retain[children[1].key] &&\n retain[children[2].key] &&\n retain[children[3].key]) continue; // tile is covered by children\n }\n\n // We couldn't find child tiles that entirely cover the ideal tile; look for parents now.\n\n // As we ascend up the tile pyramid of the ideal tile, we check whether the parent\n // tile has been previously requested (and errored because we only loop over tiles with no data)\n // in order to determine if we need to request its parent.\n let parentWasRequested = tile.wasRequested();\n\n for (let overscaledZ = tileID.overscaledZ - 1; overscaledZ >= minCoveringZoom; --overscaledZ) {\n const parentId = tileID.scaledTo(overscaledZ);\n\n // Break parent tile ascent if this route has been previously checked by another child.\n if (checked[parentId.key]) break;\n checked[parentId.key] = true;\n\n tile = this.getTile(parentId);\n if (!tile && parentWasRequested) {\n tile = this._addTile(parentId);\n }\n if (tile) {\n retain[parentId.key] = parentId;\n // Save the current values, since they're the parent of the next iteration\n // of the parent tile ascent loop.\n parentWasRequested = tile.wasRequested();\n if (tile.hasData()) break;\n }\n }\n }\n\n return retain;\n }\n\n _updateLoadedParentTileCache() {\n this._loadedParentTiles = {};\n\n for (const tileKey in this._tiles) {\n const path = [];\n let parentTile: ?Tile;\n let currentId = this._tiles[tileKey].tileID;\n\n // Find the closest loaded ancestor by traversing the tile tree towards the root and\n // caching results along the way\n while (currentId.overscaledZ > 0) {\n\n // Do we have a cached result from previous traversals?\n if (currentId.key in this._loadedParentTiles) {\n parentTile = this._loadedParentTiles[currentId.key];\n break;\n }\n\n path.push(currentId.key);\n\n // Is the parent loaded?\n const parentId = currentId.scaledTo(currentId.overscaledZ - 1);\n parentTile = this._getLoadedTile(parentId);\n if (parentTile) {\n break;\n }\n\n currentId = parentId;\n }\n\n // Cache the result of this traversal to all newly visited tiles\n for (const key of path) {\n this._loadedParentTiles[key] = parentTile;\n }\n }\n }\n\n /**\n * Add a tile, given its coordinate, to the pyramid.\n * @private\n */\n _addTile(tileID: OverscaledTileID): Tile {\n let tile: ?Tile = this._tiles[tileID.key];\n if (tile) return tile;\n\n tile = this._cache.getAndRemove(tileID);\n if (tile) {\n this._setTileReloadTimer(tileID.key, tile);\n // set the tileID because the cached tile could have had a different wrap value\n tile.tileID = tileID;\n this._state.initializeTileState(tile, this.map ? this.map.painter : null);\n if (this._cacheTimers[tileID.key]) {\n clearTimeout(this._cacheTimers[tileID.key]);\n delete this._cacheTimers[tileID.key];\n this._setTileReloadTimer(tileID.key, tile);\n }\n }\n\n const cached = Boolean(tile);\n if (!cached) {\n const painter = this.map ? this.map.painter : null;\n tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor(), this.transform.tileZoom, painter, this._isRaster);\n // $FlowFixMe[method-unbinding]\n this._loadTile(tile, this._tileLoaded.bind(this, tile, tileID.key, tile.state));\n }\n\n // Impossible, but silence flow.\n if (!tile) return (null: any);\n\n tile.uses++;\n this._tiles[tileID.key] = tile;\n if (!cached) this._source.fire(new Event('dataloading', {tile, coord: tile.tileID, dataType: 'source'}));\n\n return tile;\n }\n\n _setTileReloadTimer(id: number, tile: Tile) {\n if (id in this._timers) {\n clearTimeout(this._timers[id]);\n delete this._timers[id];\n }\n\n const expiryTimeout = tile.getExpiryTimeout();\n if (expiryTimeout) {\n this._timers[id] = setTimeout(() => {\n this._reloadTile(id, 'expired');\n delete this._timers[id];\n }, expiryTimeout);\n }\n }\n\n /**\n * Remove a tile, given its id, from the pyramid\n * @private\n */\n _removeTile(id: number) {\n const tile = this._tiles[id];\n if (!tile)\n return;\n\n tile.uses--;\n delete this._tiles[id];\n if (this._timers[id]) {\n clearTimeout(this._timers[id]);\n delete this._timers[id];\n }\n\n if (tile.uses > 0)\n return;\n\n if (tile.hasData() && tile.state !== 'reloading') {\n this._cache.add(tile.tileID, tile, tile.getExpiryTimeout());\n } else {\n tile.aborted = true;\n this._abortTile(tile);\n this._unloadTile(tile);\n }\n }\n\n /**\n * Remove all tiles from this pyramid.\n * @private\n */\n clearTiles() {\n this._shouldReloadOnResume = false;\n this._paused = false;\n\n for (const id in this._tiles)\n this._removeTile(+id);\n\n if (this._source._clear) this._source._clear();\n\n this._cache.reset();\n\n if (this.map && this.usedForTerrain && this.map.painter.terrain) {\n this.map.painter.terrain.resetTileLookupCache(this.id);\n }\n }\n\n /**\n * Search through our current tiles and attempt to find the tiles that cover the given `queryGeometry`.\n *\n * @param {QueryGeometry} queryGeometry\n * @param {boolean} [visualizeQueryGeometry=false]\n * @param {boolean} use3DQuery\n * @returns\n * @private\n */\n tilesIn(queryGeometry: QueryGeometry, use3DQuery: boolean, visualizeQueryGeometry: boolean): TilespaceQueryGeometry[] {\n const tileResults = [];\n\n const transform = this.transform;\n if (!transform) return tileResults;\n\n const isGlobe = transform.projection.name === 'globe';\n const centerX = mercatorXfromLng(transform.center.lng);\n\n for (const tileID in this._tiles) {\n const tile = this._tiles[tileID];\n if (visualizeQueryGeometry) {\n tile.clearQueryDebugViz();\n }\n if (tile.holdingForFade()) {\n // Tiles held for fading are covered by tiles that are closer to ideal\n continue;\n }\n\n // An array of wrap values for the tile [-1, 0, 1]. The default value is 0 but -1 or 1 wrapping\n // might be required in globe view due to globe's surface being continuous.\n let tilesToCheck;\n\n if (isGlobe) {\n // Compare distances to copies of the tile to see if a wrapped one should be used.\n const id = tile.tileID.canonical;\n assert(tile.tileID.wrap === 0);\n\n if (id.z === 0) {\n // Render the zoom level 0 tile twice as the query polygon might span over the antimeridian\n const distances = [\n Math.abs(clamp(centerX, ...tileBoundsX(id, -1)) - centerX),\n Math.abs(clamp(centerX, ...tileBoundsX(id, 1)) - centerX)\n ];\n\n tilesToCheck = [0, distances.indexOf(Math.min(...distances)) * 2 - 1];\n } else {\n const distances = [\n Math.abs(clamp(centerX, ...tileBoundsX(id, -1)) - centerX),\n Math.abs(clamp(centerX, ...tileBoundsX(id, 0)) - centerX),\n Math.abs(clamp(centerX, ...tileBoundsX(id, 1)) - centerX)\n ];\n\n tilesToCheck = [distances.indexOf(Math.min(...distances)) - 1];\n }\n } else {\n tilesToCheck = [0];\n }\n\n for (const wrap of tilesToCheck) {\n const tileResult = queryGeometry.containsTile(tile, transform, use3DQuery, wrap);\n if (tileResult) {\n tileResults.push(tileResult);\n }\n }\n }\n return tileResults;\n }\n\n getVisibleCoordinates(symbolLayer?: boolean): Array<OverscaledTileID> {\n const coords = this.getRenderableIds(symbolLayer).map((id) => this._tiles[id].tileID);\n for (const coord of coords) {\n coord.projMatrix = this.transform.calculateProjMatrix(coord.toUnwrapped());\n }\n return coords;\n }\n\n hasTransition(): boolean {\n if (this._source.hasTransition()) {\n return true;\n }\n\n if (isRasterType(this._source.type)) {\n for (const id in this._tiles) {\n const tile = this._tiles[id];\n if (tile.fadeEndTime !== undefined && tile.fadeEndTime >= browser.now()) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Set the value of a particular state for a feature\n * @private\n */\n setFeatureState(sourceLayer?: string, featureId: number | string, state: Object) {\n sourceLayer = sourceLayer || '_geojsonTileLayer';\n this._state.updateState(sourceLayer, featureId, state);\n }\n\n /**\n * Resets the value of a particular state key for a feature\n * @private\n */\n removeFeatureState(sourceLayer?: string, featureId?: number | string, key?: string) {\n sourceLayer = sourceLayer || '_geojsonTileLayer';\n this._state.removeFeatureState(sourceLayer, featureId, key);\n }\n\n /**\n * Get the entire state object for a feature\n * @private\n */\n getFeatureState(sourceLayer?: string, featureId: number | string): FeatureStates {\n sourceLayer = sourceLayer || '_geojsonTileLayer';\n return this._state.getState(sourceLayer, featureId);\n }\n\n /**\n * Sets the set of keys that the tile depends on. This allows tiles to\n * be reloaded when their dependencies change.\n * @private\n */\n setDependencies(tileKey: number, namespace: string, dependencies: Array<string>) {\n const tile = this._tiles[tileKey];\n if (tile) {\n tile.setDependencies(namespace, dependencies);\n }\n }\n\n /**\n * Reloads all tiles that depend on the given keys.\n * @private\n */\n reloadTilesForDependencies(namespaces: Array<string>, keys: Array<string>) {\n for (const id in this._tiles) {\n const tile = this._tiles[id];\n if (tile.hasDependency(namespaces, keys)) {\n this._reloadTile(+id, 'reloading');\n }\n }\n this._cache.filter(tile => !tile.hasDependency(namespaces, keys));\n }\n\n /**\n * Preloads all tiles that will be requested for one or a series of transformations\n *\n * @private\n * @returns {Object} Returns `this` | Promise.\n */\n _preloadTiles(transform: Transform | Array<Transform>, callback: Callback<any>) {\n if (!this._sourceLoaded) {\n const waitUntilSourceLoaded = () => {\n if (!this._sourceLoaded) return;\n this._source.off('data', waitUntilSourceLoaded);\n this._preloadTiles(transform, callback);\n };\n\n this._source.on('data', waitUntilSourceLoaded);\n return;\n }\n\n const coveringTilesIDs: Map<number, OverscaledTileID> = new Map();\n const transforms = Array.isArray(transform) ? transform : [transform];\n\n const terrain = this.map.painter.terrain;\n const tileSize = this.usedForTerrain && terrain ? terrain.getScaledDemTileSize() : this._source.tileSize;\n\n for (const tr of transforms) {\n const tileIDs = tr.coveringTiles({\n tileSize,\n minzoom: this._source.minzoom,\n maxzoom: this._source.maxzoom,\n roundZoom: this._source.roundZoom && !this.usedForTerrain,\n reparseOverscaled: this._source.reparseOverscaled,\n isTerrainDEM: this.usedForTerrain\n });\n\n for (const tileID of tileIDs) {\n coveringTilesIDs.set(tileID.key, tileID);\n }\n\n if (this.usedForTerrain) {\n tr.updateElevation(false);\n }\n }\n\n const tileIDs = Array.from(coveringTilesIDs.values());\n\n asyncAll(tileIDs, (tileID, done) => {\n const tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor(), this.transform.tileZoom, this.map.painter, this._isRaster);\n this._loadTile(tile, (err) => {\n if (this._source.type === 'raster-dem' && tile.dem) this._backfillDEM(tile);\n done(err, tile);\n });\n }, callback);\n }\n}\n\nSourceCache.maxOverzooming = 10;\nSourceCache.maxUnderzooming = 3;\n\nfunction compareTileId(a: OverscaledTileID, b: OverscaledTileID): number {\n // Different copies of the world are sorted based on their distance to the center.\n // Wrap values are converted to unsigned distances by reserving odd number for copies\n // with negative wrap and even numbers for copies with positive wrap.\n const aWrap = Math.abs(a.wrap * 2) - +(a.wrap < 0);\n const bWrap = Math.abs(b.wrap * 2) - +(b.wrap < 0);\n return a.overscaledZ - b.overscaledZ || bWrap - aWrap || b.canonical.y - a.canonical.y || b.canonical.x - a.canonical.x;\n}\n\nfunction isRasterType(type: string): boolean {\n return type === 'raster' || type === 'image' || type === 'video' || type === 'custom';\n}\n\nfunction tileBoundsX(id: CanonicalTileID, wrap: number): [number, number] {\n const tiles = 1 << id.z;\n return [id.x / tiles + wrap, (id.x + 1) / tiles + wrap];\n}\n\nexport default SourceCache;\n","// @flow\n\nimport MercatorCoordinate, {mercatorZfromAltitude} from '../geo/mercator_coordinate.js';\nimport DEMData from '../data/dem_data.js';\nimport SourceCache from '../source/source_cache.js';\nimport {number as interpolate} from '../style-spec/util/interpolate.js';\nimport EXTENT from '../data/extent.js';\nimport {vec3} from 'gl-matrix';\nimport Point from '@mapbox/point-geometry';\nimport {OverscaledTileID} from '../source/tile_id.js';\n\nimport type Projection from '../geo/projection/projection.js';\nimport type Tile from '../source/tile.js';\nimport type {Vec3} from 'gl-matrix';\n\n/**\n * Options common to {@link Map#queryTerrainElevation} and {@link Map#unproject3d}, used to control how elevation\n * data is returned.\n *\n * @typedef {Object} ElevationQueryOptions\n * @property {boolean} exaggerated When set to `true` returns the value of the elevation with the terrains `exaggeration` on the style already applied,\n * when`false` it returns the raw value of the underlying data without styling applied.\n */\nexport type ElevationQueryOptions = {\n exaggerated: boolean\n};\n\n/**\n * Provides access to elevation data from raster-dem source cache.\n */\nexport class Elevation {\n\n /**\n * Helper that checks whether DEM data is available at a given mercator coordinate.\n * @param {MercatorCoordinate} point Mercator coordinate of the point to check against.\n * @returns {boolean} `true` indicating whether the data is available at `point`, and `false` otherwise.\n */\n isDataAvailableAtPoint(point: MercatorCoordinate): boolean {\n const sourceCache = this._source();\n if (this.isUsingMockSource() || !sourceCache || point.y < 0.0 || point.y > 1.0) {\n return false;\n }\n\n const cache: SourceCache = sourceCache;\n const z = cache.getSource().maxzoom;\n const tiles = 1 << z;\n const wrap = Math.floor(point.x);\n const px = point.x - wrap;\n const x = Math.floor(px * tiles);\n const y = Math.floor(point.y * tiles);\n const demTile = this.findDEMTileFor(new OverscaledTileID(z, wrap, z, x, y));\n\n return !!(demTile && demTile.dem);\n }\n\n /**\n * Helper around `getAtPoint` that guarantees that a numeric value is returned.\n * @param {MercatorCoordinate} point Mercator coordinate of the point.\n * @param {number} defaultIfNotLoaded Value that is returned if the dem tile of the provided point is not loaded.\n * @returns {number} Altitude in meters.\n */\n getAtPointOrZero(point: MercatorCoordinate, defaultIfNotLoaded: number = 0): number {\n return this.getAtPoint(point, defaultIfNotLoaded) || 0;\n }\n\n /**\n * Altitude above sea level in meters at specified point.\n * @param {MercatorCoordinate} point Mercator coordinate of the point.\n * @param {number} defaultIfNotLoaded Value that is returned if the DEM tile of the provided point is not loaded.\n * @param {boolean} exaggerated `true` if styling exaggeration should be applied to the resulting elevation.\n * @returns {number} Altitude in meters.\n * If there is no loaded tile that carries information for the requested\n * point elevation, returns `defaultIfNotLoaded`.\n * Doesn't invoke network request to fetch the data.\n */\n getAtPoint(point: MercatorCoordinate, defaultIfNotLoaded: ?number, exaggerated: boolean = true): ?number {\n if (this.isUsingMockSource()) {\n return null;\n }\n\n // Force a cast to null for both null and undefined\n if (defaultIfNotLoaded == null) defaultIfNotLoaded = null;\n\n const src = this._source();\n if (!src) return defaultIfNotLoaded;\n if (point.y < 0.0 || point.y > 1.0) {\n return defaultIfNotLoaded;\n }\n const cache: SourceCache = src;\n const z = cache.getSource().maxzoom;\n const tiles = 1 << z;\n const wrap = Math.floor(point.x);\n const px = point.x - wrap;\n const tileID = new OverscaledTileID(z, wrap, z, Math.floor(px * tiles), Math.floor(point.y * tiles));\n const demTile = this.findDEMTileFor(tileID);\n if (!(demTile && demTile.dem)) { return defaultIfNotLoaded; }\n const dem: DEMData = demTile.dem;\n const tilesAtTileZoom = 1 << demTile.tileID.canonical.z;\n const x = (px * tilesAtTileZoom - demTile.tileID.canonical.x) * dem.dim;\n const y = (point.y * tilesAtTileZoom - demTile.tileID.canonical.y) * dem.dim;\n const i = Math.floor(x);\n const j = Math.floor(y);\n const exaggeration = exaggerated ? this.exaggeration() : 1;\n\n return exaggeration * interpolate(\n interpolate(dem.get(i, j), dem.get(i, j + 1), y - j),\n interpolate(dem.get(i + 1, j), dem.get(i + 1, j + 1), y - j),\n x - i);\n }\n\n /*\n * x and y are offset within tile, in 0 .. EXTENT coordinate space.\n */\n getAtTileOffset(tileID: OverscaledTileID, x: number, y: number): number {\n const tilesAtTileZoom = 1 << tileID.canonical.z;\n return this.getAtPointOrZero(new MercatorCoordinate(\n tileID.wrap + (tileID.canonical.x + x / EXTENT) / tilesAtTileZoom,\n (tileID.canonical.y + y / EXTENT) / tilesAtTileZoom));\n }\n\n getAtTileOffsetFunc(tileID: OverscaledTileID, lat: number, worldSize: number, projection: Projection): Function {\n return (p => {\n const elevation = this.getAtTileOffset(tileID, p.x, p.y);\n const upVector = projection.upVector(tileID.canonical, p.x, p.y);\n const upVectorScale = projection.upVectorScale(tileID.canonical, lat, worldSize).metersToTile;\n // $FlowFixMe can't yet resolve tuple vs array incompatibilities\n vec3.scale(upVector, upVector, elevation * upVectorScale);\n return upVector;\n });\n }\n\n /*\n * Batch fetch for multiple tile points: points holds input and return value:\n * vec3's items on index 0 and 1 define x and y offset within tile, in [0 .. EXTENT]\n * range, respectively. vec3 item at index 2 is output value, in meters.\n * If a DEM tile that covers tileID is loaded, true is returned, otherwise false.\n * Nearest filter sampling on dem data is done (no interpolation).\n */\n getForTilePoints(tileID: OverscaledTileID, points: Array<Vec3>, interpolated: ?boolean, useDemTile: ?Tile): boolean {\n if (this.isUsingMockSource()) {\n return false;\n }\n\n const helper = DEMSampler.create(this, tileID, useDemTile);\n if (!helper) { return false; }\n\n points.forEach(p => {\n p[2] = this.exaggeration() * helper.getElevationAt(p[0], p[1], interpolated);\n });\n return true;\n }\n\n /**\n * Get elevation minimum and maximum for tile identified by `tileID`.\n * @param {OverscaledTileID} tileID The `tileId` is a sub tile (or covers the same space) of the DEM tile we read the information from.\n * @returns {?{min: number, max: number}} The min and max elevation.\n */\n getMinMaxForTile(tileID: OverscaledTileID): ?{min: number, max: number} {\n if (this.isUsingMockSource()) {\n return null;\n }\n\n const demTile = this.findDEMTileFor(tileID);\n\n if (!(demTile && demTile.dem)) {\n return null;\n }\n\n const dem: DEMData = demTile.dem;\n const tree = dem.tree;\n const demTileID = demTile.tileID;\n const scale = 1 << tileID.canonical.z - demTileID.canonical.z;\n let xOffset = tileID.canonical.x / scale - demTileID.canonical.x;\n let yOffset = tileID.canonical.y / scale - demTileID.canonical.y;\n let index = 0; // Start from DEM tree root.\n for (let i = 0; i < tileID.canonical.z - demTileID.canonical.z; i++) {\n if (tree.leaves[index]) break;\n xOffset *= 2;\n yOffset *= 2;\n const childOffset = 2 * Math.floor(yOffset) + Math.floor(xOffset);\n index = tree.childOffsets[index] + childOffset;\n xOffset = xOffset % 1;\n yOffset = yOffset % 1;\n }\n return {min: this.exaggeration() * tree.minimums[index], max: this.exaggeration() * tree.maximums[index]};\n }\n\n /**\n * Get elevation minimum below MSL for the visible tiles. This function accounts\n * for terrain exaggeration and is conservative based on the maximum DEM error,\n * do not expect accurate values from this function.\n * If no negative elevation is visible, this function returns 0.\n * @returns {number} The min elevation below sea level of all visible tiles.\n */\n getMinElevationBelowMSL(): number {\n throw new Error('Pure virtual method called.');\n }\n\n /**\n * Performs raycast against visible DEM tiles on the screen and returns the distance travelled along the ray.\n * `x` & `y` components of the position are expected to be in normalized mercator coordinates [0, 1] and z in meters.\n * @param {vec3} position The ray origin.\n * @param {vec3} dir The ray direction.\n * @param {number} exaggeration The terrain exaggeration.\n */\n raycast(position: Vec3, dir: Vec3, exaggeration: number): ?number {\n throw new Error('Pure virtual method called.');\n }\n\n /**\n * Given a point on screen, returns 3D MercatorCoordinate on terrain.\n * Helper function that wraps `raycast`.\n *\n * @param {Point} screenPoint Screen point in pixels in top-left origin coordinate system.\n * @returns {vec3} If there is intersection with terrain, returns 3D MercatorCoordinate's of\n * intersection, as vec3(x, y, z), otherwise null.\n */ /* eslint no-unused-vars: [\"error\", { \"args\": \"none\" }] */\n pointCoordinate(screenPoint: Point): ?Vec3 {\n throw new Error('Pure virtual method called.');\n }\n\n /*\n * Implementation provides SourceCache of raster-dem source type cache, in\n * order to access already loaded cached tiles.\n */\n _source(): ?SourceCache {\n throw new Error('Pure virtual method called.');\n }\n\n /*\n * Whether the SourceCache instance is a mock source cache.\n * This mock source cache is used solely for the Globe projection and with terrain disabled,\n * where we only want to leverage the draping rendering pipeline without incurring DEM-tile\n * download overhead. This function is useful to skip DEM processing as the mock data source\n * placeholder contains only 0 height.\n */\n isUsingMockSource(): boolean {\n throw new Error('Pure virtual method called.');\n }\n\n /*\n * A multiplier defined by style as terrain exaggeration. Elevation provided\n * by getXXXX methods is multiplied by this.\n */\n exaggeration(): number {\n throw new Error('Pure virtual method called.');\n }\n\n /**\n * Lookup DEM tile that corresponds to (covers) tileID.\n * @private\n */\n findDEMTileFor(_: OverscaledTileID): ?Tile {\n throw new Error('Pure virtual method called.');\n }\n\n /**\n * Get list of DEM tiles used to render current frame.\n * @private\n */\n get visibleDemTiles(): Array<Tile> {\n throw new Error('Getter must be implemented in subclass.');\n }\n}\n\n/**\n * Helper class computes and caches data required to lookup elevation offsets at the tile level.\n */\nexport class DEMSampler {\n _demTile: Tile;\n _dem: DEMData;\n _scale: number;\n _offset: [number, number];\n\n constructor(demTile: Tile, scale: number, offset: [number, number]) {\n this._demTile = demTile;\n // demTile.dem will always exist because the factory method `create` does the check\n // Make flow happy with a cast through any\n this._dem = (((this._demTile.dem): any): DEMData);\n this._scale = scale;\n this._offset = offset;\n }\n\n static create(elevation: Elevation, tileID: OverscaledTileID, useDemTile: ?Tile): ?DEMSampler {\n const demTile = useDemTile || elevation.findDEMTileFor(tileID);\n if (!(demTile && demTile.dem)) { return; }\n const dem: DEMData = demTile.dem;\n const demTileID = demTile.tileID;\n const scale = 1 << tileID.canonical.z - demTileID.canonical.z;\n const xOffset = (tileID.canonical.x / scale - demTileID.canonical.x) * dem.dim;\n const yOffset = (tileID.canonical.y / scale - demTileID.canonical.y) * dem.dim;\n const k = demTile.tileSize / EXTENT / scale;\n\n return new DEMSampler(demTile, k, [xOffset, yOffset]);\n }\n\n tileCoordToPixel(x: number, y: number): Point {\n const px = x * this._scale + this._offset[0];\n const py = y * this._scale + this._offset[1];\n const i = Math.floor(px);\n const j = Math.floor(py);\n return new Point(i, j);\n }\n\n getElevationAt(x: number, y: number, interpolated: ?boolean, clampToEdge: ?boolean): number {\n const px = x * this._scale + this._offset[0];\n const py = y * this._scale + this._offset[1];\n const i = Math.floor(px);\n const j = Math.floor(py);\n const dem = this._dem;\n\n clampToEdge = !!clampToEdge;\n\n return interpolated ? interpolate(\n interpolate(dem.get(i, j, clampToEdge), dem.get(i, j + 1, clampToEdge), py - j),\n interpolate(dem.get(i + 1, j, clampToEdge), dem.get(i + 1, j + 1, clampToEdge), py - j),\n px - i) :\n dem.get(i, j, clampToEdge);\n }\n\n getElevationAtPixel(x: number, y: number, clampToEdge: ?boolean): number {\n return this._dem.get(x, y, !!clampToEdge);\n }\n\n getMeterToDEM(lat: number): number {\n return (1 << this._demTile.tileID.canonical.z) * mercatorZfromAltitude(1, lat) * this._dem.stride;\n }\n}\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport loadGeometry from './load_geometry.js';\nimport toEvaluationFeature from './evaluation_feature.js';\nimport EXTENT from './extent.js';\nimport featureFilter from '../style-spec/feature_filter/index.js';\nimport Grid from 'grid-index';\nimport DictionaryCoder from '../util/dictionary_coder.js';\nimport {VectorTile} from '@mapbox/vector-tile';\nimport Protobuf from 'pbf';\nimport GeoJSONFeature from '../util/vectortile_to_geojson.js';\nimport {arraysIntersect, mapObject, extend} from '../util/util.js';\nimport {OverscaledTileID} from '../source/tile_id.js';\nimport {register} from '../util/web_worker_transfer.js';\nimport EvaluationParameters from '../style/evaluation_parameters.js';\nimport SourceFeatureState from '../source/source_state.js';\nimport {polygonIntersectsBox} from '../util/intersection_tests.js';\nimport {PossiblyEvaluated} from '../style/properties.js';\nimport {FeatureIndexArray} from './array_types.js';\nimport {DEMSampler} from '../terrain/elevation.js';\n\nimport type StyleLayer from '../style/style_layer.js';\nimport type {QueryFeature} from '../util/vectortile_to_geojson.js';\nimport type {FeatureStates} from \"../source/source_state\";\nimport type {FeatureFilter} from '../style-spec/feature_filter/index.js';\nimport type Transform from '../geo/transform.js';\nimport type {FilterSpecification, PromoteIdSpecification} from '../style-spec/types.js';\nimport type {TilespaceQueryGeometry} from '../style/query_geometry.js';\nimport type {FeatureIndex as FeatureIndexStruct} from './array_types.js';\nimport type {TileTransform} from '../geo/projection/tile_transform.js';\nimport type {IVectorTileLayer, IVectorTileFeature} from '@mapbox/vector-tile';\n\ntype QueryParameters = {\n pixelPosMatrix: Float32Array,\n transform: Transform,\n tileResult: TilespaceQueryGeometry,\n tileTransform: TileTransform,\n params: {\n filter: FilterSpecification,\n layers: Array<string>,\n availableImages: Array<string>\n }\n}\n\nexport type QueryResult = {[_: string]: Array<{ featureIndex: number, feature: QueryFeature }>};\n\ntype FeatureIndices = {\n bucketIndex: number,\n sourceLayerIndex: number,\n featureIndex: number,\n layoutVertexArrayOffset: number\n} | FeatureIndexStruct;\n\nclass FeatureIndex {\n tileID: OverscaledTileID;\n x: number;\n y: number;\n z: number;\n grid: Grid;\n featureIndexArray: FeatureIndexArray;\n promoteId: ?PromoteIdSpecification;\n\n rawTileData: ArrayBuffer;\n bucketLayerIDs: Array<Array<string>>;\n\n vtLayers: {[_: string]: IVectorTileLayer};\n vtFeatures: {[_: string]: IVectorTileFeature[]};\n sourceLayerCoder: DictionaryCoder;\n\n constructor(tileID: OverscaledTileID, promoteId?: ?PromoteIdSpecification) {\n this.tileID = tileID;\n this.x = tileID.canonical.x;\n this.y = tileID.canonical.y;\n this.z = tileID.canonical.z;\n this.grid = new Grid(EXTENT, 16, 0);\n this.featureIndexArray = new FeatureIndexArray();\n this.promoteId = promoteId;\n }\n\n insert(feature: IVectorTileFeature, geometry: Array<Array<Point>>, featureIndex: number, sourceLayerIndex: number, bucketIndex: number, layoutVertexArrayOffset: number = 0) {\n const key = this.featureIndexArray.length;\n this.featureIndexArray.emplaceBack(featureIndex, sourceLayerIndex, bucketIndex, layoutVertexArrayOffset);\n\n const grid = this.grid;\n\n for (let r = 0; r < geometry.length; r++) {\n const ring = geometry[r];\n\n const bbox = [Infinity, Infinity, -Infinity, -Infinity];\n for (let i = 0; i < ring.length; i++) {\n const p = ring[i];\n bbox[0] = Math.min(bbox[0], p.x);\n bbox[1] = Math.min(bbox[1], p.y);\n bbox[2] = Math.max(bbox[2], p.x);\n bbox[3] = Math.max(bbox[3], p.y);\n }\n\n if (bbox[0] < EXTENT &&\n bbox[1] < EXTENT &&\n bbox[2] >= 0 &&\n bbox[3] >= 0) {\n grid.insert(key, bbox[0], bbox[1], bbox[2], bbox[3]);\n }\n }\n }\n\n loadVTLayers(): {[_: string]: IVectorTileLayer} {\n if (!this.vtLayers) {\n this.vtLayers = new VectorTile(new Protobuf(this.rawTileData)).layers;\n this.sourceLayerCoder = new DictionaryCoder(this.vtLayers ? Object.keys(this.vtLayers).sort() : ['_geojsonTileLayer']);\n this.vtFeatures = {};\n for (const layer in this.vtLayers) {\n this.vtFeatures[layer] = [];\n }\n }\n return this.vtLayers;\n }\n\n // Finds non-symbol features in this tile at a particular position.\n query(args: QueryParameters, styleLayers: {[_: string]: StyleLayer}, serializedLayers: {[_: string]: Object}, sourceFeatureState: SourceFeatureState): QueryResult {\n this.loadVTLayers();\n const params = args.params || {},\n filter = featureFilter(params.filter);\n const tilespaceGeometry = args.tileResult;\n const transform = args.transform;\n\n const bounds = tilespaceGeometry.bufferedTilespaceBounds;\n const queryPredicate = (bx1: number, by1: number, bx2: number, by2: number) => {\n return polygonIntersectsBox(tilespaceGeometry.bufferedTilespaceGeometry, bx1, by1, bx2, by2);\n };\n const matching = this.grid.query(bounds.min.x, bounds.min.y, bounds.max.x, bounds.max.y, queryPredicate);\n matching.sort(topDownFeatureComparator);\n\n let elevationHelper = null;\n if (transform.elevation && matching.length > 0) {\n elevationHelper = DEMSampler.create(transform.elevation, this.tileID);\n }\n\n const result = {};\n let previousIndex;\n for (let k = 0; k < matching.length; k++) {\n const index = matching[k];\n\n // don't check the same feature more than once\n if (index === previousIndex) continue;\n previousIndex = index;\n\n const match = this.featureIndexArray.get(index);\n let featureGeometry = null;\n this.loadMatchingFeature(\n result,\n match,\n filter,\n params.layers,\n params.availableImages,\n styleLayers,\n serializedLayers,\n sourceFeatureState,\n (feature: IVectorTileFeature, styleLayer: StyleLayer, featureState: Object, layoutVertexArrayOffset: number = 0) => {\n if (!featureGeometry) {\n featureGeometry = loadGeometry(feature, this.tileID.canonical, args.tileTransform);\n }\n\n return styleLayer.queryIntersectsFeature(tilespaceGeometry, feature, featureState, featureGeometry, this.z, args.transform, args.pixelPosMatrix, elevationHelper, layoutVertexArrayOffset);\n }\n );\n }\n\n return result;\n }\n\n loadMatchingFeature(\n result: QueryResult,\n featureIndexData: FeatureIndices,\n filter: FeatureFilter,\n filterLayerIDs: Array<string>,\n availableImages: Array<string>,\n styleLayers: {[_: string]: StyleLayer},\n serializedLayers: {[_: string]: Object},\n sourceFeatureState?: SourceFeatureState,\n intersectionTest?: (feature: IVectorTileFeature, styleLayer: StyleLayer, featureState: Object, layoutVertexArrayOffset: number) => boolean | number) {\n\n const {featureIndex, bucketIndex, sourceLayerIndex, layoutVertexArrayOffset} = featureIndexData;\n const layerIDs = this.bucketLayerIDs[bucketIndex];\n if (filterLayerIDs && !arraysIntersect(filterLayerIDs, layerIDs))\n return;\n\n const sourceLayerName = this.sourceLayerCoder.decode(sourceLayerIndex);\n const sourceLayer = this.vtLayers[sourceLayerName];\n const feature = sourceLayer.feature(featureIndex);\n\n if (filter.needGeometry) {\n const evaluationFeature = toEvaluationFeature(feature, true);\n // $FlowFixMe[method-unbinding]\n if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) {\n return;\n }\n // $FlowFixMe[method-unbinding]\n } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) {\n return;\n }\n\n const id = this.getId(feature, sourceLayerName);\n\n for (let l = 0; l < layerIDs.length; l++) {\n const layerID = layerIDs[l];\n\n if (filterLayerIDs && filterLayerIDs.indexOf(layerID) < 0) {\n continue;\n }\n\n const styleLayer = styleLayers[layerID];\n\n if (!styleLayer) continue;\n\n let featureState = {};\n if (id !== undefined && sourceFeatureState) {\n // `feature-state` expression evaluation requires feature state to be available\n featureState = sourceFeatureState.getState(styleLayer.sourceLayer || '_geojsonTileLayer', id);\n }\n\n const serializedLayer = extend({}, serializedLayers[layerID]);\n\n serializedLayer.paint = evaluateProperties(serializedLayer.paint, styleLayer.paint, feature, featureState, availableImages);\n serializedLayer.layout = evaluateProperties(serializedLayer.layout, styleLayer.layout, feature, featureState, availableImages);\n\n const intersectionZ = !intersectionTest || intersectionTest(feature, styleLayer, featureState, layoutVertexArrayOffset);\n if (!intersectionZ) {\n // Only applied for non-symbol features\n continue;\n }\n\n const geojsonFeature = new GeoJSONFeature(feature, this.z, this.x, this.y, id);\n geojsonFeature.layer = serializedLayer;\n let layerResult = result[layerID];\n if (layerResult === undefined) {\n layerResult = result[layerID] = [];\n }\n\n layerResult.push({featureIndex, feature: geojsonFeature, intersectionZ});\n }\n }\n\n // Given a set of symbol indexes that have already been looked up,\n // return a matching set of GeoJSONFeatures\n lookupSymbolFeatures(symbolFeatureIndexes: Array<number>,\n serializedLayers: {[string]: StyleLayer},\n bucketIndex: number,\n sourceLayerIndex: number,\n filterSpec: FilterSpecification,\n filterLayerIDs: Array<string>,\n availableImages: Array<string>,\n styleLayers: {[_: string]: StyleLayer}): QueryResult {\n const result = {};\n this.loadVTLayers();\n\n const filter = featureFilter(filterSpec);\n\n for (const symbolFeatureIndex of symbolFeatureIndexes) {\n this.loadMatchingFeature(\n result, {\n bucketIndex,\n sourceLayerIndex,\n featureIndex: symbolFeatureIndex,\n layoutVertexArrayOffset: 0\n },\n filter,\n filterLayerIDs,\n availableImages,\n styleLayers,\n serializedLayers\n );\n\n }\n return result;\n }\n\n loadFeature(featureIndexData: FeatureIndices): IVectorTileFeature {\n const {featureIndex, sourceLayerIndex} = featureIndexData;\n\n this.loadVTLayers();\n const sourceLayerName = this.sourceLayerCoder.decode(sourceLayerIndex);\n\n const featureCache = this.vtFeatures[sourceLayerName];\n if (featureCache[featureIndex]) {\n return featureCache[featureIndex];\n }\n const sourceLayer = this.vtLayers[sourceLayerName];\n const feature = sourceLayer.feature(featureIndex);\n featureCache[featureIndex] = feature;\n\n return feature;\n }\n\n hasLayer(id: string): boolean {\n for (const layerIDs of this.bucketLayerIDs) {\n for (const layerID of layerIDs) {\n if (id === layerID) return true;\n }\n }\n\n return false;\n }\n\n getId(feature: IVectorTileFeature, sourceLayerId: string): string | number | void {\n let id = feature.id;\n if (this.promoteId) {\n const propName = typeof this.promoteId === 'string' ? this.promoteId : this.promoteId[sourceLayerId];\n // $FlowFixMe[incompatible-type] - Flow can't narrow the id type from IVectorTileFeature.id\n if (propName != null) id = feature.properties[propName];\n if (typeof id === 'boolean') id = Number(id);\n }\n return id;\n }\n}\n\nregister(FeatureIndex, 'FeatureIndex', {omit: ['rawTileData', 'sourceLayerCoder']});\n\nexport default FeatureIndex;\n\nfunction evaluateProperties(serializedProperties: mixed, styleLayerProperties: mixed, feature: IVectorTileFeature, featureState: FeatureStates, availableImages: Array<string>) {\n return mapObject(serializedProperties, (property, key) => {\n const prop = styleLayerProperties instanceof PossiblyEvaluated ? styleLayerProperties.get(key) : null;\n return prop && prop.evaluate ? prop.evaluate(feature, featureState, availableImages) : prop;\n });\n}\n\nfunction topDownFeatureComparator(a: number, b: number) {\n return b - a;\n}\n","// @flow\n\nimport {warnOnce, nextPowerOfTwo} from '../util/util.js';\nimport {AlphaImage} from '../util/image.js';\nimport {register} from '../util/web_worker_transfer.js';\n\nimport type {SpritePosition, SpritePositions} from '../util/image.js';\n\ntype DashRange = {|\n isDash: boolean,\n left: number,\n right: number,\n zeroLength: boolean\n|};\n\n/**\n * A LineAtlas lets us reuse rendered dashed lines\n * by writing many of them to a texture and then fetching their positions\n * using .getDash.\n *\n * @param {number} width\n * @param {number} height\n * @private\n */\nclass LineAtlas {\n width: number;\n height: number;\n nextRow: number;\n image: AlphaImage;\n positions: SpritePositions;\n uploaded: boolean;\n\n constructor(width: number, height: number) {\n this.width = width;\n this.height = height;\n this.nextRow = 0;\n this.image = new AlphaImage({width, height});\n this.positions = {};\n this.uploaded = false;\n }\n\n /**\n * Get a dash line pattern.\n *\n * @param {Array<number>} dasharray\n * @param {string} lineCap the type of line caps to be added to dashes\n * @returns {Object} position of dash texture in { y, height, width }\n * @private\n */\n getDash(dasharray: Array<number>, lineCap: string): SpritePosition {\n const key = this.getKey(dasharray, lineCap);\n return this.positions[key];\n }\n\n trim() {\n const width = this.width;\n const height = this.height = nextPowerOfTwo(this.nextRow);\n this.image.resize({width, height});\n }\n\n getKey(dasharray: Array<number>, lineCap: string): string {\n return dasharray.join(',') + lineCap;\n }\n\n getDashRanges(dasharray: Array<number>, lineAtlasWidth: number, stretch: number): Array<DashRange> {\n // If dasharray has an odd length, both the first and last parts\n // are dashes and should be joined seamlessly.\n const oddDashArray = dasharray.length % 2 === 1;\n\n const ranges = [];\n\n let left = oddDashArray ? -dasharray[dasharray.length - 1] * stretch : 0;\n let right = dasharray[0] * stretch;\n let isDash = true;\n\n ranges.push({left, right, isDash, zeroLength: dasharray[0] === 0});\n\n let currentDashLength = dasharray[0];\n for (let i = 1; i < dasharray.length; i++) {\n isDash = !isDash;\n\n const dashLength = dasharray[i];\n left = currentDashLength * stretch;\n currentDashLength += dashLength;\n right = currentDashLength * stretch;\n\n ranges.push({left, right, isDash, zeroLength: dashLength === 0});\n }\n\n return ranges;\n }\n\n addRoundDash(ranges: Array<DashRange>, stretch: number, n: number) {\n const halfStretch = stretch / 2;\n\n for (let y = -n; y <= n; y++) {\n const row = this.nextRow + n + y;\n const index = this.width * row;\n let currIndex = 0;\n let range = ranges[currIndex];\n\n for (let x = 0; x < this.width; x++) {\n if (x / range.right > 1) { range = ranges[++currIndex]; }\n\n const distLeft = Math.abs(x - range.left);\n const distRight = Math.abs(x - range.right);\n const minDist = Math.min(distLeft, distRight);\n let signedDistance;\n\n const distMiddle = y / n * (halfStretch + 1);\n if (range.isDash) {\n const distEdge = halfStretch - Math.abs(distMiddle);\n signedDistance = Math.sqrt(minDist * minDist + distEdge * distEdge);\n } else {\n signedDistance = halfStretch - Math.sqrt(minDist * minDist + distMiddle * distMiddle);\n }\n\n this.image.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128));\n }\n }\n }\n\n addRegularDash(ranges: Array<DashRange>, capLength: number) {\n\n // Collapse any zero-length range\n // Collapse neighbouring same-type parts into a single part\n for (let i = ranges.length - 1; i >= 0; --i) {\n const part = ranges[i];\n const next = ranges[i + 1];\n if (part.zeroLength) {\n ranges.splice(i, 1);\n } else if (next && next.isDash === part.isDash) {\n next.left = part.left;\n ranges.splice(i, 1);\n }\n }\n\n // Combine the first and last parts if possible\n const first = ranges[0];\n const last = ranges[ranges.length - 1];\n if (first.isDash === last.isDash) {\n first.left = last.left - this.width;\n last.right = first.right + this.width;\n }\n\n const index = this.width * this.nextRow;\n let currIndex = 0;\n let range = ranges[currIndex];\n\n for (let x = 0; x < this.width; x++) {\n if (x / range.right > 1) {\n range = ranges[++currIndex];\n }\n\n const distLeft = Math.abs(x - range.left);\n const distRight = Math.abs(x - range.right);\n\n const minDist = Math.min(distLeft, distRight);\n const signedDistance = (range.isDash ? minDist : -minDist) + capLength;\n\n this.image.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128));\n }\n }\n\n addDash(dasharray: Array<number>, lineCap: string): null | SpritePosition {\n const key = this.getKey(dasharray, lineCap);\n if (this.positions[key]) return this.positions[key];\n\n const round = lineCap === 'round';\n const n = round ? 7 : 0;\n const height = 2 * n + 1;\n\n if (this.nextRow + height > this.height) {\n warnOnce('LineAtlas out of space');\n return null;\n }\n\n // dasharray is empty, draws a full line (no dash or no gap length represented, default behavior)\n if (dasharray.length === 0) {\n // insert a single dash range in order to draw a full line\n dasharray.push(1);\n }\n\n let length = 0;\n for (let i = 0; i < dasharray.length; i++) {\n if (dasharray[i] < 0) {\n warnOnce('Negative value is found in line dasharray, replacing values with 0');\n dasharray[i] = 0;\n }\n length += dasharray[i];\n }\n\n if (length !== 0) {\n const stretch = this.width / length;\n const ranges = this.getDashRanges(dasharray, this.width, stretch);\n\n if (round) {\n this.addRoundDash(ranges, stretch, n);\n } else {\n const capLength = lineCap === 'square' ? 0.5 * stretch : 0;\n this.addRegularDash(ranges, capLength);\n }\n }\n\n const y = this.nextRow + n;\n\n this.nextRow += height;\n\n const pos = {\n tl: [y, n],\n br: [length, 0]\n };\n this.positions[key] = pos;\n return pos;\n }\n}\n\nregister(LineAtlas, 'LineAtlas');\n\nexport default LineAtlas;\n","// @flow\n\nimport {SDF_SCALE} from '../render/glyph_manager.js';\nimport {AlphaImage} from '../util/image.js';\nimport {register} from '../util/web_worker_transfer.js';\nimport potpack from 'potpack';\n\nimport type {StyleGlyph} from '../style/style_glyph.js';\n\nconst glyphPadding = 1;\n/*\n The glyph padding is just to prevent sampling errors at the boundaries between\n glyphs in the atlas texture, and for that purpose there's no need to make it\n bigger with high-res SDFs. However, layout is done based on the glyph size\n including this padding, so scaling this padding is the easiest way to keep\n layout exactly the same as the SDF_SCALE changes.\n*/\nconst localGlyphPadding = glyphPadding * SDF_SCALE;\n\nexport type GlyphRect = {\n x: number,\n y: number,\n w: number,\n h: number\n};\n// {glyphID: glyphRect}\nexport type GlyphPositionMap = { [_: number]: GlyphRect };\n\n// {fontStack: glyphPoistionMap}\nexport type GlyphPositions = { [_: string]: GlyphPositionMap };\n\nexport default class GlyphAtlas {\n image: AlphaImage;\n positions: GlyphPositions;\n constructor(stacks: {[_: string]: {glyphs: {[_: number]: ?StyleGlyph }, ascender?: number, descender?: number }}) {\n const positions = {};\n const bins = [];\n\n for (const stack in stacks) {\n const glyphData = stacks[stack];\n const glyphPositionMap = positions[stack] = {};\n\n for (const id in glyphData.glyphs) {\n const src = glyphData.glyphs[+id];\n if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) continue;\n\n const padding = src.metrics.localGlyph ? localGlyphPadding : glyphPadding;\n const bin = {\n x: 0,\n y: 0,\n w: src.bitmap.width + 2 * padding,\n h: src.bitmap.height + 2 * padding\n };\n bins.push(bin);\n glyphPositionMap[id] = bin;\n }\n }\n\n const {w, h} = potpack(bins);\n const image = new AlphaImage({width: w || 1, height: h || 1});\n\n for (const stack in stacks) {\n const glyphData = stacks[stack];\n\n for (const id in glyphData.glyphs) {\n const src = glyphData.glyphs[+id];\n if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) continue;\n const bin = positions[stack][id];\n const padding = src.metrics.localGlyph ? localGlyphPadding : glyphPadding;\n AlphaImage.copy(src.bitmap, image, {x: 0, y: 0}, {x: bin.x + padding, y: bin.y + padding}, src.bitmap);\n }\n }\n\n this.image = image;\n this.positions = positions;\n }\n}\n\nregister(GlyphAtlas, 'GlyphAtlas');\n","// @flow\n\nimport FeatureIndex from '../data/feature_index.js';\n\nimport {performSymbolLayout} from '../symbol/symbol_layout.js';\nimport {CollisionBoxArray} from '../data/array_types.js';\nimport DictionaryCoder from '../util/dictionary_coder.js';\nimport SymbolBucket from '../data/bucket/symbol_bucket.js';\nimport LineBucket from '../data/bucket/line_bucket.js';\nimport FillBucket from '../data/bucket/fill_bucket.js';\nimport FillExtrusionBucket from '../data/bucket/fill_extrusion_bucket.js';\nimport {warnOnce, mapObject, values} from '../util/util.js';\nimport assert from 'assert';\nimport LineAtlas from '../render/line_atlas.js';\nimport ImageAtlas from '../render/image_atlas.js';\nimport GlyphAtlas from '../render/glyph_atlas.js';\nimport EvaluationParameters from '../style/evaluation_parameters.js';\nimport {CanonicalTileID, OverscaledTileID} from './tile_id.js';\nimport {PerformanceUtils} from '../util/performance.js';\nimport tileTransform from '../geo/projection/tile_transform.js';\nimport type Projection from '../geo/projection/projection.js';\nimport type {Bucket} from '../data/bucket.js';\nimport type Actor from '../util/actor.js';\nimport type StyleLayer from '../style/style_layer.js';\nimport type StyleLayerIndex from '../style/style_layer_index.js';\nimport type {StyleImage} from '../style/style_image.js';\nimport type {StyleGlyph} from '../style/style_glyph.js';\nimport type {SpritePositions} from '../util/image.js';\nimport type {\n WorkerTileParameters,\n WorkerTileCallback,\n} from '../source/worker_source.js';\nimport type {PromoteIdSpecification} from '../style-spec/types.js';\nimport type {TileTransform} from '../geo/projection/tile_transform.js';\nimport type {IVectorTile} from '@mapbox/vector-tile';\n\nclass WorkerTile {\n tileID: OverscaledTileID;\n uid: number;\n zoom: number;\n tileZoom: number;\n canonical: CanonicalTileID;\n pixelRatio: number;\n tileSize: number;\n source: string;\n promoteId: ?PromoteIdSpecification;\n overscaling: number;\n showCollisionBoxes: boolean;\n collectResourceTiming: boolean;\n returnDependencies: boolean;\n enableTerrain: boolean;\n isSymbolTile: ?boolean;\n projection: Projection;\n tileTransform: TileTransform;\n\n status: 'parsing' | 'done';\n data: IVectorTile;\n collisionBoxArray: CollisionBoxArray;\n\n abort: ?() => void;\n reloadCallback: ?WorkerTileCallback;\n vectorTile: IVectorTile;\n\n constructor(params: WorkerTileParameters) {\n this.tileID = new OverscaledTileID(params.tileID.overscaledZ, params.tileID.wrap, params.tileID.canonical.z, params.tileID.canonical.x, params.tileID.canonical.y);\n this.tileZoom = params.tileZoom;\n this.uid = params.uid;\n this.zoom = params.zoom;\n this.canonical = params.tileID.canonical;\n this.pixelRatio = params.pixelRatio;\n this.tileSize = params.tileSize;\n this.source = params.source;\n this.overscaling = this.tileID.overscaleFactor();\n this.showCollisionBoxes = params.showCollisionBoxes;\n this.collectResourceTiming = !!params.collectResourceTiming;\n this.returnDependencies = !!params.returnDependencies;\n this.promoteId = params.promoteId;\n this.enableTerrain = !!params.enableTerrain;\n this.isSymbolTile = params.isSymbolTile;\n this.tileTransform = tileTransform(params.tileID.canonical, params.projection);\n this.projection = params.projection;\n }\n\n parse(data: IVectorTile, layerIndex: StyleLayerIndex, availableImages: Array<string>, actor: Actor, callback: WorkerTileCallback) {\n const m = PerformanceUtils.beginMeasure('parseTile1');\n this.status = 'parsing';\n this.data = data;\n\n this.collisionBoxArray = new CollisionBoxArray();\n const sourceLayerCoder = new DictionaryCoder(Object.keys(data.layers).sort());\n\n const featureIndex = new FeatureIndex(this.tileID, this.promoteId);\n featureIndex.bucketLayerIDs = [];\n\n const buckets: {[_: string]: Bucket} = {};\n\n // we initially reserve space for a 256x256 atlas, but trim it after processing all line features\n const lineAtlas = new LineAtlas(256, 256);\n\n const options = {\n featureIndex,\n iconDependencies: {},\n patternDependencies: {},\n glyphDependencies: {},\n lineAtlas,\n availableImages\n };\n\n const layerFamilies = layerIndex.familiesBySource[this.source];\n for (const sourceLayerId in layerFamilies) {\n const sourceLayer = data.layers[sourceLayerId];\n if (!sourceLayer) {\n continue;\n }\n\n let anySymbolLayers = false;\n let anyOtherLayers = false;\n for (const family of layerFamilies[sourceLayerId]) {\n if (family[0].type === 'symbol') {\n anySymbolLayers = true;\n } else {\n anyOtherLayers = true;\n }\n }\n\n if (this.isSymbolTile === true && !anySymbolLayers) {\n continue;\n } else if (this.isSymbolTile === false && !anyOtherLayers) {\n continue;\n }\n\n if (sourceLayer.version === 1) {\n warnOnce(`Vector tile source \"${this.source}\" layer \"${sourceLayerId}\" ` +\n `does not use vector tile spec v2 and therefore may have some rendering errors.`);\n }\n\n const sourceLayerIndex = sourceLayerCoder.encode(sourceLayerId);\n const features = [];\n for (let index = 0; index < sourceLayer.length; index++) {\n const feature = sourceLayer.feature(index);\n const id = featureIndex.getId(feature, sourceLayerId);\n features.push({feature, id, index, sourceLayerIndex});\n }\n\n for (const family of layerFamilies[sourceLayerId]) {\n const layer = family[0];\n if (this.isSymbolTile !== undefined && (layer.type === 'symbol') !== this.isSymbolTile) continue;\n\n assert(layer.source === this.source);\n if (layer.minzoom && this.zoom < Math.floor(layer.minzoom)) continue;\n if (layer.maxzoom && this.zoom >= layer.maxzoom) continue;\n if (layer.visibility === 'none') continue;\n\n recalculateLayers(family, this.zoom, availableImages);\n\n const bucket = buckets[layer.id] = layer.createBucket({\n index: featureIndex.bucketLayerIDs.length,\n // $FlowFixMe[incompatible-call] - Flow can't infer proper `family` type from `layer` above\n layers: family,\n zoom: this.zoom,\n canonical: this.canonical,\n pixelRatio: this.pixelRatio,\n overscaling: this.overscaling,\n collisionBoxArray: this.collisionBoxArray,\n sourceLayerIndex,\n sourceID: this.source,\n enableTerrain: this.enableTerrain,\n projection: this.projection.spec,\n availableImages\n });\n\n assert(this.tileTransform.projection.name === this.projection.name);\n bucket.populate(features, options, this.tileID.canonical, this.tileTransform);\n featureIndex.bucketLayerIDs.push(family.map((l) => l.id));\n }\n }\n\n lineAtlas.trim();\n\n let error: ?Error;\n let glyphMap: {[_: string]: {glyphs: {[_: number]: ?StyleGlyph}, ascender?: number, descender?: number}};\n let iconMap: {[_: string]: StyleImage};\n let patternMap: {[_: string]: StyleImage};\n const taskMetadata = {type: 'maybePrepare', isSymbolTile: this.isSymbolTile, zoom: this.zoom};\n\n const maybePrepare = () => {\n if (error) {\n return callback(error);\n } else if (glyphMap && iconMap && patternMap) {\n const m = PerformanceUtils.beginMeasure('parseTile2');\n const glyphAtlas = new GlyphAtlas(glyphMap);\n const imageAtlas = new ImageAtlas(iconMap, patternMap);\n\n for (const key in buckets) {\n const bucket = buckets[key];\n if (bucket instanceof SymbolBucket) {\n recalculateLayers(bucket.layers, this.zoom, availableImages);\n performSymbolLayout(bucket,\n glyphMap,\n glyphAtlas.positions,\n iconMap,\n imageAtlas.iconPositions,\n this.showCollisionBoxes,\n availableImages,\n this.tileID.canonical,\n this.tileZoom,\n this.projection);\n } else if (bucket.hasPattern &&\n (bucket instanceof LineBucket ||\n bucket instanceof FillBucket ||\n bucket instanceof FillExtrusionBucket)) {\n recalculateLayers(bucket.layers, this.zoom, availableImages);\n // $FlowFixMe[incompatible-type] Flow can't interpret ImagePosition as SpritePosition for some reason here\n const imagePositions: SpritePositions = imageAtlas.patternPositions;\n bucket.addFeatures(options, this.tileID.canonical, imagePositions, availableImages, this.tileTransform);\n }\n }\n\n this.status = 'done';\n callback(null, {\n buckets: values(buckets).filter(b => !b.isEmpty()),\n featureIndex,\n collisionBoxArray: this.collisionBoxArray,\n glyphAtlasImage: glyphAtlas.image,\n lineAtlas,\n imageAtlas,\n // Only used for benchmarking:\n glyphMap: this.returnDependencies ? glyphMap : null,\n iconMap: this.returnDependencies ? iconMap : null,\n glyphPositions: this.returnDependencies ? glyphAtlas.positions : null\n });\n PerformanceUtils.endMeasure(m);\n }\n };\n\n const stacks = mapObject(options.glyphDependencies, (glyphs) => Object.keys(glyphs).map(Number));\n if (Object.keys(stacks).length) {\n actor.send('getGlyphs', {uid: this.uid, stacks}, (err, result) => {\n if (!error) {\n error = err;\n glyphMap = result;\n maybePrepare();\n }\n }, undefined, false, taskMetadata);\n } else {\n glyphMap = {};\n }\n\n const icons = Object.keys(options.iconDependencies);\n if (icons.length) {\n actor.send('getImages', {icons, source: this.source, tileID: this.tileID, type: 'icons'}, (err, result) => {\n if (!error) {\n error = err;\n iconMap = result;\n maybePrepare();\n }\n }, undefined, false, taskMetadata);\n } else {\n iconMap = {};\n }\n\n const patterns = Object.keys(options.patternDependencies);\n if (patterns.length) {\n actor.send('getImages', {icons: patterns, source: this.source, tileID: this.tileID, type: 'patterns'}, (err, result) => {\n if (!error) {\n error = err;\n patternMap = result;\n maybePrepare();\n }\n }, undefined, false, taskMetadata);\n } else {\n patternMap = {};\n }\n\n PerformanceUtils.endMeasure(m);\n\n maybePrepare();\n }\n}\n\nfunction recalculateLayers(layers: $ReadOnlyArray<StyleLayer>, zoom: number, availableImages: Array<string>) {\n // Layers are shared and may have been used by a WorkerTile with a different zoom.\n const parameters = new EvaluationParameters(zoom);\n for (const layer of layers) {\n layer.recalculate(parameters, availableImages);\n }\n}\n\nexport default WorkerTile;\n","// @flow\n\nimport {getArrayBuffer} from '../util/ajax.js';\n\nimport {VectorTile} from '@mapbox/vector-tile';\nimport Protobuf from 'pbf';\nimport WorkerTile from './worker_tile.js';\nimport {extend} from '../util/util.js';\nimport {getPerformanceMeasurement} from '../util/performance.js';\nimport {Evented} from '../util/evented.js';\nimport tileTransform from '../geo/projection/tile_transform.js';\n\nimport type {\n WorkerSource,\n WorkerTileResult,\n WorkerTileParameters,\n RequestedTileParameters,\n WorkerTileCallback,\n TileParameters\n} from '../source/worker_source.js';\n\nimport type Actor from '../util/actor.js';\nimport type StyleLayerIndex from '../style/style_layer_index.js';\nimport type {Callback} from '../types/callback.js';\nimport type Scheduler from '../util/scheduler.js';\nimport type {IVectorTile} from '@mapbox/vector-tile';\n\nexport type LoadVectorTileResult = {\n rawData: ArrayBuffer;\n vectorTile?: IVectorTile;\n expires?: any;\n cacheControl?: any;\n resourceTiming?: Array<PerformanceResourceTiming>;\n};\n\n/**\n * @callback LoadVectorDataCallback\n * @param error\n * @param vectorTile\n * @private\n */\nexport type LoadVectorDataCallback = Callback<?LoadVectorTileResult>;\n\nexport type AbortVectorData = () => void;\nexport type LoadVectorData = (params: RequestedTileParameters, callback: LoadVectorDataCallback) => ?AbortVectorData;\nexport class DedupedRequest {\n entries: { [string]: Object };\n scheduler: ?Scheduler;\n\n constructor(scheduler?: Scheduler) {\n this.entries = {};\n this.scheduler = scheduler;\n }\n\n request(key: string, metadata: Object, request: any, callback: LoadVectorDataCallback): (() => void) {\n const entry = this.entries[key] = this.entries[key] || {callbacks: []};\n\n if (entry.result) {\n const [err, result] = entry.result;\n if (this.scheduler) {\n this.scheduler.add(() => {\n callback(err, result);\n }, metadata);\n } else {\n callback(err, result);\n }\n return () => {};\n }\n\n entry.callbacks.push(callback);\n\n if (!entry.cancel) {\n entry.cancel = request((err, result) => {\n entry.result = [err, result];\n for (const cb of entry.callbacks) {\n if (this.scheduler) {\n this.scheduler.add(() => {\n cb(err, result);\n }, metadata);\n } else {\n cb(err, result);\n }\n }\n setTimeout(() => delete this.entries[key], 1000 * 3);\n });\n }\n\n return () => {\n if (entry.result) return;\n entry.callbacks = entry.callbacks.filter(cb => cb !== callback);\n if (!entry.callbacks.length) {\n entry.cancel();\n delete this.entries[key];\n }\n };\n }\n}\n\n/**\n * @private\n */\n// $FlowFixMe[missing-this-annot]\nexport function loadVectorTile(params: RequestedTileParameters, callback: LoadVectorDataCallback, skipParse?: boolean): (() => void) {\n const key = JSON.stringify(params.request);\n\n const makeRequest = (callback: LoadVectorDataCallback) => {\n const request = getArrayBuffer(params.request, (err: ?Error, data: ?ArrayBuffer, cacheControl: ?string, expires: ?string) => {\n if (err) {\n callback(err);\n } else if (data) {\n callback(null, {\n vectorTile: skipParse ? undefined : new VectorTile(new Protobuf(data)),\n rawData: data,\n cacheControl,\n expires\n });\n }\n });\n return () => {\n request.cancel();\n callback();\n };\n };\n\n if (params.data) {\n // if we already got the result earlier (on the main thread), return it directly\n (this.deduped: DedupedRequest).entries[key] = {result: [null, params.data]};\n }\n\n const callbackMetadata = {type: 'parseTile', isSymbolTile: params.isSymbolTile, zoom: params.tileZoom};\n return (this.deduped: DedupedRequest).request(key, callbackMetadata, makeRequest, callback);\n}\n\n/**\n * The {@link WorkerSource} implementation that supports {@link VectorTileSource}.\n * This class is designed to be easily reused to support custom source types\n * for data formats that can be parsed/converted into an in-memory VectorTile\n * representation. To do so, create it with\n * `new VectorTileWorkerSource(actor, styleLayers, customLoadVectorDataFunction)`.\n *\n * @private\n */\nclass VectorTileWorkerSource extends Evented implements WorkerSource {\n actor: Actor;\n layerIndex: StyleLayerIndex;\n availableImages: Array<string>;\n loadVectorData: LoadVectorData;\n loading: {[_: number]: WorkerTile };\n loaded: {[_: number]: WorkerTile };\n deduped: DedupedRequest;\n isSpriteLoaded: boolean;\n scheduler: ?Scheduler;\n\n /**\n * @param [loadVectorData] Optional method for custom loading of a VectorTile\n * object based on parameters passed from the main-thread Source. See\n * {@link VectorTileWorkerSource#loadTile}. The default implementation simply\n * loads the pbf at `params.url`.\n * @private\n */\n constructor(actor: Actor, layerIndex: StyleLayerIndex, availableImages: Array<string>, isSpriteLoaded: boolean, loadVectorData: ?LoadVectorData) {\n super();\n this.actor = actor;\n this.layerIndex = layerIndex;\n this.availableImages = availableImages;\n this.loadVectorData = loadVectorData || loadVectorTile;\n this.loading = {};\n this.loaded = {};\n this.deduped = new DedupedRequest(actor.scheduler);\n this.isSpriteLoaded = isSpriteLoaded;\n this.scheduler = actor.scheduler;\n }\n\n /**\n * Implements {@link WorkerSource#loadTile}. Delegates to\n * {@link VectorTileWorkerSource#loadVectorData} (which by default expects\n * a `params.url` property) for fetching and producing a VectorTile object.\n * @private\n */\n loadTile(params: WorkerTileParameters, callback: WorkerTileCallback) {\n const uid = params.uid;\n\n const requestParam = params && params.request;\n const perf = requestParam && requestParam.collectResourceTiming;\n\n const workerTile = this.loading[uid] = new WorkerTile(params);\n workerTile.abort = this.loadVectorData(params, (err, response) => {\n\n const aborted = !this.loading[uid];\n\n delete this.loading[uid];\n\n if (aborted || err || !response) {\n workerTile.status = 'done';\n if (!aborted) this.loaded[uid] = workerTile;\n return callback(err);\n }\n\n const rawTileData = response.rawData;\n const cacheControl = {};\n if (response.expires) cacheControl.expires = response.expires;\n if (response.cacheControl) cacheControl.cacheControl = response.cacheControl;\n\n // response.vectorTile will be present in the GeoJSON worker case (which inherits from this class)\n // because we stub the vector tile interface around JSON data instead of parsing it directly\n workerTile.vectorTile = response.vectorTile || new VectorTile(new Protobuf(rawTileData));\n const parseTile = () => {\n workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, (err, result) => {\n if (err || !result) return callback(err);\n\n const resourceTiming = {};\n if (perf) {\n // Transferring a copy of rawTileData because the worker needs to retain its copy.\n const resourceTimingData = getPerformanceMeasurement(requestParam);\n // it's necessary to eval the result of getEntriesByName() here via parse/stringify\n // late evaluation in the main thread causes TypeError: illegal invocation\n if (resourceTimingData.length > 0) {\n resourceTiming.resourceTiming = JSON.parse(JSON.stringify(resourceTimingData));\n }\n }\n callback(null, extend({rawTileData: rawTileData.slice(0)}, result, cacheControl, resourceTiming));\n });\n };\n\n if (this.isSpriteLoaded) {\n parseTile();\n } else {\n this.once('isSpriteLoaded', () => {\n if (this.scheduler) {\n const metadata = {type: 'parseTile', isSymbolTile: params.isSymbolTile, zoom: params.tileZoom};\n this.scheduler.add(parseTile, metadata);\n } else {\n parseTile();\n }\n });\n }\n\n this.loaded = this.loaded || {};\n this.loaded[uid] = workerTile;\n });\n }\n\n /**\n * Implements {@link WorkerSource#reloadTile}.\n * @private\n */\n reloadTile(params: WorkerTileParameters, callback: WorkerTileCallback) {\n const loaded = this.loaded,\n uid = params.uid,\n vtSource = this;\n if (loaded && loaded[uid]) {\n const workerTile = loaded[uid];\n workerTile.showCollisionBoxes = params.showCollisionBoxes;\n workerTile.enableTerrain = !!params.enableTerrain;\n workerTile.projection = params.projection;\n workerTile.tileTransform = tileTransform(params.tileID.canonical, params.projection);\n\n const done = (err: ?Error, data: ?WorkerTileResult) => {\n const reloadCallback = workerTile.reloadCallback;\n if (reloadCallback) {\n delete workerTile.reloadCallback;\n workerTile.parse(workerTile.vectorTile, vtSource.layerIndex, this.availableImages, vtSource.actor, reloadCallback);\n }\n callback(err, data);\n };\n\n if (workerTile.status === 'parsing') {\n workerTile.reloadCallback = done;\n } else if (workerTile.status === 'done') {\n // if there was no vector tile data on the initial load, don't try and re-parse tile\n if (workerTile.vectorTile) {\n workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, done);\n } else {\n done();\n }\n }\n }\n }\n\n /**\n * Implements {@link WorkerSource#abortTile}.\n *\n * @param params\n * @param params.uid The UID for this tile.\n * @private\n */\n abortTile(params: TileParameters, callback: WorkerTileCallback) {\n const uid = params.uid;\n const tile = this.loading[uid];\n if (tile) {\n if (tile.abort) tile.abort();\n delete this.loading[uid];\n }\n callback();\n }\n\n /**\n * Implements {@link WorkerSource#removeTile}.\n *\n * @param params\n * @param params.uid The UID for this tile.\n * @private\n */\n removeTile(params: TileParameters, callback: WorkerTileCallback) {\n const loaded = this.loaded,\n uid = params.uid;\n if (loaded && loaded[uid]) {\n delete loaded[uid];\n }\n callback();\n }\n}\n\nexport default VectorTileWorkerSource;\n","// @flow\n\nimport DEMData from '../data/dem_data.js';\nimport window from '../util/window.js';\n\nimport type Actor from '../util/actor.js';\nimport type {WorkerDEMTileParameters, WorkerDEMTileCallback} from './worker_source.js';\n\nclass RasterDEMTileWorkerSource {\n actor: Actor;\n offscreenCanvas: OffscreenCanvas;\n offscreenCanvasContext: CanvasRenderingContext2D;\n\n loadTile(params: WorkerDEMTileParameters, callback: WorkerDEMTileCallback) {\n const {uid, encoding, rawImageData, padding, buildQuadTree} = params;\n // Main thread will transfer ImageBitmap if offscreen decode with OffscreenCanvas is supported, else it will transfer an already decoded image.\n // Flow struggles to refine ImageBitmap type, likely due to the JSDom shim\n const imagePixels = window.ImageBitmap && rawImageData instanceof window.ImageBitmap ? this.getImageData(rawImageData, padding) : ((rawImageData: any): ImageData);\n const dem = new DEMData(uid, imagePixels, encoding, padding < 1, buildQuadTree);\n callback(null, dem);\n }\n\n getImageData(imgBitmap: ImageBitmap, padding: number): ImageData {\n // Lazily initialize OffscreenCanvas\n if (!this.offscreenCanvas || !this.offscreenCanvasContext) {\n // Dem tiles are typically 256x256\n this.offscreenCanvas = new OffscreenCanvas(imgBitmap.width, imgBitmap.height);\n // $FlowIssue[extra-arg]: internal Flow types don't yet know about willReadFrequently\n this.offscreenCanvasContext = this.offscreenCanvas.getContext('2d', {willReadFrequently: true});\n }\n\n this.offscreenCanvas.width = imgBitmap.width;\n this.offscreenCanvas.height = imgBitmap.height;\n\n this.offscreenCanvasContext.drawImage(imgBitmap, 0, 0, imgBitmap.width, imgBitmap.height);\n // Insert or remove defined padding around the image to allow backfilling for neighboring data.\n const imgData = this.offscreenCanvasContext.getImageData(-padding, -padding, imgBitmap.width + 2 * padding, imgBitmap.height + 2 * padding);\n this.offscreenCanvasContext.clearRect(0, 0, this.offscreenCanvas.width, this.offscreenCanvas.height);\n return imgData;\n }\n}\n\nexport default RasterDEMTileWorkerSource;\n","\nmodule.exports = rewind;\n\nfunction rewind(gj, outer) {\n var type = gj && gj.type, i;\n\n if (type === 'FeatureCollection') {\n for (i = 0; i < gj.features.length; i++) rewind(gj.features[i], outer);\n\n } else if (type === 'GeometryCollection') {\n for (i = 0; i < gj.geometries.length; i++) rewind(gj.geometries[i], outer);\n\n } else if (type === 'Feature') {\n rewind(gj.geometry, outer);\n\n } else if (type === 'Polygon') {\n rewindRings(gj.coordinates, outer);\n\n } else if (type === 'MultiPolygon') {\n for (i = 0; i < gj.coordinates.length; i++) rewindRings(gj.coordinates[i], outer);\n }\n\n return gj;\n}\n\nfunction rewindRings(rings, outer) {\n if (rings.length === 0) return;\n\n rewindRing(rings[0], outer);\n for (var i = 1; i < rings.length; i++) {\n rewindRing(rings[i], !outer);\n }\n}\n\nfunction rewindRing(ring, dir) {\n var area = 0, err = 0;\n for (var i = 0, len = ring.length, j = len - 1; i < len; j = i++) {\n var k = (ring[i][0] - ring[j][0]) * (ring[j][1] + ring[i][1]);\n var m = area + k;\n err += Math.abs(area) >= Math.abs(k) ? area - m + k : k - m + area;\n area = m;\n }\n if (area + err >= 0 !== !!dir) ring.reverse();\n}\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport {VectorTileFeature} from '@mapbox/vector-tile';\n// $FlowFixMe[method-unbinding]\nconst toGeoJSON = VectorTileFeature.prototype.toGeoJSON;\nimport EXTENT from '../data/extent.js';\n\nimport type {GeoJSONFeature} from '@mapbox/geojson-types';\nimport type {IVectorTile, IVectorTileLayer, IVectorTileFeature} from '@mapbox/vector-tile';\n\n// The feature type used by geojson-vt and supercluster. Should be extracted to\n// global type and used in module definitions for those two modules.\ntype Feature = {\n type: 1,\n id: mixed,\n tags: {[_: string]: string | number | boolean},\n geometry: Array<[number, number]>,\n} | {\n type: 2 | 3,\n id: mixed,\n tags: {[_: string]: string | number | boolean},\n geometry: Array<Array<[number, number]>>,\n}\n\nclass FeatureWrapper implements IVectorTileFeature {\n _feature: Feature;\n\n extent: number;\n type: 1 | 2 | 3;\n id: number;\n properties: {[_: string]: string | number | boolean};\n\n constructor(feature: Feature) {\n this._feature = feature;\n\n this.extent = EXTENT;\n this.type = feature.type;\n this.properties = feature.tags;\n\n // If the feature has a top-level `id` property, copy it over, but only\n // if it can be coerced to an integer, because this wrapper is used for\n // serializing geojson feature data into vector tile PBF data, and the\n // vector tile spec only supports integer values for feature ids --\n // allowing non-integer values here results in a non-compliant PBF\n // that causes an exception when it is parsed with vector-tile-js\n if ('id' in feature && !isNaN(feature.id)) {\n this.id = parseInt(feature.id, 10);\n }\n }\n\n loadGeometry(): Array<Array<Point>> {\n if (this._feature.type === 1) {\n const geometry = [];\n for (const point of this._feature.geometry) {\n geometry.push([new Point(point[0], point[1])]);\n }\n return geometry;\n } else {\n const geometry = [];\n for (const ring of this._feature.geometry) {\n const newRing = [];\n for (const point of ring) {\n newRing.push(new Point(point[0], point[1]));\n }\n geometry.push(newRing);\n }\n return geometry;\n }\n }\n\n toGeoJSON(x: number, y: number, z: number): GeoJSONFeature {\n return toGeoJSON.call(this, x, y, z);\n }\n}\n\nclass GeoJSONWrapper implements IVectorTile, IVectorTileLayer {\n layers: {[_: string]: IVectorTileLayer};\n name: string;\n extent: number;\n length: number;\n _features: Array<Feature>;\n\n constructor(features: Array<Feature>) {\n this.layers = {'_geojsonTileLayer': this};\n this.name = '_geojsonTileLayer';\n this.extent = EXTENT;\n this.length = features.length;\n this._features = features;\n }\n\n feature(i: number): IVectorTileFeature {\n return new FeatureWrapper(this._features[i]);\n }\n}\n\nexport default GeoJSONWrapper;\n","'use strict'\n\nvar Point = require('@mapbox/point-geometry')\nvar VectorTileFeature = require('@mapbox/vector-tile').VectorTileFeature\n\nmodule.exports = GeoJSONWrapper\n\n// conform to vectortile api\nfunction GeoJSONWrapper (features, options) {\n this.options = options || {}\n this.features = features\n this.length = features.length\n}\n\nGeoJSONWrapper.prototype.feature = function (i) {\n return new FeatureWrapper(this.features[i], this.options.extent)\n}\n\nfunction FeatureWrapper (feature, extent) {\n this.id = typeof feature.id === 'number' ? feature.id : undefined\n this.type = feature.type\n this.rawGeometry = feature.type === 1 ? [feature.geometry] : feature.geometry\n this.properties = feature.tags\n this.extent = extent || 4096\n}\n\nFeatureWrapper.prototype.loadGeometry = function () {\n var rings = this.rawGeometry\n this.geometry = []\n\n for (var i = 0; i < rings.length; i++) {\n var ring = rings[i]\n var newRing = []\n for (var j = 0; j < ring.length; j++) {\n newRing.push(new Point(ring[j][0], ring[j][1]))\n }\n this.geometry.push(newRing)\n }\n return this.geometry\n}\n\nFeatureWrapper.prototype.bbox = function () {\n if (!this.geometry) this.loadGeometry()\n\n var rings = this.geometry\n var x1 = Infinity\n var x2 = -Infinity\n var y1 = Infinity\n var y2 = -Infinity\n\n for (var i = 0; i < rings.length; i++) {\n var ring = rings[i]\n\n for (var j = 0; j < ring.length; j++) {\n var coord = ring[j]\n\n x1 = Math.min(x1, coord.x)\n x2 = Math.max(x2, coord.x)\n y1 = Math.min(y1, coord.y)\n y2 = Math.max(y2, coord.y)\n }\n }\n\n return [x1, y1, x2, y2]\n}\n\nFeatureWrapper.prototype.toGeoJSON = VectorTileFeature.prototype.toGeoJSON\n","var Pbf = require('pbf')\nvar GeoJSONWrapper = require('./lib/geojson_wrapper')\n\nmodule.exports = fromVectorTileJs\nmodule.exports.fromVectorTileJs = fromVectorTileJs\nmodule.exports.fromGeojsonVt = fromGeojsonVt\nmodule.exports.GeoJSONWrapper = GeoJSONWrapper\n\n/**\n * Serialize a vector-tile-js-created tile to pbf\n *\n * @param {Object} tile\n * @return {Buffer} uncompressed, pbf-serialized tile data\n */\nfunction fromVectorTileJs (tile) {\n var out = new Pbf()\n writeTile(tile, out)\n return out.finish()\n}\n\n/**\n * Serialized a geojson-vt-created tile to pbf.\n *\n * @param {Object} layers - An object mapping layer names to geojson-vt-created vector tile objects\n * @param {Object} [options] - An object specifying the vector-tile specification version and extent that were used to create `layers`.\n * @param {Number} [options.version=1] - Version of vector-tile spec used\n * @param {Number} [options.extent=4096] - Extent of the vector tile\n * @return {Buffer} uncompressed, pbf-serialized tile data\n */\nfunction fromGeojsonVt (layers, options) {\n options = options || {}\n var l = {}\n for (var k in layers) {\n l[k] = new GeoJSONWrapper(layers[k].features, options)\n l[k].name = k\n l[k].version = options.version\n l[k].extent = options.extent\n }\n return fromVectorTileJs({ layers: l })\n}\n\nfunction writeTile (tile, pbf) {\n for (var key in tile.layers) {\n pbf.writeMessage(3, writeLayer, tile.layers[key])\n }\n}\n\nfunction writeLayer (layer, pbf) {\n pbf.writeVarintField(15, layer.version || 1)\n pbf.writeStringField(1, layer.name || '')\n pbf.writeVarintField(5, layer.extent || 4096)\n\n var i\n var context = {\n keys: [],\n values: [],\n keycache: {},\n valuecache: {}\n }\n\n for (i = 0; i < layer.length; i++) {\n context.feature = layer.feature(i)\n pbf.writeMessage(2, writeFeature, context)\n }\n\n var keys = context.keys\n for (i = 0; i < keys.length; i++) {\n pbf.writeStringField(3, keys[i])\n }\n\n var values = context.values\n for (i = 0; i < values.length; i++) {\n pbf.writeMessage(4, writeValue, values[i])\n }\n}\n\nfunction writeFeature (context, pbf) {\n var feature = context.feature\n\n if (feature.id !== undefined) {\n pbf.writeVarintField(1, feature.id)\n }\n\n pbf.writeMessage(2, writeProperties, context)\n pbf.writeVarintField(3, feature.type)\n pbf.writeMessage(4, writeGeometry, feature)\n}\n\nfunction writeProperties (context, pbf) {\n var feature = context.feature\n var keys = context.keys\n var values = context.values\n var keycache = context.keycache\n var valuecache = context.valuecache\n\n for (var key in feature.properties) {\n var value = feature.properties[key]\n\n var keyIndex = keycache[key]\n if (value === null) continue // don't encode null value properties\n\n if (typeof keyIndex === 'undefined') {\n keys.push(key)\n keyIndex = keys.length - 1\n keycache[key] = keyIndex\n }\n pbf.writeVarint(keyIndex)\n\n var type = typeof value\n if (type !== 'string' && type !== 'boolean' && type !== 'number') {\n value = JSON.stringify(value)\n }\n var valueKey = type + ':' + value\n var valueIndex = valuecache[valueKey]\n if (typeof valueIndex === 'undefined') {\n values.push(value)\n valueIndex = values.length - 1\n valuecache[valueKey] = valueIndex\n }\n pbf.writeVarint(valueIndex)\n }\n}\n\nfunction command (cmd, length) {\n return (length << 3) + (cmd & 0x7)\n}\n\nfunction zigzag (num) {\n return (num << 1) ^ (num >> 31)\n}\n\nfunction writeGeometry (feature, pbf) {\n var geometry = feature.loadGeometry()\n var type = feature.type\n var x = 0\n var y = 0\n var rings = geometry.length\n for (var r = 0; r < rings; r++) {\n var ring = geometry[r]\n var count = 1\n if (type === 1) {\n count = ring.length\n }\n pbf.writeVarint(command(1, count)) // moveto\n // do not write polygon closing path as lineto\n var lineCount = type === 3 ? ring.length - 1 : ring.length\n for (var i = 0; i < lineCount; i++) {\n if (i === 1 && type !== 1) {\n pbf.writeVarint(command(2, lineCount - 1)) // lineto\n }\n var dx = ring[i].x - x\n var dy = ring[i].y - y\n pbf.writeVarint(zigzag(dx))\n pbf.writeVarint(zigzag(dy))\n x += dx\n y += dy\n }\n if (type === 3) {\n pbf.writeVarint(command(7, 1)) // closepath\n }\n }\n}\n\nfunction writeValue (value, pbf) {\n var type = typeof value\n if (type === 'string') {\n pbf.writeStringField(1, value)\n } else if (type === 'boolean') {\n pbf.writeBooleanField(7, value)\n } else if (type === 'number') {\n if (value % 1 !== 0) {\n pbf.writeDoubleField(3, value)\n } else if (value < 0) {\n pbf.writeSVarintField(6, value)\n } else {\n pbf.writeVarintField(5, value)\n }\n }\n}\n","\nconst ARRAY_TYPES = [\n Int8Array, Uint8Array, Uint8ClampedArray, Int16Array, Uint16Array,\n Int32Array, Uint32Array, Float32Array, Float64Array\n];\n\n/** @typedef {Int8ArrayConstructor | Uint8ArrayConstructor | Uint8ClampedArrayConstructor | Int16ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor} TypedArrayConstructor */\n\nconst VERSION = 1; // serialized format version\nconst HEADER_SIZE = 8;\n\nexport default class KDBush {\n\n /**\n * Creates an index from raw `ArrayBuffer` data.\n * @param {ArrayBuffer} data\n */\n static from(data) {\n if (!(data instanceof ArrayBuffer)) {\n throw new Error('Data must be an instance of ArrayBuffer.');\n }\n const [magic, versionAndType] = new Uint8Array(data, 0, 2);\n if (magic !== 0xdb) {\n throw new Error('Data does not appear to be in a KDBush format.');\n }\n const version = versionAndType >> 4;\n if (version !== VERSION) {\n throw new Error(`Got v${version} data when expected v${VERSION}.`);\n }\n const ArrayType = ARRAY_TYPES[versionAndType & 0x0f];\n if (!ArrayType) {\n throw new Error('Unrecognized array type.');\n }\n const [nodeSize] = new Uint16Array(data, 2, 1);\n const [numItems] = new Uint32Array(data, 4, 1);\n\n return new KDBush(numItems, nodeSize, ArrayType, data);\n }\n\n /**\n * Creates an index that will hold a given number of items.\n * @param {number} numItems\n * @param {number} [nodeSize=64] Size of the KD-tree node (64 by default).\n * @param {TypedArrayConstructor} [ArrayType=Float64Array] The array type used for coordinates storage (`Float64Array` by default).\n * @param {ArrayBuffer} [data] (For internal use only)\n */\n constructor(numItems, nodeSize = 64, ArrayType = Float64Array, data) {\n if (isNaN(numItems) || numItems < 0) throw new Error(`Unpexpected numItems value: ${numItems}.`);\n\n this.numItems = +numItems;\n this.nodeSize = Math.min(Math.max(+nodeSize, 2), 65535);\n this.ArrayType = ArrayType;\n this.IndexArrayType = numItems < 65536 ? Uint16Array : Uint32Array;\n\n const arrayTypeIndex = ARRAY_TYPES.indexOf(this.ArrayType);\n const coordsByteSize = numItems * 2 * this.ArrayType.BYTES_PER_ELEMENT;\n const idsByteSize = numItems * this.IndexArrayType.BYTES_PER_ELEMENT;\n const padCoords = (8 - idsByteSize % 8) % 8;\n\n if (arrayTypeIndex < 0) {\n throw new Error(`Unexpected typed array class: ${ArrayType}.`);\n }\n\n if (data && (data instanceof ArrayBuffer)) { // reconstruct an index from a buffer\n this.data = data;\n this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);\n this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);\n this._pos = numItems * 2;\n this._finished = true;\n } else { // initialize a new index\n this.data = new ArrayBuffer(HEADER_SIZE + coordsByteSize + idsByteSize + padCoords);\n this.ids = new this.IndexArrayType(this.data, HEADER_SIZE, numItems);\n this.coords = new this.ArrayType(this.data, HEADER_SIZE + idsByteSize + padCoords, numItems * 2);\n this._pos = 0;\n this._finished = false;\n\n // set header\n new Uint8Array(this.data, 0, 2).set([0xdb, (VERSION << 4) + arrayTypeIndex]);\n new Uint16Array(this.data, 2, 1)[0] = nodeSize;\n new Uint32Array(this.data, 4, 1)[0] = numItems;\n }\n }\n\n /**\n * Add a point to the index.\n * @param {number} x\n * @param {number} y\n * @returns {number} An incremental index associated with the added item (starting from `0`).\n */\n add(x, y) {\n const index = this._pos >> 1;\n this.ids[index] = index;\n this.coords[this._pos++] = x;\n this.coords[this._pos++] = y;\n return index;\n }\n\n /**\n * Perform indexing of the added points.\n */\n finish() {\n const numAdded = this._pos >> 1;\n if (numAdded !== this.numItems) {\n throw new Error(`Added ${numAdded} items when expected ${this.numItems}.`);\n }\n // kd-sort both arrays for efficient search\n sort(this.ids, this.coords, this.nodeSize, 0, this.numItems - 1, 0);\n\n this._finished = true;\n return this;\n }\n\n /**\n * Search the index for items within a given bounding box.\n * @param {number} minX\n * @param {number} minY\n * @param {number} maxX\n * @param {number} maxY\n * @returns {number[]} An array of indices correponding to the found items.\n */\n range(minX, minY, maxX, maxY) {\n if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');\n\n const {ids, coords, nodeSize} = this;\n const stack = [0, ids.length - 1, 0];\n const result = [];\n\n // recursively search for items in range in the kd-sorted arrays\n while (stack.length) {\n const axis = stack.pop() || 0;\n const right = stack.pop() || 0;\n const left = stack.pop() || 0;\n\n // if we reached \"tree node\", search linearly\n if (right - left <= nodeSize) {\n for (let i = left; i <= right; i++) {\n const x = coords[2 * i];\n const y = coords[2 * i + 1];\n if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);\n }\n continue;\n }\n\n // otherwise find the middle index\n const m = (left + right) >> 1;\n\n // include the middle item if it's in range\n const x = coords[2 * m];\n const y = coords[2 * m + 1];\n if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);\n\n // queue search in halves that intersect the query\n if (axis === 0 ? minX <= x : minY <= y) {\n stack.push(left);\n stack.push(m - 1);\n stack.push(1 - axis);\n }\n if (axis === 0 ? maxX >= x : maxY >= y) {\n stack.push(m + 1);\n stack.push(right);\n stack.push(1 - axis);\n }\n }\n\n return result;\n }\n\n /**\n * Search the index for items within a given radius.\n * @param {number} qx\n * @param {number} qy\n * @param {number} r Query radius.\n * @returns {number[]} An array of indices correponding to the found items.\n */\n within(qx, qy, r) {\n if (!this._finished) throw new Error('Data not yet indexed - call index.finish().');\n\n const {ids, coords, nodeSize} = this;\n const stack = [0, ids.length - 1, 0];\n const result = [];\n const r2 = r * r;\n\n // recursively search for items within radius in the kd-sorted arrays\n while (stack.length) {\n const axis = stack.pop() || 0;\n const right = stack.pop() || 0;\n const left = stack.pop() || 0;\n\n // if we reached \"tree node\", search linearly\n if (right - left <= nodeSize) {\n for (let i = left; i <= right; i++) {\n if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]);\n }\n continue;\n }\n\n // otherwise find the middle index\n const m = (left + right) >> 1;\n\n // include the middle item if it's in range\n const x = coords[2 * m];\n const y = coords[2 * m + 1];\n if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]);\n\n // queue search in halves that intersect the query\n if (axis === 0 ? qx - r <= x : qy - r <= y) {\n stack.push(left);\n stack.push(m - 1);\n stack.push(1 - axis);\n }\n if (axis === 0 ? qx + r >= x : qy + r >= y) {\n stack.push(m + 1);\n stack.push(right);\n stack.push(1 - axis);\n }\n }\n\n return result;\n }\n}\n\n/**\n * @param {Uint16Array | Uint32Array} ids\n * @param {InstanceType<TypedArrayConstructor>} coords\n * @param {number} nodeSize\n * @param {number} left\n * @param {number} right\n * @param {number} axis\n */\nfunction sort(ids, coords, nodeSize, left, right, axis) {\n if (right - left <= nodeSize) return;\n\n const m = (left + right) >> 1; // middle index\n\n // sort ids and coords around the middle index so that the halves lie\n // either left/right or top/bottom correspondingly (taking turns)\n select(ids, coords, m, left, right, axis);\n\n // recursively kd-sort first half and second half on the opposite axis\n sort(ids, coords, nodeSize, left, m - 1, 1 - axis);\n sort(ids, coords, nodeSize, m + 1, right, 1 - axis);\n}\n\n/**\n * Custom Floyd-Rivest selection algorithm: sort ids and coords so that\n * [left..k-1] items are smaller than k-th item (on either x or y axis)\n * @param {Uint16Array | Uint32Array} ids\n * @param {InstanceType<TypedArrayConstructor>} coords\n * @param {number} k\n * @param {number} left\n * @param {number} right\n * @param {number} axis\n */\nfunction select(ids, coords, k, left, right, axis) {\n\n while (right > left) {\n if (right - left > 600) {\n const n = right - left + 1;\n const m = k - left + 1;\n const z = Math.log(n);\n const s = 0.5 * Math.exp(2 * z / 3);\n const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n select(ids, coords, k, newLeft, newRight, axis);\n }\n\n const t = coords[2 * k + axis];\n let i = left;\n let j = right;\n\n swapItem(ids, coords, left, k);\n if (coords[2 * right + axis] > t) swapItem(ids, coords, left, right);\n\n while (i < j) {\n swapItem(ids, coords, i, j);\n i++;\n j--;\n while (coords[2 * i + axis] < t) i++;\n while (coords[2 * j + axis] > t) j--;\n }\n\n if (coords[2 * left + axis] === t) swapItem(ids, coords, left, j);\n else {\n j++;\n swapItem(ids, coords, j, right);\n }\n\n if (j <= k) left = j + 1;\n if (k <= j) right = j - 1;\n }\n}\n\n/**\n * @param {Uint16Array | Uint32Array} ids\n * @param {InstanceType<TypedArrayConstructor>} coords\n * @param {number} i\n * @param {number} j\n */\nfunction swapItem(ids, coords, i, j) {\n swap(ids, i, j);\n swap(coords, 2 * i, 2 * j);\n swap(coords, 2 * i + 1, 2 * j + 1);\n}\n\n/**\n * @param {InstanceType<TypedArrayConstructor>} arr\n * @param {number} i\n * @param {number} j\n */\nfunction swap(arr, i, j) {\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n\n/**\n * @param {number} ax\n * @param {number} ay\n * @param {number} bx\n * @param {number} by\n */\nfunction sqDist(ax, ay, bx, by) {\n const dx = ax - bx;\n const dy = ay - by;\n return dx * dx + dy * dy;\n}\n","\nimport KDBush from 'kdbush';\n\nconst defaultOptions = {\n minZoom: 0, // min zoom to generate clusters on\n maxZoom: 16, // max zoom level to cluster the points on\n minPoints: 2, // minimum points to form a cluster\n radius: 40, // cluster radius in pixels\n extent: 512, // tile extent (radius is calculated relative to it)\n nodeSize: 64, // size of the KD-tree leaf node, affects performance\n log: false, // whether to log timing info\n\n // whether to generate numeric ids for input features (in vector tiles)\n generateId: false,\n\n // a reduce function for calculating custom cluster properties\n reduce: null, // (accumulated, props) => { accumulated.sum += props.sum; }\n\n // properties to use for individual points when running the reducer\n map: props => props // props => ({sum: props.my_value})\n};\n\nconst fround = Math.fround || (tmp => ((x) => { tmp[0] = +x; return tmp[0]; }))(new Float32Array(1));\n\nconst OFFSET_ZOOM = 2;\nconst OFFSET_ID = 3;\nconst OFFSET_PARENT = 4;\nconst OFFSET_NUM = 5;\nconst OFFSET_PROP = 6;\n\nexport default class Supercluster {\n constructor(options) {\n this.options = Object.assign(Object.create(defaultOptions), options);\n this.trees = new Array(this.options.maxZoom + 1);\n this.stride = this.options.reduce ? 7 : 6;\n this.clusterProps = [];\n }\n\n load(points) {\n const {log, minZoom, maxZoom} = this.options;\n\n if (log) console.time('total time');\n\n const timerId = `prepare ${ points.length } points`;\n if (log) console.time(timerId);\n\n this.points = points;\n\n // generate a cluster object for each point and index input points into a KD-tree\n const data = [];\n\n for (let i = 0; i < points.length; i++) {\n const p = points[i];\n if (!p.geometry) continue;\n\n const [lng, lat] = p.geometry.coordinates;\n const x = fround(lngX(lng));\n const y = fround(latY(lat));\n // store internal point/cluster data in flat numeric arrays for performance\n data.push(\n x, y, // projected point coordinates\n Infinity, // the last zoom the point was processed at\n i, // index of the source feature in the original input array\n -1, // parent cluster id\n 1 // number of points in a cluster\n );\n if (this.options.reduce) data.push(0); // noop\n }\n let tree = this.trees[maxZoom + 1] = this._createTree(data);\n\n if (log) console.timeEnd(timerId);\n\n // cluster points on max zoom, then cluster the results on previous zoom, etc.;\n // results in a cluster hierarchy across zoom levels\n for (let z = maxZoom; z >= minZoom; z--) {\n const now = +Date.now();\n\n // create a new set of clusters for the zoom and index them with a KD-tree\n tree = this.trees[z] = this._createTree(this._cluster(tree, z));\n\n if (log) console.log('z%d: %d clusters in %dms', z, tree.numItems, +Date.now() - now);\n }\n\n if (log) console.timeEnd('total time');\n\n return this;\n }\n\n getClusters(bbox, zoom) {\n let minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180;\n const minLat = Math.max(-90, Math.min(90, bbox[1]));\n let maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180;\n const maxLat = Math.max(-90, Math.min(90, bbox[3]));\n\n if (bbox[2] - bbox[0] >= 360) {\n minLng = -180;\n maxLng = 180;\n } else if (minLng > maxLng) {\n const easternHem = this.getClusters([minLng, minLat, 180, maxLat], zoom);\n const westernHem = this.getClusters([-180, minLat, maxLng, maxLat], zoom);\n return easternHem.concat(westernHem);\n }\n\n const tree = this.trees[this._limitZoom(zoom)];\n const ids = tree.range(lngX(minLng), latY(maxLat), lngX(maxLng), latY(minLat));\n const data = tree.data;\n const clusters = [];\n for (const id of ids) {\n const k = this.stride * id;\n clusters.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]);\n }\n return clusters;\n }\n\n getChildren(clusterId) {\n const originId = this._getOriginId(clusterId);\n const originZoom = this._getOriginZoom(clusterId);\n const errorMsg = 'No cluster with the specified id.';\n\n const tree = this.trees[originZoom];\n if (!tree) throw new Error(errorMsg);\n\n const data = tree.data;\n if (originId * this.stride >= data.length) throw new Error(errorMsg);\n\n const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1));\n const x = data[originId * this.stride];\n const y = data[originId * this.stride + 1];\n const ids = tree.within(x, y, r);\n const children = [];\n for (const id of ids) {\n const k = id * this.stride;\n if (data[k + OFFSET_PARENT] === clusterId) {\n children.push(data[k + OFFSET_NUM] > 1 ? getClusterJSON(data, k, this.clusterProps) : this.points[data[k + OFFSET_ID]]);\n }\n }\n\n if (children.length === 0) throw new Error(errorMsg);\n\n return children;\n }\n\n getLeaves(clusterId, limit, offset) {\n limit = limit || 10;\n offset = offset || 0;\n\n const leaves = [];\n this._appendLeaves(leaves, clusterId, limit, offset, 0);\n\n return leaves;\n }\n\n getTile(z, x, y) {\n const tree = this.trees[this._limitZoom(z)];\n const z2 = Math.pow(2, z);\n const {extent, radius} = this.options;\n const p = radius / extent;\n const top = (y - p) / z2;\n const bottom = (y + 1 + p) / z2;\n\n const tile = {\n features: []\n };\n\n this._addTileFeatures(\n tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom),\n tree.data, x, y, z2, tile);\n\n if (x === 0) {\n this._addTileFeatures(\n tree.range(1 - p / z2, top, 1, bottom),\n tree.data, z2, y, z2, tile);\n }\n if (x === z2 - 1) {\n this._addTileFeatures(\n tree.range(0, top, p / z2, bottom),\n tree.data, -1, y, z2, tile);\n }\n\n return tile.features.length ? tile : null;\n }\n\n getClusterExpansionZoom(clusterId) {\n let expansionZoom = this._getOriginZoom(clusterId) - 1;\n while (expansionZoom <= this.options.maxZoom) {\n const children = this.getChildren(clusterId);\n expansionZoom++;\n if (children.length !== 1) break;\n clusterId = children[0].properties.cluster_id;\n }\n return expansionZoom;\n }\n\n _appendLeaves(result, clusterId, limit, offset, skipped) {\n const children = this.getChildren(clusterId);\n\n for (const child of children) {\n const props = child.properties;\n\n if (props && props.cluster) {\n if (skipped + props.point_count <= offset) {\n // skip the whole cluster\n skipped += props.point_count;\n } else {\n // enter the cluster\n skipped = this._appendLeaves(result, props.cluster_id, limit, offset, skipped);\n // exit the cluster\n }\n } else if (skipped < offset) {\n // skip a single point\n skipped++;\n } else {\n // add a single point\n result.push(child);\n }\n if (result.length === limit) break;\n }\n\n return skipped;\n }\n\n _createTree(data) {\n const tree = new KDBush(data.length / this.stride | 0, this.options.nodeSize, Float32Array);\n for (let i = 0; i < data.length; i += this.stride) tree.add(data[i], data[i + 1]);\n tree.finish();\n tree.data = data;\n return tree;\n }\n\n _addTileFeatures(ids, data, x, y, z2, tile) {\n for (const i of ids) {\n const k = i * this.stride;\n const isCluster = data[k + OFFSET_NUM] > 1;\n\n let tags, px, py;\n if (isCluster) {\n tags = getClusterProperties(data, k, this.clusterProps);\n px = data[k];\n py = data[k + 1];\n } else {\n const p = this.points[data[k + OFFSET_ID]];\n tags = p.properties;\n const [lng, lat] = p.geometry.coordinates;\n px = lngX(lng);\n py = latY(lat);\n }\n\n const f = {\n type: 1,\n geometry: [[\n Math.round(this.options.extent * (px * z2 - x)),\n Math.round(this.options.extent * (py * z2 - y))\n ]],\n tags\n };\n\n // assign id\n let id;\n if (isCluster || this.options.generateId) {\n // optionally generate id for points\n id = data[k + OFFSET_ID];\n } else {\n // keep id if already assigned\n id = this.points[data[k + OFFSET_ID]].id;\n }\n\n if (id !== undefined) f.id = id;\n\n tile.features.push(f);\n }\n }\n\n _limitZoom(z) {\n return Math.max(this.options.minZoom, Math.min(Math.floor(+z), this.options.maxZoom + 1));\n }\n\n _cluster(tree, zoom) {\n const {radius, extent, reduce, minPoints} = this.options;\n const r = radius / (extent * Math.pow(2, zoom));\n const data = tree.data;\n const nextData = [];\n const stride = this.stride;\n\n // loop through each point\n for (let i = 0; i < data.length; i += stride) {\n // if we've already visited the point at this zoom level, skip it\n if (data[i + OFFSET_ZOOM] <= zoom) continue;\n data[i + OFFSET_ZOOM] = zoom;\n\n // find all nearby points\n const x = data[i];\n const y = data[i + 1];\n const neighborIds = tree.within(data[i], data[i + 1], r);\n\n const numPointsOrigin = data[i + OFFSET_NUM];\n let numPoints = numPointsOrigin;\n\n // count the number of points in a potential cluster\n for (const neighborId of neighborIds) {\n const k = neighborId * stride;\n // filter out neighbors that are already processed\n if (data[k + OFFSET_ZOOM] > zoom) numPoints += data[k + OFFSET_NUM];\n }\n\n // if there were neighbors to merge, and there are enough points to form a cluster\n if (numPoints > numPointsOrigin && numPoints >= minPoints) {\n let wx = x * numPointsOrigin;\n let wy = y * numPointsOrigin;\n\n let clusterProperties;\n let clusterPropIndex = -1;\n\n // encode both zoom and point index on which the cluster originated -- offset by total length of features\n const id = ((i / stride | 0) << 5) + (zoom + 1) + this.points.length;\n\n for (const neighborId of neighborIds) {\n const k = neighborId * stride;\n\n if (data[k + OFFSET_ZOOM] <= zoom) continue;\n data[k + OFFSET_ZOOM] = zoom; // save the zoom (so it doesn't get processed twice)\n\n const numPoints2 = data[k + OFFSET_NUM];\n wx += data[k] * numPoints2; // accumulate coordinates for calculating weighted center\n wy += data[k + 1] * numPoints2;\n\n data[k + OFFSET_PARENT] = id;\n\n if (reduce) {\n if (!clusterProperties) {\n clusterProperties = this._map(data, i, true);\n clusterPropIndex = this.clusterProps.length;\n this.clusterProps.push(clusterProperties);\n }\n reduce(clusterProperties, this._map(data, k));\n }\n }\n\n data[i + OFFSET_PARENT] = id;\n nextData.push(wx / numPoints, wy / numPoints, Infinity, id, -1, numPoints);\n if (reduce) nextData.push(clusterPropIndex);\n\n } else { // left points as unclustered\n for (let j = 0; j < stride; j++) nextData.push(data[i + j]);\n\n if (numPoints > 1) {\n for (const neighborId of neighborIds) {\n const k = neighborId * stride;\n if (data[k + OFFSET_ZOOM] <= zoom) continue;\n data[k + OFFSET_ZOOM] = zoom;\n for (let j = 0; j < stride; j++) nextData.push(data[k + j]);\n }\n }\n }\n }\n\n return nextData;\n }\n\n // get index of the point from which the cluster originated\n _getOriginId(clusterId) {\n return (clusterId - this.points.length) >> 5;\n }\n\n // get zoom of the point from which the cluster originated\n _getOriginZoom(clusterId) {\n return (clusterId - this.points.length) % 32;\n }\n\n _map(data, i, clone) {\n if (data[i + OFFSET_NUM] > 1) {\n const props = this.clusterProps[data[i + OFFSET_PROP]];\n return clone ? Object.assign({}, props) : props;\n }\n const original = this.points[data[i + OFFSET_ID]].properties;\n const result = this.options.map(original);\n return clone && result === original ? Object.assign({}, result) : result;\n }\n}\n\nfunction getClusterJSON(data, i, clusterProps) {\n return {\n type: 'Feature',\n id: data[i + OFFSET_ID],\n properties: getClusterProperties(data, i, clusterProps),\n geometry: {\n type: 'Point',\n coordinates: [xLng(data[i]), yLat(data[i + 1])]\n }\n };\n}\n\nfunction getClusterProperties(data, i, clusterProps) {\n const count = data[i + OFFSET_NUM];\n const abbrev =\n count >= 10000 ? `${Math.round(count / 1000) }k` :\n count >= 1000 ? `${Math.round(count / 100) / 10 }k` : count;\n const propIndex = data[i + OFFSET_PROP];\n const properties = propIndex === -1 ? {} : Object.assign({}, clusterProps[propIndex]);\n return Object.assign(properties, {\n cluster: true,\n cluster_id: data[i + OFFSET_ID],\n point_count: count,\n point_count_abbreviated: abbrev\n });\n}\n\n// longitude/latitude to spherical mercator in [0..1] range\nfunction lngX(lng) {\n return lng / 360 + 0.5;\n}\nfunction latY(lat) {\n const sin = Math.sin(lat * Math.PI / 180);\n const y = (0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI);\n return y < 0 ? 0 : y > 1 ? 1 : y;\n}\n\n// spherical mercator to longitude/latitude\nfunction xLng(x) {\n return (x - 0.5) * 360;\n}\nfunction yLat(y) {\n const y2 = (180 - y * 360) * Math.PI / 180;\n return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90;\n}\n","\n// calculate simplification data using optimized Douglas-Peucker algorithm\n\nexport default function simplify(coords, first, last, sqTolerance) {\n var maxSqDist = sqTolerance;\n var mid = (last - first) >> 1;\n var minPosToMid = last - first;\n var index;\n\n var ax = coords[first];\n var ay = coords[first + 1];\n var bx = coords[last];\n var by = coords[last + 1];\n\n for (var i = first + 3; i < last; i += 3) {\n var d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by);\n\n if (d > maxSqDist) {\n index = i;\n maxSqDist = d;\n\n } else if (d === maxSqDist) {\n // a workaround to ensure we choose a pivot close to the middle of the list,\n // reducing recursion depth, for certain degenerate inputs\n // https://github.com/mapbox/geojson-vt/issues/104\n var posToMid = Math.abs(i - mid);\n if (posToMid < minPosToMid) {\n index = i;\n minPosToMid = posToMid;\n }\n }\n }\n\n if (maxSqDist > sqTolerance) {\n if (index - first > 3) simplify(coords, first, index, sqTolerance);\n coords[index + 2] = maxSqDist;\n if (last - index > 3) simplify(coords, index, last, sqTolerance);\n }\n}\n\n// square distance from a point to a segment\nfunction getSqSegDist(px, py, x, y, bx, by) {\n\n var dx = bx - x;\n var dy = by - y;\n\n if (dx !== 0 || dy !== 0) {\n\n var t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);\n\n if (t > 1) {\n x = bx;\n y = by;\n\n } else if (t > 0) {\n x += dx * t;\n y += dy * t;\n }\n }\n\n dx = px - x;\n dy = py - y;\n\n return dx * dx + dy * dy;\n}\n","\nexport default function createFeature(id, type, geom, tags) {\n var feature = {\n id: typeof id === 'undefined' ? null : id,\n type: type,\n geometry: geom,\n tags: tags,\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity\n };\n calcBBox(feature);\n return feature;\n}\n\nfunction calcBBox(feature) {\n var geom = feature.geometry;\n var type = feature.type;\n\n if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') {\n calcLineBBox(feature, geom);\n\n } else if (type === 'Polygon' || type === 'MultiLineString') {\n for (var i = 0; i < geom.length; i++) {\n calcLineBBox(feature, geom[i]);\n }\n\n } else if (type === 'MultiPolygon') {\n for (i = 0; i < geom.length; i++) {\n for (var j = 0; j < geom[i].length; j++) {\n calcLineBBox(feature, geom[i][j]);\n }\n }\n }\n}\n\nfunction calcLineBBox(feature, geom) {\n for (var i = 0; i < geom.length; i += 3) {\n feature.minX = Math.min(feature.minX, geom[i]);\n feature.minY = Math.min(feature.minY, geom[i + 1]);\n feature.maxX = Math.max(feature.maxX, geom[i]);\n feature.maxY = Math.max(feature.maxY, geom[i + 1]);\n }\n}\n","\nimport simplify from './simplify';\nimport createFeature from './feature';\n\n// converts GeoJSON feature into an intermediate projected JSON vector format with simplification data\n\nexport default function convert(data, options) {\n var features = [];\n if (data.type === 'FeatureCollection') {\n for (var i = 0; i < data.features.length; i++) {\n convertFeature(features, data.features[i], options, i);\n }\n\n } else if (data.type === 'Feature') {\n convertFeature(features, data, options);\n\n } else {\n // single geometry or a geometry collection\n convertFeature(features, {geometry: data}, options);\n }\n\n return features;\n}\n\nfunction convertFeature(features, geojson, options, index) {\n if (!geojson.geometry) return;\n\n var coords = geojson.geometry.coordinates;\n var type = geojson.geometry.type;\n var tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2);\n var geometry = [];\n var id = geojson.id;\n if (options.promoteId) {\n id = geojson.properties[options.promoteId];\n } else if (options.generateId) {\n id = index || 0;\n }\n if (type === 'Point') {\n convertPoint(coords, geometry);\n\n } else if (type === 'MultiPoint') {\n for (var i = 0; i < coords.length; i++) {\n convertPoint(coords[i], geometry);\n }\n\n } else if (type === 'LineString') {\n convertLine(coords, geometry, tolerance, false);\n\n } else if (type === 'MultiLineString') {\n if (options.lineMetrics) {\n // explode into linestrings to be able to track metrics\n for (i = 0; i < coords.length; i++) {\n geometry = [];\n convertLine(coords[i], geometry, tolerance, false);\n features.push(createFeature(id, 'LineString', geometry, geojson.properties));\n }\n return;\n } else {\n convertLines(coords, geometry, tolerance, false);\n }\n\n } else if (type === 'Polygon') {\n convertLines(coords, geometry, tolerance, true);\n\n } else if (type === 'MultiPolygon') {\n for (i = 0; i < coords.length; i++) {\n var polygon = [];\n convertLines(coords[i], polygon, tolerance, true);\n geometry.push(polygon);\n }\n } else if (type === 'GeometryCollection') {\n for (i = 0; i < geojson.geometry.geometries.length; i++) {\n convertFeature(features, {\n id: id,\n geometry: geojson.geometry.geometries[i],\n properties: geojson.properties\n }, options, index);\n }\n return;\n } else {\n throw new Error('Input data is not a valid GeoJSON object.');\n }\n\n features.push(createFeature(id, type, geometry, geojson.properties));\n}\n\nfunction convertPoint(coords, out) {\n out.push(projectX(coords[0]));\n out.push(projectY(coords[1]));\n out.push(0);\n}\n\nfunction convertLine(ring, out, tolerance, isPolygon) {\n var x0, y0;\n var size = 0;\n\n for (var j = 0; j < ring.length; j++) {\n var x = projectX(ring[j][0]);\n var y = projectY(ring[j][1]);\n\n out.push(x);\n out.push(y);\n out.push(0);\n\n if (j > 0) {\n if (isPolygon) {\n size += (x0 * y - x * y0) / 2; // area\n } else {\n size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2)); // length\n }\n }\n x0 = x;\n y0 = y;\n }\n\n var last = out.length - 3;\n out[2] = 1;\n simplify(out, 0, last, tolerance);\n out[last + 2] = 1;\n\n out.size = Math.abs(size);\n out.start = 0;\n out.end = out.size;\n}\n\nfunction convertLines(rings, out, tolerance, isPolygon) {\n for (var i = 0; i < rings.length; i++) {\n var geom = [];\n convertLine(rings[i], geom, tolerance, isPolygon);\n out.push(geom);\n }\n}\n\nfunction projectX(x) {\n return x / 360 + 0.5;\n}\n\nfunction projectY(y) {\n var sin = Math.sin(y * Math.PI / 180);\n var y2 = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;\n return y2 < 0 ? 0 : y2 > 1 ? 1 : y2;\n}\n","\nimport createFeature from './feature';\n\n/* clip features between two axis-parallel lines:\n * | |\n * ___|___ | /\n * / | \\____|____/\n * | |\n */\n\nexport default function clip(features, scale, k1, k2, axis, minAll, maxAll, options) {\n\n k1 /= scale;\n k2 /= scale;\n\n if (minAll >= k1 && maxAll < k2) return features; // trivial accept\n else if (maxAll < k1 || minAll >= k2) return null; // trivial reject\n\n var clipped = [];\n\n for (var i = 0; i < features.length; i++) {\n\n var feature = features[i];\n var geometry = feature.geometry;\n var type = feature.type;\n\n var min = axis === 0 ? feature.minX : feature.minY;\n var max = axis === 0 ? feature.maxX : feature.maxY;\n\n if (min >= k1 && max < k2) { // trivial accept\n clipped.push(feature);\n continue;\n } else if (max < k1 || min >= k2) { // trivial reject\n continue;\n }\n\n var newGeometry = [];\n\n if (type === 'Point' || type === 'MultiPoint') {\n clipPoints(geometry, newGeometry, k1, k2, axis);\n\n } else if (type === 'LineString') {\n clipLine(geometry, newGeometry, k1, k2, axis, false, options.lineMetrics);\n\n } else if (type === 'MultiLineString') {\n clipLines(geometry, newGeometry, k1, k2, axis, false);\n\n } else if (type === 'Polygon') {\n clipLines(geometry, newGeometry, k1, k2, axis, true);\n\n } else if (type === 'MultiPolygon') {\n for (var j = 0; j < geometry.length; j++) {\n var polygon = [];\n clipLines(geometry[j], polygon, k1, k2, axis, true);\n if (polygon.length) {\n newGeometry.push(polygon);\n }\n }\n }\n\n if (newGeometry.length) {\n if (options.lineMetrics && type === 'LineString') {\n for (j = 0; j < newGeometry.length; j++) {\n clipped.push(createFeature(feature.id, type, newGeometry[j], feature.tags));\n }\n continue;\n }\n\n if (type === 'LineString' || type === 'MultiLineString') {\n if (newGeometry.length === 1) {\n type = 'LineString';\n newGeometry = newGeometry[0];\n } else {\n type = 'MultiLineString';\n }\n }\n if (type === 'Point' || type === 'MultiPoint') {\n type = newGeometry.length === 3 ? 'Point' : 'MultiPoint';\n }\n\n clipped.push(createFeature(feature.id, type, newGeometry, feature.tags));\n }\n }\n\n return clipped.length ? clipped : null;\n}\n\nfunction clipPoints(geom, newGeom, k1, k2, axis) {\n for (var i = 0; i < geom.length; i += 3) {\n var a = geom[i + axis];\n\n if (a >= k1 && a <= k2) {\n newGeom.push(geom[i]);\n newGeom.push(geom[i + 1]);\n newGeom.push(geom[i + 2]);\n }\n }\n}\n\nfunction clipLine(geom, newGeom, k1, k2, axis, isPolygon, trackMetrics) {\n\n var slice = newSlice(geom);\n var intersect = axis === 0 ? intersectX : intersectY;\n var len = geom.start;\n var segLen, t;\n\n for (var i = 0; i < geom.length - 3; i += 3) {\n var ax = geom[i];\n var ay = geom[i + 1];\n var az = geom[i + 2];\n var bx = geom[i + 3];\n var by = geom[i + 4];\n var a = axis === 0 ? ax : ay;\n var b = axis === 0 ? bx : by;\n var exited = false;\n\n if (trackMetrics) segLen = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2));\n\n if (a < k1) {\n // ---|--> | (line enters the clip region from the left)\n if (b > k1) {\n t = intersect(slice, ax, ay, bx, by, k1);\n if (trackMetrics) slice.start = len + segLen * t;\n }\n } else if (a > k2) {\n // | <--|--- (line enters the clip region from the right)\n if (b < k2) {\n t = intersect(slice, ax, ay, bx, by, k2);\n if (trackMetrics) slice.start = len + segLen * t;\n }\n } else {\n addPoint(slice, ax, ay, az);\n }\n if (b < k1 && a >= k1) {\n // <--|--- | or <--|-----|--- (line exits the clip region on the left)\n t = intersect(slice, ax, ay, bx, by, k1);\n exited = true;\n }\n if (b > k2 && a <= k2) {\n // | ---|--> or ---|-----|--> (line exits the clip region on the right)\n t = intersect(slice, ax, ay, bx, by, k2);\n exited = true;\n }\n\n if (!isPolygon && exited) {\n if (trackMetrics) slice.end = len + segLen * t;\n newGeom.push(slice);\n slice = newSlice(geom);\n }\n\n if (trackMetrics) len += segLen;\n }\n\n // add the last point\n var last = geom.length - 3;\n ax = geom[last];\n ay = geom[last + 1];\n az = geom[last + 2];\n a = axis === 0 ? ax : ay;\n if (a >= k1 && a <= k2) addPoint(slice, ax, ay, az);\n\n // close the polygon if its endpoints are not the same after clipping\n last = slice.length - 3;\n if (isPolygon && last >= 3 && (slice[last] !== slice[0] || slice[last + 1] !== slice[1])) {\n addPoint(slice, slice[0], slice[1], slice[2]);\n }\n\n // add the final slice\n if (slice.length) {\n newGeom.push(slice);\n }\n}\n\nfunction newSlice(line) {\n var slice = [];\n slice.size = line.size;\n slice.start = line.start;\n slice.end = line.end;\n return slice;\n}\n\nfunction clipLines(geom, newGeom, k1, k2, axis, isPolygon) {\n for (var i = 0; i < geom.length; i++) {\n clipLine(geom[i], newGeom, k1, k2, axis, isPolygon, false);\n }\n}\n\nfunction addPoint(out, x, y, z) {\n out.push(x);\n out.push(y);\n out.push(z);\n}\n\nfunction intersectX(out, ax, ay, bx, by, x) {\n var t = (x - ax) / (bx - ax);\n out.push(x);\n out.push(ay + (by - ay) * t);\n out.push(1);\n return t;\n}\n\nfunction intersectY(out, ax, ay, bx, by, y) {\n var t = (y - ay) / (by - ay);\n out.push(ax + (bx - ax) * t);\n out.push(y);\n out.push(1);\n return t;\n}\n","\nimport clip from './clip';\nimport createFeature from './feature';\n\nexport default function wrap(features, options) {\n var buffer = options.buffer / options.extent;\n var merged = features;\n var left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2, options); // left world copy\n var right = clip(features, 1, 1 - buffer, 2 + buffer, 0, -1, 2, options); // right world copy\n\n if (left || right) {\n merged = clip(features, 1, -buffer, 1 + buffer, 0, -1, 2, options) || []; // center world copy\n\n if (left) merged = shiftFeatureCoords(left, 1).concat(merged); // merge left into center\n if (right) merged = merged.concat(shiftFeatureCoords(right, -1)); // merge right into center\n }\n\n return merged;\n}\n\nfunction shiftFeatureCoords(features, offset) {\n var newFeatures = [];\n\n for (var i = 0; i < features.length; i++) {\n var feature = features[i],\n type = feature.type;\n\n var newGeometry;\n\n if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') {\n newGeometry = shiftCoords(feature.geometry, offset);\n\n } else if (type === 'MultiLineString' || type === 'Polygon') {\n newGeometry = [];\n for (var j = 0; j < feature.geometry.length; j++) {\n newGeometry.push(shiftCoords(feature.geometry[j], offset));\n }\n } else if (type === 'MultiPolygon') {\n newGeometry = [];\n for (j = 0; j < feature.geometry.length; j++) {\n var newPolygon = [];\n for (var k = 0; k < feature.geometry[j].length; k++) {\n newPolygon.push(shiftCoords(feature.geometry[j][k], offset));\n }\n newGeometry.push(newPolygon);\n }\n }\n\n newFeatures.push(createFeature(feature.id, type, newGeometry, feature.tags));\n }\n\n return newFeatures;\n}\n\nfunction shiftCoords(points, offset) {\n var newPoints = [];\n newPoints.size = points.size;\n\n if (points.start !== undefined) {\n newPoints.start = points.start;\n newPoints.end = points.end;\n }\n\n for (var i = 0; i < points.length; i += 3) {\n newPoints.push(points[i] + offset, points[i + 1], points[i + 2]);\n }\n return newPoints;\n}\n","\n// Transforms the coordinates of each feature in the given tile from\n// mercator-projected space into (extent x extent) tile space.\nexport default function transformTile(tile, extent) {\n if (tile.transformed) return tile;\n\n var z2 = 1 << tile.z,\n tx = tile.x,\n ty = tile.y,\n i, j, k;\n\n for (i = 0; i < tile.features.length; i++) {\n var feature = tile.features[i],\n geom = feature.geometry,\n type = feature.type;\n\n feature.geometry = [];\n\n if (type === 1) {\n for (j = 0; j < geom.length; j += 2) {\n feature.geometry.push(transformPoint(geom[j], geom[j + 1], extent, z2, tx, ty));\n }\n } else {\n for (j = 0; j < geom.length; j++) {\n var ring = [];\n for (k = 0; k < geom[j].length; k += 2) {\n ring.push(transformPoint(geom[j][k], geom[j][k + 1], extent, z2, tx, ty));\n }\n feature.geometry.push(ring);\n }\n }\n }\n\n tile.transformed = true;\n\n return tile;\n}\n\nfunction transformPoint(x, y, extent, z2, tx, ty) {\n return [\n Math.round(extent * (x * z2 - tx)),\n Math.round(extent * (y * z2 - ty))];\n}\n","\nexport default function createTile(features, z, tx, ty, options) {\n var tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent);\n var tile = {\n features: [],\n numPoints: 0,\n numSimplified: 0,\n numFeatures: 0,\n source: null,\n x: tx,\n y: ty,\n z: z,\n transformed: false,\n minX: 2,\n minY: 1,\n maxX: -1,\n maxY: 0\n };\n for (var i = 0; i < features.length; i++) {\n tile.numFeatures++;\n addFeature(tile, features[i], tolerance, options);\n\n var minX = features[i].minX;\n var minY = features[i].minY;\n var maxX = features[i].maxX;\n var maxY = features[i].maxY;\n\n if (minX < tile.minX) tile.minX = minX;\n if (minY < tile.minY) tile.minY = minY;\n if (maxX > tile.maxX) tile.maxX = maxX;\n if (maxY > tile.maxY) tile.maxY = maxY;\n }\n return tile;\n}\n\nfunction addFeature(tile, feature, tolerance, options) {\n\n var geom = feature.geometry,\n type = feature.type,\n simplified = [];\n\n if (type === 'Point' || type === 'MultiPoint') {\n for (var i = 0; i < geom.length; i += 3) {\n simplified.push(geom[i]);\n simplified.push(geom[i + 1]);\n tile.numPoints++;\n tile.numSimplified++;\n }\n\n } else if (type === 'LineString') {\n addLine(simplified, geom, tile, tolerance, false, false);\n\n } else if (type === 'MultiLineString' || type === 'Polygon') {\n for (i = 0; i < geom.length; i++) {\n addLine(simplified, geom[i], tile, tolerance, type === 'Polygon', i === 0);\n }\n\n } else if (type === 'MultiPolygon') {\n\n for (var k = 0; k < geom.length; k++) {\n var polygon = geom[k];\n for (i = 0; i < polygon.length; i++) {\n addLine(simplified, polygon[i], tile, tolerance, true, i === 0);\n }\n }\n }\n\n if (simplified.length) {\n var tags = feature.tags || null;\n if (type === 'LineString' && options.lineMetrics) {\n tags = {};\n for (var key in feature.tags) tags[key] = feature.tags[key];\n tags['mapbox_clip_start'] = geom.start / geom.size;\n tags['mapbox_clip_end'] = geom.end / geom.size;\n }\n var tileFeature = {\n geometry: simplified,\n type: type === 'Polygon' || type === 'MultiPolygon' ? 3 :\n type === 'LineString' || type === 'MultiLineString' ? 2 : 1,\n tags: tags\n };\n if (feature.id !== null) {\n tileFeature.id = feature.id;\n }\n tile.features.push(tileFeature);\n }\n}\n\nfunction addLine(result, geom, tile, tolerance, isPolygon, isOuter) {\n var sqTolerance = tolerance * tolerance;\n\n if (tolerance > 0 && (geom.size < (isPolygon ? sqTolerance : tolerance))) {\n tile.numPoints += geom.length / 3;\n return;\n }\n\n var ring = [];\n\n for (var i = 0; i < geom.length; i += 3) {\n if (tolerance === 0 || geom[i + 2] > sqTolerance) {\n tile.numSimplified++;\n ring.push(geom[i]);\n ring.push(geom[i + 1]);\n }\n tile.numPoints++;\n }\n\n if (isPolygon) rewind(ring, isOuter);\n\n result.push(ring);\n}\n\nfunction rewind(ring, clockwise) {\n var area = 0;\n for (var i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) {\n area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]);\n }\n if (area > 0 === clockwise) {\n for (i = 0, len = ring.length; i < len / 2; i += 2) {\n var x = ring[i];\n var y = ring[i + 1];\n ring[i] = ring[len - 2 - i];\n ring[i + 1] = ring[len - 1 - i];\n ring[len - 2 - i] = x;\n ring[len - 1 - i] = y;\n }\n }\n}\n","\nimport convert from './convert'; // GeoJSON conversion and preprocessing\nimport clip from './clip'; // stripe clipping algorithm\nimport wrap from './wrap'; // date line processing\nimport transform from './transform'; // coordinate transformation\nimport createTile from './tile'; // final simplified tile generation\n\nexport default function geojsonvt(data, options) {\n return new GeoJSONVT(data, options);\n}\n\nfunction GeoJSONVT(data, options) {\n options = this.options = extend(Object.create(this.options), options);\n\n var debug = options.debug;\n\n if (debug) console.time('preprocess data');\n\n if (options.maxZoom < 0 || options.maxZoom > 24) throw new Error('maxZoom should be in the 0-24 range');\n if (options.promoteId && options.generateId) throw new Error('promoteId and generateId cannot be used together.');\n\n var features = convert(data, options);\n\n this.tiles = {};\n this.tileCoords = [];\n\n if (debug) {\n console.timeEnd('preprocess data');\n console.log('index: maxZoom: %d, maxPoints: %d', options.indexMaxZoom, options.indexMaxPoints);\n console.time('generate tiles');\n this.stats = {};\n this.total = 0;\n }\n\n features = wrap(features, options);\n\n // start slicing from the top tile down\n if (features.length) this.splitTile(features, 0, 0, 0);\n\n if (debug) {\n if (features.length) console.log('features: %d, points: %d', this.tiles[0].numFeatures, this.tiles[0].numPoints);\n console.timeEnd('generate tiles');\n console.log('tiles generated:', this.total, JSON.stringify(this.stats));\n }\n}\n\nGeoJSONVT.prototype.options = {\n maxZoom: 14, // max zoom to preserve detail on\n indexMaxZoom: 5, // max zoom in the tile index\n indexMaxPoints: 100000, // max number of points per tile in the tile index\n tolerance: 3, // simplification tolerance (higher means simpler)\n extent: 4096, // tile extent\n buffer: 64, // tile buffer on each side\n lineMetrics: false, // whether to calculate line metrics\n promoteId: null, // name of a feature property to be promoted to feature.id\n generateId: false, // whether to generate feature ids. Cannot be used with promoteId\n debug: 0 // logging level (0, 1 or 2)\n};\n\nGeoJSONVT.prototype.splitTile = function (features, z, x, y, cz, cx, cy) {\n\n var stack = [features, z, x, y],\n options = this.options,\n debug = options.debug;\n\n // avoid recursion by using a processing queue\n while (stack.length) {\n y = stack.pop();\n x = stack.pop();\n z = stack.pop();\n features = stack.pop();\n\n var z2 = 1 << z,\n id = toID(z, x, y),\n tile = this.tiles[id];\n\n if (!tile) {\n if (debug > 1) console.time('creation');\n\n tile = this.tiles[id] = createTile(features, z, x, y, options);\n this.tileCoords.push({z: z, x: x, y: y});\n\n if (debug) {\n if (debug > 1) {\n console.log('tile z%d-%d-%d (features: %d, points: %d, simplified: %d)',\n z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified);\n console.timeEnd('creation');\n }\n var key = 'z' + z;\n this.stats[key] = (this.stats[key] || 0) + 1;\n this.total++;\n }\n }\n\n // save reference to original geometry in tile so that we can drill down later if we stop now\n tile.source = features;\n\n // if it's the first-pass tiling\n if (!cz) {\n // stop tiling if we reached max zoom, or if the tile is too simple\n if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints) continue;\n\n // if a drilldown to a specific tile\n } else {\n // stop tiling if we reached base zoom or our target tile zoom\n if (z === options.maxZoom || z === cz) continue;\n\n // stop tiling if it's not an ancestor of the target tile\n var m = 1 << (cz - z);\n if (x !== Math.floor(cx / m) || y !== Math.floor(cy / m)) continue;\n }\n\n // if we slice further down, no need to keep source geometry\n tile.source = null;\n\n if (features.length === 0) continue;\n\n if (debug > 1) console.time('clipping');\n\n // values we'll use for clipping\n var k1 = 0.5 * options.buffer / options.extent,\n k2 = 0.5 - k1,\n k3 = 0.5 + k1,\n k4 = 1 + k1,\n tl, bl, tr, br, left, right;\n\n tl = bl = tr = br = null;\n\n left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX, options);\n right = clip(features, z2, x + k2, x + k4, 0, tile.minX, tile.maxX, options);\n features = null;\n\n if (left) {\n tl = clip(left, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);\n bl = clip(left, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);\n left = null;\n }\n\n if (right) {\n tr = clip(right, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);\n br = clip(right, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);\n right = null;\n }\n\n if (debug > 1) console.timeEnd('clipping');\n\n stack.push(tl || [], z + 1, x * 2, y * 2);\n stack.push(bl || [], z + 1, x * 2, y * 2 + 1);\n stack.push(tr || [], z + 1, x * 2 + 1, y * 2);\n stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1);\n }\n};\n\nGeoJSONVT.prototype.getTile = function (z, x, y) {\n var options = this.options,\n extent = options.extent,\n debug = options.debug;\n\n if (z < 0 || z > 24) return null;\n\n var z2 = 1 << z;\n x = ((x % z2) + z2) % z2; // wrap tile x coordinate\n\n var id = toID(z, x, y);\n if (this.tiles[id]) return transform(this.tiles[id], extent);\n\n if (debug > 1) console.log('drilling down to z%d-%d-%d', z, x, y);\n\n var z0 = z,\n x0 = x,\n y0 = y,\n parent;\n\n while (!parent && z0 > 0) {\n z0--;\n x0 = Math.floor(x0 / 2);\n y0 = Math.floor(y0 / 2);\n parent = this.tiles[toID(z0, x0, y0)];\n }\n\n if (!parent || !parent.source) return null;\n\n // if we found a parent tile containing the original geometry, we can drill down from it\n if (debug > 1) console.log('found parent tile z%d-%d-%d', z0, x0, y0);\n\n if (debug > 1) console.time('drilling down');\n this.splitTile(parent.source, z0, x0, y0, z, x, y);\n if (debug > 1) console.timeEnd('drilling down');\n\n return this.tiles[id] ? transform(this.tiles[id], extent) : null;\n};\n\nfunction toID(z, x, y) {\n return (((1 << z) * y + x) * 32) + z;\n}\n\nfunction extend(dest, src) {\n for (var i in src) dest[i] = src[i];\n return dest;\n}\n","// @flow\n\nimport {getJSON} from '../util/ajax.js';\n\nimport {getPerformanceMeasurement} from '../util/performance.js';\nimport rewind from '@mapbox/geojson-rewind';\nimport GeoJSONWrapper from './geojson_wrapper.js';\nimport vtpbf from 'vt-pbf';\nimport Supercluster from 'supercluster';\nimport geojsonvt from 'geojson-vt';\nimport assert from 'assert';\nimport VectorTileWorkerSource from './vector_tile_worker_source.js';\nimport {createExpression} from '../style-spec/expression/index.js';\n\nimport type {\n RequestedTileParameters,\n WorkerTileParameters,\n WorkerTileCallback,\n} from '../source/worker_source.js';\n\nimport type Actor from '../util/actor.js';\nimport type StyleLayerIndex from '../style/style_layer_index.js';\n\nimport type {LoadVectorDataCallback} from './vector_tile_worker_source.js';\nimport type {RequestParameters, ResponseCallback} from '../util/ajax.js';\nimport type {Callback} from '../types/callback.js';\nimport type {GeoJSONFeature} from '@mapbox/geojson-types';\n\nexport type GeoJSONWorkerOptions = {\n source: string,\n cluster: boolean,\n superclusterOptions?: Object,\n geojsonVtOptions?: Object,\n clusterProperties?: Object,\n filter?: Array<mixed>\n};\n\nexport type LoadGeoJSONParameters = GeoJSONWorkerOptions & {\n request?: RequestParameters,\n data?: string\n};\n\nexport type LoadGeoJSON = (params: LoadGeoJSONParameters, callback: ResponseCallback<Object>) => void;\n\nexport interface GeoJSONIndex {\n getTile(z: number, x: number, y: number): Object;\n\n // supercluster methods\n getClusterExpansionZoom(clusterId: number): number;\n getChildren(clusterId: number): Array<GeoJSONFeature>;\n getLeaves(clusterId: number, limit: number, offset: number): Array<GeoJSONFeature>;\n}\n\n// $FlowFixMe[missing-this-annot]\nfunction loadGeoJSONTile(params: RequestedTileParameters, callback: LoadVectorDataCallback) {\n const canonical = params.tileID.canonical;\n\n if (!this._geoJSONIndex) {\n return callback(null, null); // we couldn't load the file\n }\n\n const geoJSONTile = this._geoJSONIndex.getTile(canonical.z, canonical.x, canonical.y);\n if (!geoJSONTile) {\n return callback(null, null); // nothing in the given tile\n }\n\n const geojsonWrapper = new GeoJSONWrapper(geoJSONTile.features);\n\n // Encode the geojson-vt tile into binary vector tile form. This\n // is a convenience that allows `FeatureIndex` to operate the same way\n // across `VectorTileSource` and `GeoJSONSource` data.\n let pbf = vtpbf(geojsonWrapper);\n if (pbf.byteOffset !== 0 || pbf.byteLength !== pbf.buffer.byteLength) {\n // Compatibility with node Buffer (https://github.com/mapbox/pbf/issues/35)\n pbf = new Uint8Array(pbf);\n }\n\n callback(null, {\n vectorTile: geojsonWrapper,\n rawData: pbf.buffer\n });\n}\n\n/**\n * The {@link WorkerSource} implementation that supports {@link GeoJSONSource}.\n * This class is designed to be easily reused to support custom source types\n * for data formats that can be parsed/converted into an in-memory GeoJSON\n * representation. To do so, create it with\n * `new GeoJSONWorkerSource(actor, layerIndex, customLoadGeoJSONFunction)`.\n * For a full example, see [mapbox-gl-topojson](https://github.com/developmentseed/mapbox-gl-topojson).\n *\n * @private\n */\nclass GeoJSONWorkerSource extends VectorTileWorkerSource {\n loadGeoJSON: LoadGeoJSON;\n _geoJSONIndex: GeoJSONIndex\n\n /**\n * @param [loadGeoJSON] Optional method for custom loading/parsing of\n * GeoJSON based on parameters passed from the main-thread Source.\n * See {@link GeoJSONWorkerSource#loadGeoJSON}.\n * @private\n */\n constructor(actor: Actor, layerIndex: StyleLayerIndex, availableImages: Array<string>, isSpriteLoaded: boolean, loadGeoJSON: ?LoadGeoJSON) {\n super(actor, layerIndex, availableImages, isSpriteLoaded, loadGeoJSONTile);\n if (loadGeoJSON) {\n this.loadGeoJSON = loadGeoJSON;\n }\n }\n\n /**\n * Fetches (if appropriate), parses, and index geojson data into tiles. This\n * preparatory method must be called before {@link GeoJSONWorkerSource#loadTile}\n * can correctly serve up tiles.\n *\n * Defers to {@link GeoJSONWorkerSource#loadGeoJSON} for the fetching/parsing,\n * expecting `callback(error, data)` to be called with either an error or a\n * parsed GeoJSON object.\n *\n * When `loadData` requests come in faster than they can be processed,\n * they are coalesced into a single request using the latest data.\n * See {@link GeoJSONWorkerSource#coalesce}\n *\n * @param params\n * @param callback\n * @private\n */\n loadData(params: LoadGeoJSONParameters, callback: Callback<{resourceTiming?: {[_: string]: Array<PerformanceResourceTiming>}}>) {\n const requestParam = params && params.request;\n const perf = requestParam && requestParam.collectResourceTiming;\n\n this.loadGeoJSON(params, (err: ?Error, data: ?Object) => {\n if (err || !data) {\n return callback(err);\n } else if (typeof data !== 'object') {\n return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`));\n } else {\n rewind(data, true);\n\n try {\n if (params.filter) {\n const compiled = createExpression(params.filter, {type: 'boolean', 'property-type': 'data-driven', overridable: false, transition: false});\n if (compiled.result === 'error')\n throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', '));\n\n const features = data.features.filter(feature => compiled.value.evaluate({zoom: 0}, feature));\n data = {type: 'FeatureCollection', features};\n }\n\n this._geoJSONIndex = params.cluster ?\n new Supercluster(getSuperclusterOptions(params)).load(data.features) :\n geojsonvt(data, params.geojsonVtOptions);\n } catch (err) {\n return callback(err);\n }\n\n this.loaded = {};\n\n const result = {};\n if (perf) {\n const resourceTimingData = getPerformanceMeasurement(requestParam);\n // it's necessary to eval the result of getEntriesByName() here via parse/stringify\n // late evaluation in the main thread causes TypeError: illegal invocation\n if (resourceTimingData) {\n result.resourceTiming = {};\n result.resourceTiming[params.source] = JSON.parse(JSON.stringify(resourceTimingData));\n }\n }\n callback(null, result);\n }\n });\n }\n\n /**\n * Implements {@link WorkerSource#reloadTile}.\n *\n * If the tile is loaded, uses the implementation in VectorTileWorkerSource.\n * Otherwise, such as after a setData() call, we load the tile fresh.\n *\n * @param params\n * @param params.uid The UID for this tile.\n * @private\n */\n reloadTile(params: WorkerTileParameters, callback: WorkerTileCallback): void {\n const loaded = this.loaded,\n uid = params.uid;\n\n if (loaded && loaded[uid]) {\n return super.reloadTile(params, callback);\n } else {\n return this.loadTile(params, callback);\n }\n }\n\n /**\n * Fetch and parse GeoJSON according to the given params. Calls `callback`\n * with `(err, data)`, where `data` is a parsed GeoJSON object.\n *\n * GeoJSON is loaded and parsed from `params.url` if it exists, or else\n * expected as a literal (string or object) `params.data`.\n *\n * @param params\n * @param [params.url] A URL to the remote GeoJSON data.\n * @param [params.data] Literal GeoJSON data. Must be provided if `params.url` is not.\n * @private\n */\n // $FlowFixMe[duplicate-class-member]\n loadGeoJSON(params: LoadGeoJSONParameters, callback: ResponseCallback<Object>): void {\n // Because of same origin issues, urls must either include an explicit\n // origin or absolute path.\n // ie: /foo/bar.json or http://example.com/bar.json\n // but not ../foo/bar.json\n if (params.request) {\n getJSON(params.request, callback);\n } else if (typeof params.data === 'string') {\n try {\n return callback(null, JSON.parse(params.data));\n } catch (e) {\n return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`));\n }\n } else {\n return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`));\n }\n }\n\n getClusterExpansionZoom(params: {clusterId: number}, callback: Callback<number>) {\n try {\n callback(null, this._geoJSONIndex.getClusterExpansionZoom(params.clusterId));\n } catch (e) {\n callback(e);\n }\n }\n\n getClusterChildren(params: {clusterId: number}, callback: Callback<Array<GeoJSONFeature>>) {\n try {\n callback(null, this._geoJSONIndex.getChildren(params.clusterId));\n } catch (e) {\n callback(e);\n }\n }\n\n getClusterLeaves(params: {clusterId: number, limit: number, offset: number}, callback: Callback<Array<GeoJSONFeature>>) {\n try {\n callback(null, this._geoJSONIndex.getLeaves(params.clusterId, params.limit, params.offset));\n } catch (e) {\n callback(e);\n }\n }\n}\n\nfunction getSuperclusterOptions({superclusterOptions, clusterProperties}: LoadGeoJSONParameters) {\n if (!clusterProperties || !superclusterOptions) return superclusterOptions;\n\n const mapExpressions = {};\n const reduceExpressions = {};\n const globals = {accumulated: null, zoom: 0};\n const feature = {properties: null};\n const propertyNames = Object.keys(clusterProperties);\n\n for (const key of propertyNames) {\n const [operator, mapExpression] = clusterProperties[key];\n\n const mapExpressionParsed = createExpression(mapExpression);\n const reduceExpressionParsed = createExpression(\n typeof operator === 'string' ? [operator, ['accumulated'], ['get', key]] : operator);\n\n assert(mapExpressionParsed.result === 'success');\n assert(reduceExpressionParsed.result === 'success');\n\n mapExpressions[key] = mapExpressionParsed.value;\n reduceExpressions[key] = reduceExpressionParsed.value;\n }\n\n superclusterOptions.map = (pointProperties) => {\n feature.properties = pointProperties;\n const properties = {};\n for (const key of propertyNames) {\n properties[key] = mapExpressions[key].evaluate(globals, feature);\n }\n return properties;\n };\n superclusterOptions.reduce = (accumulated, clusterProperties) => {\n feature.properties = clusterProperties;\n for (const key of propertyNames) {\n globals.accumulated = accumulated[key];\n accumulated[key] = reduceExpressions[key].evaluate(globals, feature);\n }\n };\n\n return superclusterOptions;\n}\n\nexport default GeoJSONWorkerSource;\n","// @flow\n\nimport Actor from '../util/actor.js';\n\nimport StyleLayerIndex from '../style/style_layer_index.js';\nimport VectorTileWorkerSource from './vector_tile_worker_source.js';\nimport RasterDEMTileWorkerSource from './raster_dem_tile_worker_source.js';\nimport GeoJSONWorkerSource from './geojson_worker_source.js';\nimport assert from 'assert';\nimport {plugin as globalRTLTextPlugin} from './rtl_text_plugin.js';\nimport {enforceCacheSizeLimit} from '../util/tile_request_cache.js';\nimport {extend} from '../util/util.js';\nimport {PerformanceUtils} from '../util/performance.js';\nimport {Event} from '../util/evented.js';\nimport {getProjection} from '../geo/projection/index.js';\n\nimport type {\n WorkerSource,\n WorkerTileParameters,\n WorkerDEMTileParameters,\n WorkerTileCallback,\n WorkerDEMTileCallback,\n TileParameters\n} from '../source/worker_source.js';\n\nimport type {WorkerGlobalScopeInterface} from '../util/web_worker.js';\nimport type {Callback} from '../types/callback.js';\nimport type {LayerSpecification, ProjectionSpecification} from '../style-spec/types.js';\nimport type {PluginState} from './rtl_text_plugin.js';\nimport type Projection from '../geo/projection/projection.js';\n\n/**\n * @private\n */\nexport default class Worker {\n self: WorkerGlobalScopeInterface;\n actor: Actor;\n layerIndexes: {[_: string]: StyleLayerIndex };\n availableImages: {[_: string]: Array<string> };\n workerSourceTypes: {[_: string]: Class<WorkerSource> };\n workerSources: {[_: string]: {[_: string]: {[_: string]: WorkerSource } } };\n demWorkerSources: {[_: string]: {[_: string]: RasterDEMTileWorkerSource } };\n projections: {[_: string]: Projection };\n defaultProjection: Projection;\n isSpriteLoaded: {[_: string]: boolean };\n referrer: ?string;\n terrain: ?boolean;\n\n constructor(self: WorkerGlobalScopeInterface) {\n PerformanceUtils.measure('workerEvaluateScript');\n this.self = self;\n this.actor = new Actor(self, this);\n\n this.layerIndexes = {};\n this.availableImages = {};\n this.isSpriteLoaded = {};\n\n this.projections = {};\n this.defaultProjection = getProjection({name: 'mercator'});\n\n this.workerSourceTypes = {\n vector: VectorTileWorkerSource,\n geojson: GeoJSONWorkerSource\n };\n\n // [mapId][sourceType][sourceName] => worker source instance\n this.workerSources = {};\n this.demWorkerSources = {};\n\n this.self.registerWorkerSource = (name: string, WorkerSource: Class<WorkerSource>) => {\n if (this.workerSourceTypes[name]) {\n throw new Error(`Worker source with name \"${name}\" already registered.`);\n }\n this.workerSourceTypes[name] = WorkerSource;\n };\n\n // This is invoked by the RTL text plugin when the download via the `importScripts` call has finished, and the code has been parsed.\n this.self.registerRTLTextPlugin = (rtlTextPlugin: {applyArabicShaping: Function, processBidirectionalText: Function, processStyledBidirectionalText?: Function}) => {\n if (globalRTLTextPlugin.isParsed()) {\n throw new Error('RTL text plugin already registered.');\n }\n globalRTLTextPlugin['applyArabicShaping'] = rtlTextPlugin.applyArabicShaping;\n globalRTLTextPlugin['processBidirectionalText'] = rtlTextPlugin.processBidirectionalText;\n globalRTLTextPlugin['processStyledBidirectionalText'] = rtlTextPlugin.processStyledBidirectionalText;\n };\n }\n\n clearCaches(mapId: string, unused: mixed, callback: WorkerTileCallback) {\n delete this.layerIndexes[mapId];\n delete this.availableImages[mapId];\n delete this.workerSources[mapId];\n delete this.demWorkerSources[mapId];\n callback();\n }\n\n checkIfReady(mapID: string, unused: mixed, callback: WorkerTileCallback) {\n // noop, used to check if a worker is fully set up and ready to receive messages\n callback();\n }\n\n setReferrer(mapID: string, referrer: string) {\n this.referrer = referrer;\n }\n\n spriteLoaded(mapId: string, bool: boolean) {\n this.isSpriteLoaded[mapId] = bool;\n for (const workerSource in this.workerSources[mapId]) {\n const ws = this.workerSources[mapId][workerSource];\n for (const source in ws) {\n if (ws[source] instanceof VectorTileWorkerSource) {\n ws[source].isSpriteLoaded = bool;\n ws[source].fire(new Event('isSpriteLoaded'));\n }\n }\n }\n }\n\n setImages(mapId: string, images: Array<string>, callback: WorkerTileCallback) {\n this.availableImages[mapId] = images;\n for (const workerSource in this.workerSources[mapId]) {\n const ws = this.workerSources[mapId][workerSource];\n for (const source in ws) {\n ws[source].availableImages = images;\n }\n }\n callback();\n }\n\n enableTerrain(mapId: string, enable: boolean, callback: WorkerTileCallback) {\n this.terrain = enable;\n callback();\n }\n\n setProjection(mapId: string, config: ProjectionSpecification) {\n this.projections[mapId] = getProjection(config);\n }\n\n setLayers(mapId: string, layers: Array<LayerSpecification>, callback: WorkerTileCallback) {\n this.getLayerIndex(mapId).replace(layers);\n callback();\n }\n\n updateLayers(mapId: string, params: {layers: Array<LayerSpecification>, removedIds: Array<string>}, callback: WorkerTileCallback) {\n this.getLayerIndex(mapId).update(params.layers, params.removedIds);\n callback();\n }\n\n loadTile(mapId: string, params: WorkerTileParameters & {type: string}, callback: WorkerTileCallback) {\n assert(params.type);\n // $FlowFixMe[method-unbinding]\n const p = this.enableTerrain ? extend({enableTerrain: this.terrain}, params) : params;\n p.projection = this.projections[mapId] || this.defaultProjection;\n this.getWorkerSource(mapId, params.type, params.source).loadTile(p, callback);\n }\n\n loadDEMTile(mapId: string, params: WorkerDEMTileParameters, callback: WorkerDEMTileCallback) {\n // $FlowFixMe[method-unbinding]\n const p = this.enableTerrain ? extend({buildQuadTree: this.terrain}, params) : params;\n this.getDEMWorkerSource(mapId, params.source).loadTile(p, callback);\n }\n\n reloadTile(mapId: string, params: WorkerTileParameters & {type: string}, callback: WorkerTileCallback) {\n assert(params.type);\n // $FlowFixMe[method-unbinding]\n const p = this.enableTerrain ? extend({enableTerrain: this.terrain}, params) : params;\n p.projection = this.projections[mapId] || this.defaultProjection;\n this.getWorkerSource(mapId, params.type, params.source).reloadTile(p, callback);\n }\n\n abortTile(mapId: string, params: TileParameters & {type: string}, callback: WorkerTileCallback) {\n assert(params.type);\n this.getWorkerSource(mapId, params.type, params.source).abortTile(params, callback);\n }\n\n removeTile(mapId: string, params: TileParameters & {type: string}, callback: WorkerTileCallback) {\n assert(params.type);\n this.getWorkerSource(mapId, params.type, params.source).removeTile(params, callback);\n }\n\n removeSource(mapId: string, params: {source: string} & {type: string}, callback: WorkerTileCallback) {\n assert(params.type);\n assert(params.source);\n\n if (!this.workerSources[mapId] ||\n !this.workerSources[mapId][params.type] ||\n !this.workerSources[mapId][params.type][params.source]) {\n return;\n }\n\n const worker = this.workerSources[mapId][params.type][params.source];\n delete this.workerSources[mapId][params.type][params.source];\n\n if (worker.removeSource !== undefined) {\n worker.removeSource(params, callback);\n } else {\n callback();\n }\n }\n\n /**\n * Load a {@link WorkerSource} script at params.url. The script is run\n * (using importScripts) with `registerWorkerSource` in scope, which is a\n * function taking `(name, workerSourceObject)`.\n * @private\n */\n loadWorkerSource(map: string, params: { url: string }, callback: Callback<void>) {\n try {\n this.self.importScripts(params.url);\n callback();\n } catch (e) {\n callback(e.toString());\n }\n }\n\n syncRTLPluginState(map: string, state: PluginState, callback: Callback<boolean>) {\n try {\n globalRTLTextPlugin.setState(state);\n const pluginURL = globalRTLTextPlugin.getPluginURL();\n if (\n globalRTLTextPlugin.isLoaded() &&\n !globalRTLTextPlugin.isParsed() &&\n pluginURL != null // Not possible when `isLoaded` is true, but keeps flow happy\n ) {\n this.self.importScripts(pluginURL);\n const complete = globalRTLTextPlugin.isParsed();\n const error = complete ? undefined : new Error(`RTL Text Plugin failed to import scripts from ${pluginURL}`);\n callback(error, complete);\n }\n } catch (e) {\n callback(e.toString());\n }\n }\n\n getAvailableImages(mapId: string): Array<string> {\n let availableImages = this.availableImages[mapId];\n\n if (!availableImages) {\n availableImages = [];\n }\n\n return availableImages;\n }\n\n getLayerIndex(mapId: string): StyleLayerIndex {\n let layerIndexes = this.layerIndexes[mapId];\n if (!layerIndexes) {\n layerIndexes = this.layerIndexes[mapId] = new StyleLayerIndex();\n }\n return layerIndexes;\n }\n\n getWorkerSource(mapId: string, type: string, source: string): WorkerSource {\n if (!this.workerSources[mapId])\n this.workerSources[mapId] = {};\n if (!this.workerSources[mapId][type])\n this.workerSources[mapId][type] = {};\n\n if (!this.workerSources[mapId][type][source]) {\n // use a wrapped actor so that we can attach a target mapId param\n // to any messages invoked by the WorkerSource\n const actor = {\n send: (type: string, data: mixed, callback: any, _: any, mustQueue: boolean, metadata: any) => {\n this.actor.send(type, data, callback, mapId, mustQueue, metadata);\n },\n scheduler: this.actor.scheduler\n };\n this.workerSources[mapId][type][source] = new (this.workerSourceTypes[type]: any)((actor: any), this.getLayerIndex(mapId), this.getAvailableImages(mapId), this.isSpriteLoaded[mapId]);\n }\n\n return this.workerSources[mapId][type][source];\n }\n\n getDEMWorkerSource(mapId: string, source: string): RasterDEMTileWorkerSource {\n if (!this.demWorkerSources[mapId])\n this.demWorkerSources[mapId] = {};\n\n if (!this.demWorkerSources[mapId][source]) {\n this.demWorkerSources[mapId][source] = new RasterDEMTileWorkerSource();\n }\n\n return this.demWorkerSources[mapId][source];\n }\n\n enforceCacheSizeLimit(mapId: string, limit: number) {\n enforceCacheSizeLimit(limit);\n }\n\n getWorkerPerformanceMetrics(mapId: string, params: any, callback: (error: ?Error, result: ?Object) => void) {\n callback(undefined, PerformanceUtils.getWorkerPerformanceMetrics());\n }\n}\n\n/* global self, WorkerGlobalScope */\nif (typeof WorkerGlobalScope !== 'undefined' &&\n typeof self !== 'undefined' &&\n self instanceof WorkerGlobalScope) {\n // $FlowFixMe[prop-missing]\n self.worker = new Worker(self);\n}\n"],"names":["module","UnitBezier","p1x","p1y","p2x","p2y","this","cx","bx","ax","cy","by","ay","prototype","sampleCurveX","t","sampleCurveY","sampleCurveDerivativeX","solveCurveX","x","epsilon","undefined","i","x2","Math","abs","d2","t0","t1","solve","Point","y","clone","add","p","_add","sub","_sub","multByPoint","_multByPoint","divByPoint","_divByPoint","mult","k","_mult","div","_div","rotate","a","_rotate","rotateAround","_rotateAround","matMult","m","_matMult","unit","_unit","perp","_perp","round","_round","mag","sqrt","equals","other","dist","distSqr","dx","dy","angle","atan2","angleTo","b","angleWith","angleWithSep","cos","sin","convert","Array","isArray","window","self","DEG_TO_RAD","PI","RAD_TO_DEG","degToRad","radToDeg","clamp","n","min","max","wrap","d","w","values","obj","result","push","extend","dest","src","sources","id","uuid","random","toString","replace","validateUuid","str","test","bindAll","fns","context","forEach","fn","bind","endsWith","string","suffix","indexOf","length","mapObject","input","iterator","output","key","call","map","warnOnceHistory","warnOnce","message","console","warn","isCounterClockwise","c","calculateSignedArea","ring","sum","p1","p2","len","j","isWorker","WorkerGlobalScope","parseCacheControl","cacheControl","re","header","$0","$1","$2","$3","value","toLowerCase","maxAge","parseInt","isNaN","_isSafari","isSafari","scope","userAgent","navigator","safari","match","storageAvailable","type","storage","setItem","removeItem","e","getColumn","matrix","col","GridIndex","NUM_PARAMS","extent","padding","cells","ArrayBuffer","arrayBuffer","array","Int32Array","start","end","subarray","bboxesOffset","keys","bboxes","insert","_insertReadonly","scale","uid","x1","y1","y2","_forEachCell","_insertCell","cellIndex","query","intersectionTest","slice","_queryCell","seenUids","cell","u","offset","arg1","arg2","cx1","_convertToCellCoord","cy1","cx2","cy2","_convertFromCellCoord","floor","toArrayBuffer","metadataLength","totalCellLength","set","buffer","kCSSColorTable","transparent","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen","clamp_css_byte","parse_css_int","parseFloat","parse_css_float","f","css_hue_to_rgb","m1","m2","h","exports","css_str","iv","substr","op","ep","fname","params","split","alpha","pop","s","l","Color","constructor","r","g","parse","rgba","parseCSSColor","toArray","toArray01","toArray01PremultipliedAlpha","Color$1","extend$1","inputs","ParsingError","Error","super","ParsingError$1","Scope","parent","bindings","name","expression","concat","get","has","Scope$1","NullType","kind","NumberType","StringType","BooleanType","ColorType","ObjectType","ValueType","CollatorType","FormattedType","ResolvedImageType","itemType","N","valueMemberTypes","checkSubtype","expected","memberType","isValidType","provided","allowedTypes","some","isValidNativeType","Collator","caseSensitive","diacriticSensitive","locale","sensitivity","collator","Intl","usage","compare","lhs","rhs","resolvedLocale","resolvedOptions","FormattedSection","text","image","fontStack","textColor","normalize","Formatted","sections","static","unformatted","isEmpty","section","fromString","join","serialize","serialized","options","ResolvedImage","available","validateRGBA","isValue","mixed","item","typeOf","String","JSON","stringify","Literal","args","error","expectedType","evaluate","eachChild","outputDefined","Literal$1","RuntimeError$1","RuntimeError","toJSON","types","number","boolean","object","Assertion","parsed","ctx","every","arg","Assertion$1","FormatExpression","firstArg","nextTokenMayBeObject","font","lastExpression","content","evaluatedContent","ImageExpression","evaluatedImageName","availableImages","Coercion","Boolean","parseColor","num","Number","valueToString","child","Coercion$1","geometryTypes","EvaluationContext$1","EvaluationContext","globals","feature","featureState","formattedSection","_parseColorCache","canonical","featureTileCoord","featureDistanceData","geometryType","geometry","canonicalID","properties","distanceFromCenter","center","bearing","cached","CompoundExpression","_evaluate","definition","definitions","availableOverloads","overloads","filter","signature","signatureContext","ParsingContext","registry","path","parsedArgs","argParseFailed","errors","signatures","stringifySignature","actualTypes","CompoundExpression$1","CollatorExpression","EXTENT","updateBBox","bbox","coord","boxWithinBox","bbox1","bbox2","getTileCoordinates","lng","log","tilesAtZoom","pow","z","onBoundary","pointWithinPolygon","point","rings","inside","len2","pointWithinPolygons","polygons","twoSided","q1","q2","x3","y3","det1","det2","lineIntersectPolygon","polygon","v1","v2","lineStringWithinPolygon","line","lineStringWithinPolygons","getTilePolygon","coordinates","getTilePolygons","updatePoint","polyBBox","worldSize","halfWorldSize","shift","getTilePoints","pointBBox","shifts","tilePoints","points","getTileLines","lineBBox","tileLines","tileLine","Infinity","Within","geojson","geometries","features","polygonGeometry","tilePolygon","tilePolygons","pointsWithinPolygons","linesWithinPolygons","Within$1","isFeatureConstant","isStateConstant","isGlobalPropertyConstant","Var","boundExpression","Var$1","part","expr","index","_parse","annotate","typeAnnotation","Expr","actual","isConstant","ec","ParsingContext$1","isTypeAnnotation","childrenConstant","findStopLessThanOrEqualTo","stops","lastIndex","currentValue","nextValue","lowerIndex","upperIndex","currentIndex","Step","labels","outputs","label","outputType","labelKey","valueKey","stopCount","out","Step$1","from","to","Xn","Zn","t2","t3","deg2rad","rad2deg","xyz2lab","lab2xyz","xyz2rgb","rgb2xyz","rgbToLab","rgbColor","labToRgb","labColor","interpolateHue","lab","forward","reverse","interpolate","interpolateNumber","hcl","hclColor","Interpolate","operator","interpolation","lower","upper","exponentialInterpolation","base","controlPoints","rest","interpolationFactor","outputLower","outputUpper","lowerValue","upperValue","difference","progress","Interpolate$1","Coalesce","needsAnnotation","firstImage","argCount","Coalesce$1","Let","binding","Let$1","At","At$1","In","needle","haystack","In$1","IndexOf","fromIndex","IndexOf$1","Match","inputType","cases","otherwise","labelContext","MAX_SAFE_INTEGER","sortedLabels","Object","sort","groupedByOutput","outputLookup","outputIndex","coerceLabel","Match$1","Case","branches","_","Case$1","Slice","beginIndex","endIndex","Slice$1","isComparableType","eqCollate","makeComparison","compareBasic","compareWithCollator","isOrderComparison","Comparison","hasUntypedArgument","lt","rt","Equals","NotEquals","LessThan","GreaterThan","LessThanOrEqual","GreaterThanOrEqual","NumberFormat","currency","minFractionDigits","maxFractionDigits","style","minimumFractionDigits","maximumFractionDigits","format","Length","expressions","at","case","coalesce","in","let","literal","step","var","within","v","varargs","register","typeof","typeToString","rgb","zoom","pitch","heatmapDensity","lineProgress","skyRadialProgress","accumulated","ln2","LN2","pi","E","log10","LN10","ln","log2","asin","acos","atan","ceil","binarySearch","all","any","isSupportedScript","upcase","toUpperCase","downcase","expressions$1","success","supportsPropertyExpression","spec","supportsZoomExpression","parameters","supportsInterpolation","interpolated","getType","val","isFunction","identityFunction","createFunction","propertySpec","isColor","zoomAndFeatureDependent","zoomDependent","property","stop","default","colorSpace","colorSpaces","innerFun","hashedStops","categoricalKeyType","evaluateExponentialFunction","evaluateIntervalFunction","evaluateCategoricalFunction","create","evaluateIdentityFunction","featureFunctions","zoomStops","featureFunctionStops","interpolationType","keyType","interp","colorspace","evaluatedLower","apply","evaluatedUpper","StyleExpression","_warningHistory","_evaluator","_defaultValue","getDefaultValue","_enumValues","evaluateWithoutErrorHandling","isExpression","createExpression","parser","color","enum","formatted","resolvedImage","getExpectedType","ZoomConstantExpression","_styleExpression","isStateDependent","ZoomDependentExpression","createPropertyExpression","isZoomConstant","zoomCurve","findZoomCurve","StylePropertyFunction","specification","_parameters","_specification","childResult","mapboxHTTPURLRegex","config","API_URL","API_URL_REGEX","prodMapboxHTTPURLRegex","process","env","RegExp","API_TILEJSON_REGEX","API_SPRITE_REGEX","API_FONTS_REGEX","API_STYLE_REGEX","API_CDN_URL_REGEX","EVENTS_URL","url","URL","hostname","SESSION_PATH","FEEDBACK_URL","TILE_URL_VERSION","RASTER_URL_PREFIX","REQUIRE_ACCESS_TOKEN","ACCESS_TOKEN","MAX_PARALLEL_IMAGE_REQUESTS","exported","supported","testSupport","gl","webpCheckComplete","webpImgTest","webpImgTestOnloadComplete","testWebpTextureUpload","glForTesting","texture","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","isContextLost","deleteTexture","document","createElement","onload","onerror","PerformanceMarkers","load","fullLoad","getResourceCategory","entry","isMapboxHTTPCDNURL","includes","isMapboxHTTPFontsURL","isMapboxHTTPSpriteURL","isMapboxHTTPStyleURL","isMapboxHTTPTileJSONURL","AUTH_ERR_MSG","isMapboxHTTPURL","urlRe","parseUrl","parts","protocol","authority","formatUrl","telemEventKey","parseAccessToken","accessToken","decodeURIComponent","atob","charCodeAt","TelemetryEvent","anonId","eventData","queue","pendingRequest","getStorageKey","domain","tokenData","btoa","encodeURIComponent","fromCharCode","fetchEventData","isLocalStorageAvailable","storageKey","uuidKey","data","localStorage","getItem","saveEventData","processRequests","postEvent","timestamp","additionalPayload","callback","customAccessToken","eventsUrlObject","payload","event","created","Date","toISOString","finalPayload","request","headers","body","postData","queueRequest","turnstileEvent_","TurnstileEvent","_customAccessToken","postTurnstileEvent","tileUrls","isMapboxURL","now","lastSuccess","tokenU","dueForEvent","nextUpdate","lastUpdate","nextDate","daysElapsed","getDate","sdkIdentifier","sdkVersion","skuId","userId","err","mapLoadEvent_","MapLoadEvent","skuToken","postMapLoadEvent","mapId","errorCb","performanceEvent_","PerformanceEvent","postPerformanceEvent","performanceData","resourceTimers","performance","getEntriesByType","markerTimers","counters","category","timer","reqCount","reqCachedCount","startTime","responseEnd","increment","transferSize","getCountersPerResourceType","arr","categorize","devicePixelRatio","connection","mozConnection","webkitConnection","metrics","metadata","attributes","addMetric","counter","interactionRange","marker","markerName","markerTimer","find","visibilityHidden","getStyle","terrainEnabled","fogEnabled","projection","effectiveType","screen","width","height","innerWidth","innerHeight","renderer","vendor","getLivePerformanceMetrics","attribute","mapSessionAPI_","MapSessionAPI","getSession","token","authUrlObject","getData","getSessionAPI","Set","CACHE_NAME","sharedCache","responseConstructorSupportsReadableStream","cacheOpen","caches","getCaches","open","stripQueryParameters","paramStart","getQueryParameters","filteredParams","param","AJAXError","status","getReferrer","worker","referrer","location","href","makeRequest","requestParameters","fetch","Request","AbortController","hasOwnProperty","controller","method","credentials","referrerPolicy","signal","complete","aborted","cacheIgnoringSearch","validateOrFetch","cachedResponse","responseIsFresh","finishRequest","requestTime","then","response","ok","cacheableResponse","statusText","catch","json","Headers","toUTCString","expires","getTime","Response","ReadableStream","blob","prepareBody","clonedResponse","cache","put","cachePut","strippedURL","fresh","isFresh","delete","cacheGet","cancel","abort","makeFetchRequest","actor","send","xhr","XMLHttpRequest","responseType","setRequestHeader","withCredentials","getResponseHeader","makeXMLHttpRequest","getArrayBuffer","klass","defineProperty","writeable","omit","Grid","grid","transferables","deserialize","_classRegistryKey","isArrayBuffer","isImageBitmap","ImageBitmap","isView","view","ImageData","$name","ThrottledInvoker","_callback","_triggered","MessageChannel","_channel","port2","onmessage","trigger","port1","postMessage","setTimeout","remove","getPerformanceMeasurement","getEntriesByName","Scheduler","tasks","taskQueue","invoker","nextId","priority","isSymbolTile","getPriority","pick","task","minIndex","minPriority","splice","Actor","target","callbacks","cancelCallbacks","addEventListener","receive","globalScope","scheduler","targetMapId","mustQueue","callbackMetadata","substring","buffers","hasCallback","sourceMapId","processTask","done","getWorkerSource","source","removeEventListener","_addEventListener","listener","listenerList","_removeEventListener","Event","ErrorEvent","Evented","on","_listeners","off","_oneTimeListeners","once","Promise","resolve","fire","listens","listeners","oneTimeListeners","_eventedParent","_eventedParentData","setEventedParent","unbundle","valueOf","deepUnbundle","unbundledValue","ValidationError","identifier","__line__","validateObject","elementSpecs","valueSpec","elementValidators","objectElementValidators","styleSpec","objectKey","elementSpecKey","validateElement","validateSpec","required","validateArray","arraySpec","validateArrayElement","arrayElementValidator","validate","arrayElementSpec","minimum","maximum","function","$version","arrayIndex","validateNumber","specMin","specMax","validateFunction","functionValueSpec","functionType","stopKeyType","previousStopDomainValue","previousStopDomainZoom","stopDomainValues","isZoomFunction","isPropertyFunction","isZoomAndPropertyFunction","validateFunctionStop","nextStopDomainZoom","validateStopDomainValue","reportValue","isFinite","validateExpression","expressionContext","expressionObj","propertyKey","propertyType","disallowedFilterParameters","disallowedParameters","size","validateEnum","isExpressionFilter","createFilter","layerType","needGeometry","needFeature","convertFilter","filterExp","staticFilter","isDynamicFilter","unionDynamicBranches","collapseDynamicBooleanExpressions","extractStaticFilter","filterSpec","latest","compiledStaticFilter","filterFunc","globalProperties","dynamicFilterFunc","compiledDynamicFilter","dynamicFilter","geometryNeeded","collapsed","dynamicConditionExpressions","collapsedExpression","subExpression","isBranchingDynamically","convertComparisonOp","convertNegation","filters","convertInOp","convertHasOp","validateFilter","validateNonExpressionFilter","filter_operator","geometry_type","validateProperty","layerSpec","transitionMatch","transition","tokenMatch","tokens","exec","example","glyphs","validatePaintProperty","validateLayoutProperty","validateString","promoteId","prop","getSourceTypeValues","reduce","memo","sourceType","VALIDATORS","layer","ref","layerId","otherLayer","layers","paint","lineMetrics","layout","source_geojson","cluster","clusterProperties","mapExpr","reduceExpr","source_video","source_image","light","lightSpec","rootType","terrain","terrainSpec","fog","fogSpec","projectionSpec","validateGlyphsURL","validateStyle","latestStyleSpec","sortErrors","$root","opts","_validatePaintProperty","_validateLayoutProperty","unicodeBlockLookup","char","Hiragana","Katakana","Bopomofo","Kanbun","allowsVerticalWritingMode","chars","charHasUprightVerticalOrientation","allowsLetterSpacing","charAllowsLetterSpacing","isChar","charHasRotatedVerticalOrientation","charHasNeutralVerticalOrientation","charInRTLScript","charInSupportedScript","canRenderRTL","stringContainsRTLText","linkEl","reducedMotionQuery","stubTime","canvas","setNow","time","restoreNow","frame","requestAnimationFrame","cancelAnimationFrame","getImageData","img","getContext","willReadFrequently","clearRect","drawImage","resolveURL","prefersReducedMotion","matchMedia","matches","pluginStatus","pluginURL","sendPluginStateToWorker","evented","getRTLTextPluginStatus","downloadRTLTextPlugin","triggerPluginCompletionEvent","plugin","applyArabicShaping","processBidirectionalText","processStyledBidirectionalText","isLoaded","isLoading","setState","state","isParsed","getPluginURL","EvaluationParameters","fadeDuration","isStringInSupportedScript","rtlTextPlugin","PropertyValue","constant","normalizePropertyExpression","isDataDriven","possiblyEvaluate","TransitionablePropertyValue","transitioned","prior","TransitioningPropertyValue","untransitioned","Transitionable","_properties","_values","defaultTransitionablePropertyValues","getValue","setValue","getTransition","setTransition","Transitioning","delay","duration","begin","finalValue","easeCubicInOut","defaultTransitioningPropertyValues","PossiblyEvaluated","hasTransition","Layout","defaultPropertyValues","PossiblyEvaluatedPropertyValue","constantOr","defaultPossiblyEvaluatedValues","DataConstantProperty","DataDrivenProperty","overrides","ColorRampProperty","Properties","overridableProperties","defaultParameters","overridable","defaultPropertyValue","defaultTransitionablePropertyValue","packUint8ToFloat","viewTypes","Int8","Int8Array","Uint8","Uint8Array","Int16","Int16Array","Uint16","Uint16Array","Int32","Uint32","Uint32Array","Float32","Float32Array","Struct","structArray","_structArray","_pos1","_pos2","_pos4","_pos8","StructArray","isTransferred","capacity","resize","_trim","byteLength","bytesPerElement","_refreshViews","clear","reserve","oldUint8Array","uint8","destroy","int8","int16","uint16","int32","uint32","float32","createLayout","members","alignment","maxSize","member","typeSize","BYTES_PER_ELEMENT","memberOffset","align","components","StructArrayLayout2i4","emplaceBack","v0","emplace","o2","StructArrayLayout3i6","StructArrayLayout4i8","v3","StructArrayLayout2i4ub1f12","v4","v5","v6","o1","o4","StructArrayLayout4f16","StructArrayLayout4ui1f12","StructArrayLayout4ui8","StructArrayLayout6i12","StructArrayLayout4i4ui4i24","v7","v8","v9","v10","v11","StructArrayLayout3i3f20","StructArrayLayout1ul4","StructArrayLayout5i4f1i1ul2ui40","v12","StructArrayLayout3i2i2i16","StructArrayLayout2f1f2i16","StructArrayLayout2ub2f12","StructArrayLayout3f12","StructArrayLayout3ui6","StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60","v13","v14","v15","v16","v17","v18","v19","v20","StructArrayLayout3i2f6i15ui1ul3f76","v21","v22","v23","v24","v25","v26","v27","v28","v29","StructArrayLayout1f4","StructArrayLayout5f20","StructArrayLayout1ul3ui12","StructArrayLayout2ui4","StructArrayLayout1ui2","StructArrayLayout2f8","CollisionBoxStruct","projectedAnchorX","projectedAnchorY","projectedAnchorZ","tileAnchorX","tileAnchorY","featureIndex","sourceLayerIndex","bucketIndex","CollisionBoxArray","PlacedSymbolStruct","glyphStartIndex","numGlyphs","vertexStartIndex","lineStartIndex","lineLength","segment","lowerSize","upperSize","lineOffsetX","lineOffsetY","writingMode","placedOrientation","hidden","crossTileID","associatedIconIndex","flipState","PlacedSymbolArray","SymbolInstanceStruct","rightJustifiedTextSymbolIndex","centerJustifiedTextSymbolIndex","leftJustifiedTextSymbolIndex","verticalPlacedTextSymbolIndex","placedIconSymbolIndex","verticalPlacedIconSymbolIndex","textBoxStartIndex","textBoxEndIndex","verticalTextBoxStartIndex","verticalTextBoxEndIndex","iconBoxStartIndex","iconBoxEndIndex","verticalIconBoxStartIndex","verticalIconBoxEndIndex","numHorizontalGlyphVertices","numVerticalGlyphVertices","numIconVertices","numVerticalIconVertices","useRuntimeCollisionCircles","textOffset0","textOffset1","collisionCircleDiameter","SymbolInstanceArray","GlyphOffsetArray","getoffsetX","SymbolLineVertexArray","getx","gety","FeatureIndexStruct","layoutVertexArrayOffset","FeatureIndexArray","FillExtrusionCentroidArray","geta_centroid_pos0","geta_centroid_pos1","patternAttributes","dashAttributes","seed","remainder","bytes","h1","h1b","c1","c2","k1","murmur3","require","murmur2","murmurhashJsModule","FeaturePositionMap","ids","positions","indexed","getNumericId","getPositions","intId","Float64Array","numValue","MIN_SAFE_INTEGER","left","right","pivot","swap","tmp","Uniform","initialized","fetchUniformLocation","program","getUniformLocation","Uniform1f","current","uniform1f","Uniform4f","uniform4f","UniformColor","packColor","ConstantBinder","names","uniformNames","setUniform","uniform","uniformName","getBinding","PatternConstantBinder","pattern","pixelRatio","setConstantPatternPositions","posTo","tl","br","pos","SourceExpressionBinder","PaintVertexArray","maxValue","paintVertexAttributes","paintVertexArray","populatePaintArray","newLength","imagePositions","_setPaintValue","updatePaintArray","upload","paintVertexBuffer","updateData","createVertexBuffer","CompositeExpressionBinder","useIntegerZoom","minColor","maxColor","currentZoom","factor","PatternCompositeBinder","_setPaintValues","patterns","ProgramConfiguration","filterProperties","binders","_buffers","paintAttributeNames","isPattern","sourceException","StructArrayLayout","layoutType","cacheKey","getMaxValue","binder","populatePaintArrays","updatePaintArrays","featureStates","featureMap","vtLayer","dirty","defines","getBinderAttributes","getBinderUniforms","uniforms","getPaintVertexBuffers","getUniforms","setUniforms","binderUniforms","updatePaintBuffers","ProgramConfigurationSet","programConfigurations","needsUpload","_featureMap","_bufferOffset","attributeNameExceptions","propertyExceptions","PatternLayoutArray","composite","DashLayoutArray","defaultLayouts","binderType","layoutException","TRANSITION_SUFFIX","StyleLayer","_featureFilter","_filterCompiled","minzoom","maxzoom","sourceLayer","_unevaluatedLayout","_transitionablePaint","setPaintProperty","setLayoutProperty","_transitioningPaint","getLayoutProperty","visibility","_validate","getPaintProperty","transitionable","wasDataDriven","oldValue","_handleSpecialPaintPropertyUpdate","newValue","_handleOverridablePaintPropertyUpdate","getProgramIds","getProgramConfiguration","isHidden","updateTransitions","recalculate","filterObject","emitter","hasErrors","emitValidationErrors","sprite","is3D","isSky","isTileClipped","hasOffscreenPass","compileFilter","featureFilter","invalidateCompiledFilter","dynamicFilterNeedsFeature","circleAttributes","circleGlobeAttributesExt","SegmentVector","segments","prepareSegment","numVertices","layoutVertexArray","indexArray","sortKey","MAX_VERTEX_ARRAY_LENGTH","vertexLength","vertexOffset","primitiveOffset","primitiveLength","vaos","LngLatBounds","sw","ne","setSouthWest","setNorthEast","_ne","LngLat","lat","_sw","sw2","ne2","getCenter","getSouthWest","getNorthEast","getNorthWest","getWest","getNorth","getSouthEast","getEast","getSouth","contains","lnglat","containsLongitude","EPSILON","ARRAY_TYPE","identity","invert","a00","a01","a02","a03","a10","a11","a12","a13","a20","a21","a22","a23","a30","a31","a32","a33","b00","b01","b02","b03","b04","b05","b06","b07","b08","b09","b10","b11","det","multiply","b0","b1","b2","b3","translate","glMatrix","hypot","fromValues","scaleAndAdd","dot","transformMat4","arguments","vec3","posAttributesGlobeExt","posAttributes","Ray","pos_","dir_","dir","intersectsPlane","pt","normal","D","closestPointOnSphere","a0","a1","a2","dz","px","py","pz","gx","gy","gz","glen","plen","Aabb","aabb","transform","corners","getCorners","fromPoints","min_","max_","quadrant","qMin","qMax","axis","distanceX","distanceY","distanceZ","mn","mx","intersects","frustum","aabbPoints","fullyInside","planes","plane","pointsInside","projMin","MAX_VALUE","projMax","projectedPoint","GLOBE_RADIUS","GLOBE_NORMALIZATION_MASK","GLOBE_MIN","GLOBE_MAX","GLOBE_LOW_ZOOM_TILE_AABBS","globeMetersToEcef","earthRadius","globePointCoordinate","tr","clampToHorizon","point0","_camera","position","point1","vec4","pixelMatrixInverse","globeMatrix","globeCenter","p0toCenter","p0toCenterDist","centerDir","radius","cosAngle","origoTangentAngle","clampedP1","origoToP1","pointOnGlobe","xa","ya","za","xp","yp","zp","diff","shortestAngle","mercatorXfromLng","my","mercatorYfromLat","MercatorCoordinate","globeTileBounds","boundsToECEF","tileCornersToBounds","interpolateVec3","phase","lngFromMercatorX","latFromMercatorY","bounds","ny","sy","cosN","cosS","sinN","sinS","csLatLngToECEF","cosLat","sinLat","latLngToECEF","tileCoordToECEF","tileCount","mercatorX","globeECEFNormalizationScale","tempMatrix","globeNormalizeECEF","mat4","globeToMercatorTransition","earthCircumference","distanceTo","lngLat","rad","lat1","lat2","toBounds","latAccuracy","lngAccuracy","toEcef","altitude","altInEcef","lon","LngLat$1","circumferenceAtLatitude","latitude","mercatorZfromAltitude","exp","MAX_MERCATOR_LATITUDE","lngLatLike","toLngLat","toAltitude","meterInMercatorCoordinateUnits","addResampled","resampled","mx0","my0","mx2","my2","reproject","tolerance","mx1","my1","mid","pointToLineDist","resample","prev","addResampledPred","pred","resamplePred","predicate","MAX","BITS","MIN","preparePoint","loadGeometry","tileTransform","extentScale","isReprojectedInTileSpace","z2","project","toEvaluationFeature","addCircleVertex","extrudeX","extrudeY","addGlobeExtVertex","vertexArray","encode","CircleBucket","overscaling","layerIds","hasPattern","CircleLayoutArray","TriangleIndexArray","stateDependentLayerIds","populate","styleLayer","bucketFeatures","circleSortKey","evaluationFeature","bucketFeature","globeProjection","globeExtVertexArray","CircleGlobeExtArray","addFeature","update","states","stateDependentLayers","uploadPending","uploaded","layoutVertexBuffer","indexBuffer","createIndexBuffer","globeExtVertexBuffer","projectTilePoint","upVector","polygonIntersectsPolygon","polygonA","polygonB","polygonContainsPoint","lineIntersectsLine","polygonIntersectsBufferedPoint","pointIntersectsBufferedLine","polygonIntersectsMultiPolygon","multiPolygon","multiPolygonContainsPoint","lineIntersectsBufferedLine","lineA","lineB","lineSegmentIntersectsLineSegment","radiusSquared","distToSegmentSquared","l2","edgeIntersectsBox","e1","e2","getMaximumPaintValue","bucket","translateDistance","queryGeometry","translateAnchor","pixelsToTileUnits","translated","tilespaceTranslate","properties$9","queryIntersectsCircle","pixelPosMatrix","elevationHelper","alignWithMap","scaleWithMap","translation","isAboveHorizon","pixelToTileUnitsFactor","tileId","tileID","elevationScale","upVectorScale","metersToTile","translatedPoint","elevation","exaggeration","getElevationAt","reproj","transformedPoint","projectPoint","transformedPolygon","tilespaceRays","intersectAtHeight","screenGeometry","projectedCenter","cameraToCenterDistance","pixelsPerMeter","origin","up","intersectionPt","HeatmapBucket","createImage","channels","Uint8ClampedArray","RangeError","resizeImage","newImage","copyImage","srcImg","dstImg","srcPt","dstPt","srcData","dstData","srcOffset","dstOffset","AlphaImage","RGBAImage","copy","properties$8","renderColorRamp","evaluationGlobals","resolution","clips","renderPixel","stride","evaluationKey","pxColor","clip","properties$7","earcut","holeIndices","dim","minX","minY","maxX","maxY","invSize","hasHoles","outerLen","outerNode","linkedList","triangles","next","list","steiner","getLeftmost","compareX","eliminateHole","eliminateHoles","earcutLinked","clockwise","last","signedArea","insertNode","removeNode","filterPoints","again","area","ear","pass","zOrder","prevZ","nextZ","q","tail","numMerges","pSize","qSize","inSize","sortLinked","indexCurve","isEarHashed","isEar","cureLocalIntersections","splitEarcut","x0","y0","pointInTriangle","minZ","maxZ","locallyInside","isValidDiagonal","splitPolygon","hole","bridge","hx","hy","qx","tanMin","sectorContainsSector","findHoleBridge","bridgeReverse","leftmost","intersectsPolygon","middleInside","sign","o3","onSegment","Node","an","bp","earcutModule","deviation","polygonArea","trianglesArea","flatten","vertices","holes","dimensions","holeIndex","quickselect","quickselectStep","defaultCompare","sd","classifyRings","maxRings","ccw","compareAreas","patternDependencies","patternProperty","constantPattern","addPatternDependencies","patternFeature","patternPropertyValue","FillBucket","patternFeatures","FillLayoutArray","indexArray2","LineIndexArray","segments2","fillSortKey","addFeatures","layoutAttributes","indexBuffer2","triangleSegment","triangleIndex","flattened","lineSegment","lineIndex","indices","properties$6","fillExtrusionAttributes","centroidAttributes","fillExtrusionAttributesExt","VectorTileFeature","pbf","_pbf","_geometry","_keys","readFields","readFeature","tag","readVarint","readTag","cmd","lines","cmdLen","readSVarint","toGeoJSON","coords","VectorTileLayer","version","_features","readLayer","readString","readFloat","readDouble","readVarint64","readBoolean","readValueMessage","readTile","VectorTile","vectorTile","clipPolygon","clipAxis1","clipAxis2","polygonsClipped","intersect","polygonClipped","clipped","vectorTileFeatureTypes","FACTOR","addVertex","nxRatio","nySign","normalUp","top","PartMetadata","acc","polyCount","startRing","currentPolyCount","edges","append","processBorderOverlap","addBorderIntersection","borders","centroid","count","span","intersectsCount","FillExtrusionBucket","edgeRadius","FillExtrusionLayoutArray","centroidVertexArray","enableTerrain","featuresOnBorder","borderDoneWithNeighborZ","tileToMeter","circumferenceAtEquator","vertexArrayOffset","sortBorders","layoutVertexExtArray","layoutVertexExtBuffer","uploadCentroid","centroidVertexBuffer","needsCentroidUpdate","tileBounds","isGlobe","isPolygon","FillExtrusionExtArray","clippedPolygons","resampleFillExtrusionPolygonsForGlobe","topIndex","na","nb","nm","kFirst","isPrevCornerConcave","isAOConcaveAngle","offsetPrev","getRoundedEdgeOffset","cap","edgeDistance","p0","isEdgeOutsideBounds","offsetNext","_getRoundedEdgeOffset","getCosHalfAngle","nEdge","isConcaveCorner","encodedEdgeDistance","encodeAOToEdgeDistance","projectedP0","projectedP1","n0","n1","encodeCentroid","polyInfo","cosHalfAngle","sinHalfAngle","p3","cosAB","edgeStart","tiles","leftLng","rightLng","topLat","bottomLat","gridSizeX","gridSizeY","splitFn","outPolygons","addResult","hSplits","vSplits","initialSplits","splits","stack","depth","bboxMin","bboxMax","splitMin","splitMax","splitMid","lclip","rclip","lclipBounds","rclipBounds","subdividePolygons","maxLat","properties$5","getMercCoords","CanonicalTileID","calculateKey","urls","scheme","getTileBBox","quadkey","mask","getQuadkey","UnwrappedTileID","OverscaledTileID","overscaledZ","scaledTo","targetZ","zDifference","calculateScaledKey","withWrap","isChildOf","children","sourceMaxZoom","isLessThan","wrapped","unwrapTo","overscaleFactor","toUnwrapped","xy","bitsAvailable","Point3D","getIntersectionDistance","projectedQueryGeometry","projectedFace","ab","ac","ap","dotABAB","dotABAC","dotACAC","dotAPAB","dotAPAC","denom","distance","closestDistance","getTerrainHeightOffset","zBase","zTop","demSampler","ele","flatRoof","centroidElevation","posX","posY","spanX","spanY","meterToDEM","getMeterToDEM","wX","wY","posPx","tileCoordToPixel","offsetX","offsetY","getElevationAtPixel","fourSample","diffX","diffY","diffSumY","slopeX","slopeY","flatElevation","lineLayoutAttributes","lineLayoutAttributesExt","COS_HALF_SHARP_CORNER","LineBucket","lineClipsArray","gradients","LineLayoutArray","layoutVertexArray2","LineExtLayoutArray","maxLineLength","lineSortKey","lineAtlas","hasFeatureDashes","addConstantDashes","addFeatureDashes","patternBucketFeature","dashPropertyValue","capPropertyValue","constCap","constDash","addDash","dashArray","getKey","layoutVertexBuffer2","layoutAttributesExt","lineFeatureClips","miterLimit","roundLimit","lineClips","addLine","scaledDistance","totalDistance","lineSoFar","updateScaledDistance","first","sharpCornerOffset","currentVertex","prevVertex","nextVertex","prevNormal","nextNormal","joinNormal","miterLength","approxAngle","isSharpCorner","lineTurnsLeft","prevSegmentLength","newPrevVertex","updateDistance","addCurrentVertex","middleVertex","currentJoin","bevelLength","offsetA","offsetB","extrude","addHalfVertex","nextSegmentLength","newCurrentVertex","endLeft","endRight","leftX","rightX","rightY","totalFeatureLength","properties$4","lineFloorwidthProperty","LineFloorwidthProperty","getLineWidth","lineWidth","lineGapWidth","symbolLayoutAttributes","symbolGlobeExtAttributes","dynamicLayoutAttributes","collisionVertexAttributes","collisionVertexAttributesExt","collisionBoxLayout","ONE_EM","SIZE_PACK_FACTOR","getSizeData","tileZoom","layoutSize","minZoom","maxZoom","minSize","evaluateSizeForFeature","sizeData","uSize","uSizeT","evaluateSizeForZoom","transformText$1","toLocaleUpperCase","toLocaleLowerCase","transformText","verticalizedCharacterMap","$","isVerticalClosePunctuation","chr","isVerticalOpenPunctuation","Pbf","ieee754","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","buf","Varint","Fixed64","Bytes","Fixed32","SHIFT_LEFT_32","SHIFT_RIGHT_32","utf8TextDecoder","TextDecoder","readPackedEnd","toNum","low","high","isSigned","makeRoomForExtraLength","startPos","extraLen","realloc","writePackedVarint","writeVarint","writePackedSVarint","writeSVarint","writePackedFloat","writeFloat","writePackedDouble","writeDouble","writePackedBoolean","writeBoolean","writePackedFixed32","writeFixed32","writePackedSFixed32","writeSFixed32","writePackedFixed64","writeFixed64","writePackedSFixed64","writeSFixed64","readUInt32","writeInt32","readInt32","readField","skip","readMessage","readFixed32","readSFixed32","readFixed64","readSFixed64","readVarintRemainder","decode","readUtf8TextDecoder","bytesPerSequence","readUtf8","readBytes","readPackedVarint","readPackedSVarint","readPackedBoolean","readPackedFloat","readPackedDouble","readPackedFixed32","readPackedSFixed32","readPackedFixed64","readPackedSFixed64","writeTag","finish","writeBigVarintLow","lsb","writeBigVarintHigh","writeBigVarint","writeString","lead","writeUtf8","writeBytes","writeRawMessage","writeMessage","writeBytesField","writeFixed32Field","writeSFixed32Field","writeFixed64Field","writeSFixed64Field","writeVarintField","writeSVarintField","writeStringField","writeFloatField","writeDoubleField","writeBooleanField","GLYPH_PBF_BORDER","potpack","boxes","maxWidth","box","startWidth","spaces","space","fill","IMAGE_PADDING","ImagePosition","paddedRect","stretchX","stretchY","displaySize","ImageAtlas","icons","iconPositions","patternPositions","haveRenderCallbacks","bins","addImages","bin","images","hasRenderCallback","patchUpdatedImages","imageManager","hasImage","dispatchRenderCallbacks","updatedImages","patchUpdatedImage","getImage","WritingMode","horizontal","vertical","horizontalOnly","SHAPING_DEFAULT_OFFSET","SectionOptions","imageName","textOptions","imageOptions","TaggedString","sectionIndex","imageSectionID","defaultFontStack","addImageSection","addTextSection","getSection","getSections","getSectionIndex","getCharCode","verticalizePunctuation","skipContextChecking","nextCharCode","prevCharCode","trim","beginningWhitespace","whitespace","trailingWhitespace","getMaxScale","forText","nextImageSectionCharCode","getNextImageSectionCharCode","forImage","shapeText","glyphMap","glyphPositions","lineHeight","textAnchor","textJustify","spacing","allowVerticalPlacement","layoutTextSize","layoutTextSizeThisZoom","logicalInput","fromFeature","lineBreaks","potentialLineBreaks","targetWidth","totalWidth","getGlyphAdvance","determineAverageLineWidth","hasServerSuggestedBreakpoints","currentX","codePoint","ideographicBreak","breakable","evaluateBreak","calculatePenalty","leastBadBreaks","determineLineBreaks","untaggedLines","taggedLine","processedLines","lineBreakPoints","lineBreak","breakLines","positionedLines","shaping","bottom","iconsInText","verticalizable","hasBaseline","justify","glyphData","ascender","descender","lineMaxScale","maxLineOffset","positionedLine","positionedGlyphs","lineOffset","biggestHeight","baselineOffset","sectionScale","rect","verticalAdvance","glyphOffset","imagePosition","advance","localGlyph","glyphPositionData","glyph","justifyLine","currentLineHeight","horizontalAlign","verticalAlign","getAnchorAlignment","blockHeight","shiftX","shiftY","positionedGlyph","shapeLines","calculateBadness","penalty","isLastBreak","raggedness","nextCodePoint","penalizableIdeographicBreak","breakIndex","breakX","potentialBreaks","bestPriorBreak","bestBreakBadness","potentialBreak","breakBadness","badness","priorBreak","lastLineBreak","anchor","halfLineHeight","lastGlyph","lineIndent","shapeIcon","iconOffset","iconAnchor","fitIconToText","shapedIcon","shapedText","textFit","fontScale","collisionPadding","textLeft","textRight","textTop","textBottom","Anchor","checkMaxAngle","labelLength","windowSize","maxAngle","anchorDistance","recentCorners","recentAngleDelta","angleDelta","getLineLength","getAngleWindowSize","glyphSize","boxScale","getShapedLabelLength","getCenterAnchor","angleWindowSize","prevDistance","centerDistance","segmentDistance","getAnchors","tileExtent","shapedLabelLength","isLineContinued","placeAtMiddle","halfLabelLength","markedDistance","anchors","segmentDist","SDF_SCALE","border","getIconQuads","iconRotate","isSDFIcon","hasIconTextFit","quads","imageWidth","imageHeight","iconWidth","iconHeight","reduceRanges","range","stretchWidth","stretchHeight","fixedWidth","fixedHeight","stretchOffsetX","stretchContentWidth","stretchOffsetY","stretchContentHeight","fixedOffsetX","fixedContentWidth","fixedOffsetY","fixedContentHeight","sumWithinRange","makeBox","leftEm","getEmOffset","stretch","leftPx","getPxOffset","fixed","topEm","topPx","rightEm","rightPx","bottomEm","bottomPx","bl","pixelOffsetTL","pixelOffsetBR","tex","minFontScaleX","minFontScaleY","isSDF","xCuts","stretchZonesToCuts","yCuts","xi","yi","ranges","stretchZones","fixedSize","stretchSize","cuts","stretchOffset","iconSize","fixedOffset","getMidlineOffset","previousOffset","TinyQueue","_down","_up","peek","halfLength","best","findPoleOfInaccessibility","polygonRings","precision","debug","outerRing","cellSize","cellQueue","Queue","compareMax","Cell","bestCell","getCentroidCell","numProbes","minDistSq","pointToPolygonDist","SQRT2","INVALID_TEXT_OFFSET","POSITIVE_INFINITY","sqrt2","evaluateVariableOffset","hypotenuse","performSymbolLayout","imageMap","showCollisionBoxes","createArrays","tilePixelRatio","compareText","iconsNeedLinear","unevaluatedLayoutValues","sizes","textSizeData","compositeTextSizes","iconSizeData","compositeIconSizes","layoutIconSize","textMaxSize","textAlongLine","textSize","fontstack","shapedTextOrientations","textOffset","unformattedText","spacingIfAllowed","variableTextAnchor","radialOffset","isPointPlacement","addVerticalShapingIfNeeded","justifications","getAnchorJustification","singleLine","justification","icon","sdf","sdfIcons","getDefaultHorizontalShaping","generateCollisionDebugBuffers","collisionBoxArray","defaultShaping","textMaxBoxScale","symbolMinDistance","textPadding","iconPadding","textMaxAngle","iconAlongLine","symbolPlacement","textRepeatDistance","iconTextFit","verticallyShapedIcon","addSymbolAtAnchor","canonicalId","globe","iconBoxScale","lineArray","addToLineVertexArray","textBoxIndex","iconBoxIndex","verticalTextBoxIndex","verticalIconBoxIndex","textCircle","verticalTextCircle","verticalIconCircle","placedTextSymbolIndices","collisionFeatureAnchor","verticalShaping","evaluateCircleCollisionFeature","verticalTextRotation","evaluateBoxCollisionFeature","iconQuads","verticalIconQuads","MAX_PACKED_SIZE","MAX_GLYPH_ICON_SIZE","addSymbols","placedSymbolArray","addTextVertices","getCollisionCircleHeight","diameter","prevHeight","glyphOffsetArray","SymbolBucket","MAX_GLYPHS","addToSortKeyRanges","symbolInstances","addSymbol","clippedLines","clippedLine","clipLine","anchorIsTooClose","poi","tileAnchor","placementTypes","placedIconIndex","glyphQuads","alongLine","textRotate","rotateOffset","product","getRotateOffset","shapingHeight","lineCounts","currentOffset","textureRect","rectBuffer","rotateVerticalGlyph","halfAdvance","builtInOffset","verticalizedLabelOffset","useRotateOffset","paddedWidth","paddedHeight","yShift","verticalRotation","verticalOffsetCorrection","getGlyphQuads","placementType","horizontalShaping","projectedAnchor","shaped","rotateRadians","rotateCenter","repeatDistance","otherAnchors","farthestPixelDistanceOnPlane","fovAboveCenter","minElevationInPixels","getMinElevationBelowMSL","cameraToSeaLevelDistance","_pitch","topHalfSurfaceDistance","furthestDistance","_horizonShift","lng1","lng2","maxErr","processSegment","pa","pb","pm","Projection","requiresDraping","supportsWorldCopies","supportsTerrain","supportsFog","supportsFreeCamera","zAxisUnit","unsupportedLayers","unproject","locationPoint","_coordinatePoint","locationCoordinate","pixelSpaceConversion","interpolationT","farthestPixelDistance","pointCoordinate","horizonOffset","horizonLineFromTop","clamped","rayIntersectionCoordinate","pointRayIntersection","pointCoordinate3D","mc","isPointAboveHorizon","horizon","createInversionMatrix","createTileMatrix","scaledX","scaledY","posMatrix","cs","zoomScale","Albers","lat0","parallels","sy0","r0","lambda","phi","r0y","dt","a3","a4","M","EqualEarth","theta","theta2","theta6","delta","fy","fpy","Equirectangular","halfPi","tany","LambertConformalConic","southernCenter","cy0","tany0","signFy","Mercator","maxPhi","NaturalEarth","phi2","phi4","WinkelTripel","twoOverPi","sinAlphaOverAlpha","dlambda","dphi","cosphi","sinphi","sinphi2","sin2phi","cos2phi","coslambda2","sinlambda2","sinlambda","sin2lambda2","C","F","fx","dxdlambda","dxdphi","dydlambda","dydphi","denominator","CylindricalEqualArea","cosPhi","y_","Globe","getAtPointOrZero","_centerAltitude","pixelMatrix","centerScale","combinedScale","globeDenormalizeECEF","_pixelsPerMercatorPixel","globePixelDistance","cameraDistance","centerPixelAltitude","camera","cameraPosition","globeRadius","aspectRatio","tanFovAboveCenter","pixelDistance","globeCenterToCamera","cameraToGlobe","cameraHeight","farthestPixelDistanceOnSphere","mercatorPixelDistance","pixelRadius","approxTileArcHalfAngle","getProjection","isDegenerateConic","shaderOpacityAttributes","ox","oy","tx","ty","sizeVertex","pixelOffsetX","pixelOffsetY","aSizeX","aSizeY","addGlobeVertex","projAnchorX","projAnchorY","projAnchorZ","normX","normY","normZ","addDynamicAttributes","dynamicLayoutVertexArray","containsRTLText","formattedText","SymbolBuffers","SymbolLayoutArray","SymbolDynamicLayoutArray","opacityVertexArray","SymbolOpacityArray","SymbolGlobeExtArray","dynamicIndexBuffer","dynamicLayoutVertexBuffer","opacityVertexBuffer","itemSize","CollisionBuffers","LayoutArray","IndexArray","collisionVertexArray","CollisionVertexArray","collisionVertexArrayExt","CollisionVertexExtArray","collisionVertexBuffer","collisionVertexBufferExt","hasRTLText","fullyClipped","sortKeyRanges","collisionCircleArray","placementInvProjMatrix","placementViewportMatrix","canOverlap","sortFeaturesByKey","sortFeaturesByY","writingModes","wm","sourceID","lineVertexArray","calculateGlyphDependencies","doesAllowVerticalWritingMode","verticalChar","charAt","textFont","textField","iconImage","hasText","hasIcon","symbolSortKey","iconDependencies","stacks","glyphDependencies","geom","cosAngleThreshold","resolvedTokens","getValueAndResolveTokens","factory","globalRTLTextPlugin","sectionFont","sectionStack","leftIndex","rightIndex","mergedFeatures","mergedIndex","mergeFromRight","leftKey","rightKey","mergeFromLeft","onRight","mergeLines","hasDebugData","textCollisionBox","iconCollisionBox","destroyDebugData","projectionInstance","arrays","glyphOffsetArrayStart","ux","uy","uz","_commitLayoutVertex","boxTileAnchorX","boxTileAnchorY","boxTileAnchorZ","_addCollisionDebugVertices","symbolInstance","symbolTileAnchorX","symbolTileAnchorY","_addTextDebugCollisionBoxes","startIndex","instance","getSymbolInstanceTextSize","_addIconDebugCollisionBoxes","getSymbolInstanceIconSize","CollisionBoxLayoutArray","symbolSize","boxIndex","symbol","featureSize","iconIndex","_commitDebugCollisionVertexUpdate","_updateTextDebugCollisionBoxes","_updateIconDebugCollisionBoxes","symbolIndex","updateCollisionDebugBuffers","hasTextCollisionBoxData","hasIconCollisionBoxData","_deserializeCollisionBoxesForSymbol","textStartIndex","textEndIndex","verticalTextStartIndex","verticalTextEndIndex","iconStartIndex","iconEndIndex","verticalIconStartIndex","verticalIconEndIndex","collisionArrays","textBox","textFeatureIndex","verticalTextBox","verticalTextFeatureIndex","iconBox","iconFeatureIndex","verticalIconBox","verticalIconFeatureIndex","deserializeCollisionBoxes","hasTextData","hasIconData","addIndicesForPlacedSymbol","iconOrText","placedSymbolIndex","placedSymbol","vertexIndex","getSortedSymbolIndexes","sortedAngle","symbolInstanceIndexes","rotatedYs","featureIndexes","aIndex","bIndex","symbolInstanceIndex","symbolInstanceEnd","symbolInstanceStart","sortFeatures","featureSortOrder","iconVertical","properties$3","runtimeType","getOverride","o","hasOverride","FormatSectionOverride","defaultValue","SymbolStyleLayer","deduped","_setPaintOverrides","unevaluated","resolveTokens","createBucket","queryRadius","queryIntersectsFeature","hasPaintOverride","overriden","override","styleExpression","_interpolationType","propertyName","hasOverrides","checkSections","checkExpression","properties$2","properties$1","CustomStyleLayer","implementation","renderingMode","prerender","isLayerDraped","renderToTile","shouldRedrape","shouldRerenderTiles","onAdd","painter","onRemove","getCelestialDirection","azimuth","leftHanded","rotation","quat","az","aw","bw","qy","qz","uvx","uvy","uvz","uuvx","uuvy","uuvz","w2","subclasses","circle","CircleStyleLayer","circleBucket","heatmap","HeatmapStyleLayer","_updateColorRamp","colorRamp","colorRampTexture","heatmapFbo","hillshade","HillshadeStyleLayer","FillStyleLayer","outlineColor","tilespaceGeometry","FillExtrusionStyleLayer","terrainVisible","tile","getBucket","centroidOffset","flat","projectedBase","projectedTop","basePoint","topPoint","setPoint","lift","tanAngle","fillExtrusionHeightLift","ringBase","ringTop","zBasePoint","zTopPoint","projectExtrusionGlobe","heightOffset","projectExtrusion3D","baseXZ","baseYZ","baseZZ","baseWZ","topXZ","topYZ","topZZ","topWZ","sX","sY","sZ","sW","baseX","baseY","baseZ","baseW","topX","topY","topZ","topW","projectExtrusion2D","projectExtrusion","screenQuery","topA","face","checkIntersection","isPointQuery","screenBounds","LineStyleLayer","gradientVersion","stepInterpolant","gradientExpression","widthExpression","lineBucket","translatedPolygon","halfWidth","newRings","zero","newRing","aToB","bToC","offsetLine","multiLine","polygonIntersectsBufferedMultiLine","background","BackgroundStyleLayer","raster","RasterStyleLayer","sky","SkyLayer","_skyboxInvalidated","needsSkyboxCapture","skyboxTexture","skyboxGeometry","lightPosition","_lightPosition","azimuthal","polar","sunPosition","useLightPosition","direction","markSkyboxValid","refProperties","StyleLayerIndex","layerConfigs","keyCache","_layerConfigs","_layers","removedIds","layerConfig","familiesBySource","groups","cachedKeys","group","groupByLayout","sourceId","sourceGroup","sourceLayerId","sourceLayerFamilies","DictionaryCoder","strings","_stringToNumber","_numberToString","customProps","Feature","vectorTileFeature","_vectorTileFeature","_z","_x","_y","Texture","HTMLImageElement","HTMLCanvasElement","HTMLVideoElement","pixelStoreUnpackFlipY","pixelStoreUnpack","pixelStoreUnpackPremultiplyAlpha","premultiply","texSubImage2D","useMipmap","isSizePowerOfTwo","generateMipmap","texParameteri","TEXTURE_MAG_FILTER","TEXTURE_MIN_FILTER","NEAREST","NEAREST_MIPMAP_NEAREST","LINEAR_MIPMAP_NEAREST","TEXTURE_WRAP_S","TEXTURE_WRAP_T","meshSize","gridSize","numTriangles","reprojectedCoords","used","indexMap","seamPadding","boundsAttributes","BOUNDS_FEATURE","Tile","isRaster","uses","tileSize","buckets","expirationTime","queryPadding","hasSymbolBuckets","dependencies","expiredRequestCount","registerFadeDuration","fadeEndTime","timeAdded","browser","wasRequested","_tileTransform","loadVectorData","justReloaded","unloadVectorData","latestFeatureIndex","rawTileData","latestRawTileData","getLayer","lId","deserializeBucket","imageAtlas","glyphAtlasImage","hasData","imageAtlasTexture","glyphAtlasTexture","lineAtlasTexture","_tileBoundsBuffer","_tileBoundsIndexBuffer","_tileBoundsSegments","_tileDebugBuffer","_tileDebugSegments","_tileDebugIndexBuffer","_globeTileDebugBorderBuffer","_tileDebugTextBuffer","_tileDebugTextSegments","_tileDebugTextIndexBuffer","_globeTileDebugTextBuffer","ALPHA","prepare","queryRenderedFeatures","serializedLayers","sourceFeatureState","tileResult","visualizeQueryGeometry","querySourceFeatures","vtLayers","loadVTLayers","_geojsonTileLayer","getId","geojsonFeature","GeoJSONFeature","patternsLoaded","setExpiryData","parsedCC","isExpired","getExpiryTimeout","setFeatureState","listImages","hasLayer","sourceLayerStates","sourceCache","_getSourceCache","_terrain","enabled","_clearRenderCacheForTile","holdingForFade","symbolFadeHoldUntil","symbolFadeFinished","clearFadeHold","setHoldDuration","setTexture","getTileTexture","LINEAR","CLAMP_TO_EDGE","setDependencies","namespace","dep","hasDependency","namespaces","clearQueryDebugViz","_makeDebugTileBoundsBuffers","boundsLine","debugVertices","PosArray","debugIndices","LineStripIndexArray","simpleSegment","_makeTileBoundsBuffers","boundsVertices","boundsIndices","mesh","mIndex","isUsed","TileBoundsArray","addTriangles","ai","bi","ci","getTileMesh","_makeGlobeTileDebugBuffers","freezeTileCoverage","nw","se","worldToECEFMatrix","transitionTileAABBinECEF","normalizationMatrix","_makeGlobeTileDebugBorderBuffer","_makeGlobeTileDebugTextBuffer","_globePoint","ecef","camX","camY","mercatorY","mercatorPos","extraGlobe","PosGlobeExtArray","sx","ex","ey","pointCount","stepX","stepY","vOffset","gp","totalVertices","SEGMENTS","toIndex","SourceFeatureState","stateChanges","deletedStates","updateState","featureId","newState","ft","removeFeatureState","getState","reconciledState","featureDeletions","initializeTileState","coalesceChanges","featuresChanged","layerStates","MipLevel","size_","minimums","maximums","leaves","getElevation","idx","toIdx","isLeaf","aabbRayIntersect","tMin","tMax","ood","temp","triangleRayIntersect","bz","cz","abX","abY","abZ","acX","acY","acZ","pvecX","pvecY","pvecZ","invDet","tvecX","tvecY","tvecZ","qvecX","qvecY","qvecZ","frac","lo","hi","decodeBounds","boundsMinx","boundsMiny","boundsMaxx","boundsMaxy","outMin","outMax","rangex","rangey","DemMinMaxQuadTree","dem_","childOffsets","nodeCount","dem","_siblingOffset","mips","levelCount","blockCount","blockSize","blockSamples","exclusive","outBounds","maxx","miny","maxy","mip","blockBounds","e0","sampleElevation","e3","prevMip","l0","l1","l3","minElevation","maxElevation","canConcatenate","buildDemMipmap","maxLvl","rootMip","_addNode","_construct","raycastRoot","minx","raycast","rootMinx","rootMiny","rootMaxx","rootMaxy","tHits","sortedHits","boundsMin","boundsMax","nodex","nodey","minxUv","maxxUv","minyUv","maxyUv","hitPos","bilinearLerp","hitCount","tHit","added","hitIdx","leaf","lvl","parentIdx","childLvl","childMip","leafMask","firstNodeIdx","childX","childY","nodeIdx","p00","p10","p01","p11","demSize","ixMin","iyMin","ixMax","iyMax","unpackVectors","mapbox","terrarium","unpackMapbox","unpackTerrarium","DEMData","tree","_tree","_buildQuadTree","encoding","borderReady","buildQuadTree","pixels","_idx","clampToEdge","unpackVector","vector","getUnpackVector","getPixels","backfillBorder","borderTile","xMin","xMax","yMin","yMax","onDeserialize","TileCache","reset","removedData","timeout","clearTimeout","order","expiryTimeout","dataWrapper","_getAndRemoveByKey","getAndRemove","getByKey","dataIndex","setMaxSize","filterFn","removed","ColorMode","blendFunction","blendColor","Replace","disabled","unblended","alphaBlended","SourceCache","onlySymbols","_onlySymbols","dataType","sourceDataType","_sourceLoaded","_paused","reload","_sourceErrored","_source","_tiles","_cache","_unloadTile","_timers","_cacheTimers","_minTileCacheSize","minTileCacheSize","_maxTileCacheSize","maxTileCacheSize","_loadedParentTiles","_coveredTiles","_state","_isRaster","_dataType","loaded","getSource","pause","resume","shouldReload","_shouldReloadOnResume","_loadTile","loadTile","unloadTile","_abortTile","abortTile","getIds","compareTileId","getRenderableIds","symbolLayer","renderables","_isIdRenderable","a_","b_","rotatedA","rotatedB","hasRenderableParent","parentTile","findLoadedParent","_reloadTile","_tileLoaded","previousState","usedForTerrain","getScaledDemTileSize","resetTileLookupCache","refreshedUponExpiration","_setTileReloadTimer","_backfillDEM","sourceCacheId","borderId","neighboringTiles","getTileByID","fillBorder","needsHillshadePrepare","needsDEMTextureUpload","backfilled","getTile","_retainLoadedChildren","idealTiles","maxCoveringZoom","retain","topmostLoadedID","parentID","minCoveringZoom","parentTileID","_getLoadedTile","reparseOverscaled","updateCacheSize","widthInTiles","heightInTiles","viewDependentMaxSize","handleWrapJump","prevLng","wrapDelta","_prevLng","updateForTerrain","idealTileIDs","getVisibleUnwrappedCoordinates","unwrapped","coveringTiles","roundZoom","isTerrainDEM","hasTile","_updateRetainedTiles","isRasterType","parentsForFading","fadingTiles","maxOverzooming","_addTile","childTile","retainedId","keysDifference","_fadeDuration","_removeTile","_updateLoadedParentTileCache","afterUpdate","releaseSymbolFadeTiles","checked","maxUnderzooming","missingTiles","childCoord","parentWasRequested","parentId","tileKey","currentId","clearTiles","_clear","tilesIn","use3DQuery","tileResults","centerX","tilesToCheck","distances","tileBoundsX","containsTile","getVisibleCoordinates","projMatrix","calculateProjMatrix","getFeatureState","reloadTilesForDependencies","_preloadTiles","waitUntilSourceLoaded","coveringTilesIDs","Map","transforms","tileIDs","updateElevation","remaining","results","asyncAll","aWrap","bWrap","DEMSampler","demTile","_demTile","_dem","_scale","_offset","useDemTile","findDEMTileFor","demTileID","FeatureIndex","featureIndexArray","Protobuf","sourceLayerCoder","vtFeatures","styleLayers","bufferedTilespaceBounds","matching","bx1","by1","bx2","by2","boxX1","boxY1","boxX2","boxY2","corner","polygonIntersectsBox","bufferedTilespaceGeometry","topDownFeatureComparator","previousIndex","featureGeometry","loadMatchingFeature","featureIndexData","filterLayerIDs","layerIDs","bucketLayerIDs","arraysIntersect","sourceLayerName","layerID","serializedLayer","evaluateProperties","intersectionZ","layerResult","lookupSymbolFeatures","symbolFeatureIndexes","symbolFeatureIndex","loadFeature","featureCache","propName","serializedProperties","styleLayerProperties","LineAtlas","nextRow","getDash","dasharray","lineCap","getDashRanges","lineAtlasWidth","oddDashArray","isDash","zeroLength","currentDashLength","dashLength","addRoundDash","halfStretch","currIndex","distLeft","distRight","minDist","signedDistance","distMiddle","distEdge","addRegularDash","capLength","localGlyphPadding","GlyphAtlas","glyphPositionMap","bitmap","WorkerTile","collectResourceTiming","returnDependencies","layerIndex","layerFamilies","anySymbolLayers","anyOtherLayers","family","recalculateLayers","iconMap","patternMap","taskMetadata","maybePrepare","glyphAtlas","DedupedRequest","entries","cb","loadVectorTile","skipParse","rawData","VectorTileWorkerSource","isSpriteLoaded","loading","requestParam","perf","workerTile","parseTile","resourceTiming","resourceTimingData","reloadTile","vtSource","reloadCallback","removeTile","RasterDEMTileWorkerSource","rawImageData","imagePixels","imgBitmap","offscreenCanvas","offscreenCanvasContext","OffscreenCanvas","imgData","rewindRings","outer","rewindRing","rewind","gj","GeoJSONWrapper","FeatureWrapper","rawGeometry","tags","fromVectorTileJs","writeLayer","writeTile","keycache","valuecache","writeFeature","writeValue","writeProperties","writeGeometry","keyIndex","valueIndex","command","zigzag","lineCount","vtPbfModule","fromGeojsonVt","ARRAY_TYPES","KDBush","magic","versionAndType","ArrayType","nodeSize","numItems","IndexArrayType","arrayTypeIndex","coordsByteSize","idsByteSize","padCoords","_pos","_finished","numAdded","r2","sqDist","select","swapItem","defaultOptions","minPoints","generateId","props","fround","OFFSET_ID","OFFSET_NUM","OFFSET_PROP","Supercluster","assign","trees","clusterProps","timerId","lngX","latY","_createTree","timeEnd","_cluster","getClusters","minLng","minLat","maxLng","easternHem","westernHem","_limitZoom","clusters","getClusterJSON","getChildren","clusterId","originId","_getOriginId","originZoom","_getOriginZoom","errorMsg","getLeaves","limit","_appendLeaves","_addTileFeatures","getClusterExpansionZoom","expansionZoom","cluster_id","skipped","point_count","isCluster","getClusterProperties","nextData","neighborIds","numPointsOrigin","numPoints","neighborId","wx","wy","clusterPropIndex","numPoints2","_map","original","yLat","abbrev","propIndex","point_count_abbreviated","simplify","sqTolerance","maxSqDist","minPosToMid","getSqSegDist","posToMid","createFeature","calcLineBBox","calcBBox","convertFeature","convertPoint","convertLine","convertLines","projectX","projectY","k2","minAll","maxAll","newGeometry","clipPoints","clipLines","newGeom","trackMetrics","segLen","newSlice","intersectX","intersectY","exited","addPoint","shiftFeatureCoords","newFeatures","shiftCoords","newPolygon","newPoints","transformTile","transformed","transformPoint","createTile","numSimplified","numFeatures","simplified","tileFeature","isOuter","GeoJSONVT","tileCoords","indexMaxZoom","indexMaxPoints","stats","total","merged","splitTile","toID","loadGeoJSONTile","_geoJSONIndex","geoJSONTile","geojsonWrapper","_feature","vtpbf","byteOffset","k3","k4","z0","GeoJSONWorkerSource","loadGeoJSON","loadData","compiled","superclusterOptions","mapExpressions","reduceExpressions","propertyNames","mapExpression","mapExpressionParsed","reduceExpressionParsed","pointProperties","getSuperclusterOptions","geojsonvt","geojsonVtOptions","getJSON","getClusterChildren","getClusterLeaves","Worker","layerIndexes","projections","defaultProjection","workerSourceTypes","workerSources","demWorkerSources","registerWorkerSource","WorkerSource","registerRTLTextPlugin","clearCaches","unused","checkIfReady","mapID","setReferrer","spriteLoaded","bool","workerSource","ws","setImages","enable","setProjection","setLayers","getLayerIndex","updateLayers","loadDEMTile","getDEMWorkerSource","removeSource","loadWorkerSource","importScripts","syncRTLPluginState","getAvailableImages","enforceCacheSizeLimit","getWorkerPerformanceMetrics"],"mappings":"6IAEAA,EAAiBC,EAEjB,SAASA,EAAWC,EAAKC,EAAKC,EAAKC,GAE/BC,KAAKC,GAAK,EAAML,EAChBI,KAAKE,GAAK,GAAOJ,EAAMF,GAAOI,KAAKC,GACnCD,KAAKG,GAAK,EAAMH,KAAKC,GAAKD,KAAKE,GAE/BF,KAAKI,GAAK,EAAMP,EAChBG,KAAKK,GAAK,GAAON,EAAMF,GAAOG,KAAKI,GACnCJ,KAAKM,GAAK,EAAMN,KAAKI,GAAKJ,KAAKK,GAE/BL,KAAKJ,IAAMA,EACXI,KAAKH,IAAMA,EACXG,KAAKF,IAAMA,EACXE,KAAKD,IAAMA,CAbyB,CAgBxCJ,EAAWY,UAAY,CACnBC,aAAc,SAAUC,GAEpB,QAAcN,KAAAA,GAAKM,EAAIT,KAAKE,IAAMO,EAAIT,KAAKC,IAAMQ,CAHlC,EAMnBC,aAAc,SAAUD,GACpB,QAAST,KAAKM,GAAKG,EAAIT,KAAKK,IAAMI,EAAIT,KAAKI,IAAMK,CAPlC,EAUnBE,uBAAwB,SAAUF,GAC9B,OAAc,EAAAT,KAAKG,GAAKM,EAAI,EAAMT,KAAKE,IAAMO,EAAIT,KAAKC,EAXvC,EAcnBW,YAAa,SAAUC,EAAGC,GAGtB,QAFgBC,IAAZD,IAAuBA,EAAU,MAEjCD,EAAI,EAAK,OAAO,EACpB,GAAIA,EAAI,EAAK,OAAO,EAKpB,IAHA,I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