{"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/web_worker_transfer.js","../src/util/throttled_invoker.js","../src/util/actor.js","../src/style-spec/error/validation_error.js","../src/style-spec/validate/validate_constants.js","../src/style-spec/util/unbundle_jsonlint.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_layer.js","../src/style-spec/validate/validate_string.js","../src/style-spec/validate/validate_source.js","../src/style-spec/validate/validate_light.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_formatted.js","../src/style-spec/validate/validate_image.js","../src/style-spec/validate/validate_glyphs_url.js","../src/style-spec/validate_style.min.js","../src/util/evented.js","../src/style/validate_style.js","../src/style/zoom_history.js","../src/util/is_char_in_unicode_block.js","../src/util/script_detection.js","../src/util/config.js","../src/util/webp_supported.js","../src/util/browser.js","../src/util/mapbox.js","../src/util/sku_token.js","../src/util/tile_request_cache.js","../src/util/ajax.js","../src/source/rtl_text_plugin.js","../src/style/evaluation_parameters.js","../src/style/properties.js","../src/style/style_layer.js","../src/util/struct_array.js","../src/data/array_types.js","../src/data/bucket/circle_attributes.js","../src/data/segment.js","../src/shaders/encode_attribute.js","../src/data/bucket/pattern_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/data/extent.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","../node_modules/gl-matrix/esm/common.js","../node_modules/gl-matrix/esm/mat4.js","../node_modules/gl-matrix/esm/vec4.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/style/style_layer/heatmap_style_layer.js","../src/util/color_ramp.js","../src/style/style_layer/hillshade_style_layer_properties.js","../src/style/style_layer/hillshade_style_layer.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/style/style_layer/fill_style_layer.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/data/bucket/fill_extrusion_bucket.js","../src/style/style_layer/fill_extrusion_style_layer_properties.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/transform_text.js","../src/util/verticalize_punctuation.js","../node_modules/ieee754/index.js","../node_modules/pbf/index.js","../node_modules/potpack/index.mjs","../src/render/image_atlas.js","../src/symbol/shaping.js","../src/style/parse_glyph_pbf.js","../src/symbol/anchor.js","../src/symbol/symbol_size.js","../src/symbol/check_max_angle.js","../src/symbol/get_anchors.js","../src/symbol/quads.js","../src/symbol/collision_feature.js","../node_modules/tinyqueue/index.js","../src/util/find_pole_of_inaccessibility.js","../src/symbol/symbol_layout.js","../src/symbol/clip_line.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/background_style_layer.js","../src/style/style_layer/raster_style_layer_properties.js","../src/style/style_layer/raster_style_layer.js","../src/style/style_layer/custom_style_layer.js","../src/style/create_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","../node_modules/@mapbox/whoots-js/index.mjs","../src/geo/lng_lat_bounds.js","../src/geo/lng_lat.js","../src/geo/mercator_coordinate.js","../src/source/tile_id.js","../src/data/feature_index.js","../src/render/glyph_atlas.js","../src/source/worker_tile.js","../src/util/performance.js","../src/source/vector_tile_worker_source.js","../src/data/dem_data.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/src/sort.js","../node_modules/kdbush/src/within.js","../node_modules/kdbush/src/index.js","../node_modules/kdbush/src/range.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":["/*\n * Copyright (C) 2008 Apple Inc. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Ported from Webkit\n * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h\n */\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 = p2y;\n this.p2x = p2x;\n this.p2y = p2y;\n}\n\nUnitBezier.prototype.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\nUnitBezier.prototype.sampleCurveY = function(t) {\n return ((this.ay * t + this.by) * t + this.cy) * t;\n};\n\nUnitBezier.prototype.sampleCurveDerivativeX = function(t) {\n return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;\n};\n\nUnitBezier.prototype.solveCurveX = function(x, epsilon) {\n if (typeof epsilon === 'undefined') epsilon = 1e-6;\n\n var t0, t1, t2, x2, i;\n\n // First try a few iterations of Newton's method -- normally very fast.\n for (t2 = x, i = 0; i < 8; i++) {\n\n x2 = this.sampleCurveX(t2) - x;\n if (Math.abs(x2) < epsilon) return t2;\n\n var d2 = this.sampleCurveDerivativeX(t2);\n if (Math.abs(d2) < 1e-6) break;\n\n t2 = t2 - x2 / d2;\n }\n\n // Fall back to the bisection method for reliability.\n t0 = 0.0;\n t1 = 1.0;\n t2 = x;\n\n if (t2 < t0) return t0;\n if (t2 > t1) return t1;\n\n while (t0 < t1) {\n\n x2 = this.sampleCurveX(t2);\n if (Math.abs(x2 - x) < epsilon) return t2;\n\n if (x > x2) {\n t0 = t2;\n } else {\n t1 = t2;\n }\n\n t2 = (t1 - t0) * 0.5 + t0;\n }\n\n // Failure.\n return t2;\n};\n\nUnitBezier.prototype.solve = function(x, epsilon) {\n return this.sampleCurveY(this.solveCurveX(x, epsilon));\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} 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|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';\n\n// shim window for the case of requiring the browser bundle in Node\nexport default typeof self !== 'undefined' ? (self: Window) : (({}: any): Window);\n","// @flow\n\nimport UnitBezier from '@mapbox/unitbezier';\n\nimport Point from '@mapbox/point-geometry';\nimport window from './window';\n\nimport type {Callback} from '../types/callback';\n\n// Number.MAX_SAFE_INTEGER not available in IE\nexport const MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;\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 * 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): (t: number) => number {\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 = 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 * 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 * 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(\n array: Array,\n fn: (item: Item, fnCallback: Callback) => void,\n callback: Callback>\n) {\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(obj: {[key: string]: T}): Array {\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(obj: {[key: string]: S}, other: {[key: string]: T}): Array {\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 {\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): 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) {\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 * 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, 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 */\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 */\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';\nexport {deepEqual};\n\n/**\n * Deeply clones two objects.\n *\n * @private\n */\nexport function clone(input: T): T {\n if (Array.isArray(input)) {\n return input.map(clone);\n } else if (typeof input === 'object' && input) {\n return ((mapObject(input, clone): any): T);\n } else {\n return input;\n }\n}\n\n/**\n * Check if two arrays have at least one common element.\n *\n * @private\n */\nexport function arraysIntersect(a: Array, b: Array): 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): 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/**\n * Detects closed polygons, first + last point are equal\n *\n * @private\n * @param points array of points\n * @return true if the points are a closed polygon\n */\nexport function isClosedPolygon(points: Array): boolean {\n // If it is 2 points that are the same then it is a point\n // If it is 3 points with start and end the same then it is a line\n if (points.length < 4)\n return false;\n\n const p1 = points[0];\n const p2 = points[points.length - 1];\n\n if (Math.abs(p1.x - p2.x) > 0 ||\n Math.abs(p1.y - p2.y) > 0) {\n return false;\n }\n\n // polygon simplification can produce polygons with zero area and more than 3 points\n return Math.abs(calculateSignedArea(points)) > 0.01;\n}\n\n/**\n * Converts spherical coordinates to cartesian coordinates.\n *\n * @private\n * @param spherical Spherical coordinates, in [radial, azimuthal, polar]\n * @return cartesian coordinates in [x, y, z]\n */\n\nexport function sphericalToCartesian([r, azimuthal, polar]: [number, number, number]): {x: number, y: number, z: number} {\n // We abstract \"north\"/\"up\" (compass-wise) to be 0° when really this is 90° (π/2):\n // correct for that here\n azimuthal += 90;\n\n // Convert azimuthal and polar angles to radians\n azimuthal *= Math.PI / 180;\n polar *= Math.PI / 180;\n\n return {\n x: r * Math.cos(azimuthal) * Math.sin(polar),\n y: r * Math.sin(azimuthal) * Math.sin(polar),\n z: r * Math.cos(polar)\n };\n}\n\n/* global self, WorkerGlobalScope */\n/**\n * Retuns true if the when 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\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 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) {\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) {\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","'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 , 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\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 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\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);\n\nexport default Color;\n","// @flow\n\nexport default function (output: any, ...inputs: Array) {\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';\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]>) {\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): boolean {\n return allowedTypes.some(t => t.kind === provided.kind);\n}\n\nexport function isValidNativeType(provided: any, allowedTypes: Array): 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\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';\nimport type ResolvedImage from '../types/resolved_image';\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 this.text = 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;\n\n constructor(sections: Array) {\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 {\n const serialized: Array = [\"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).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 {\n return [\"image\", this.name];\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport Color from '../util/color';\nimport Collator from './types/collator';\nimport Formatted from './types/formatted';\nimport ResolvedImage from './types/resolved_image';\nimport {NullType, NumberType, StringType, BooleanType, ColorType, ObjectType, ValueType, CollatorType, FormattedType, ResolvedImageType, array} from './types';\n\nimport type {Type} from './types';\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 | { +[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) {\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';\nimport Formatted from '../types/formatted';\n\nimport type {Type} from '../types';\nimport type {Value} from '../values';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\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, context: ParsingContext) {\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() {\n return this.value;\n }\n\n eachChild() {}\n\n outputDefined() {\n return true;\n }\n\n serialize(): Array {\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() {\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';\nimport RuntimeError from '../runtime_error';\nimport {typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\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;\n\n constructor(type: Type, args: Array) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray, 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;\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];\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) {\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(): Array {\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';\nimport Formatted, {FormattedSection} from '../types/formatted';\nimport {toString, typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\n\ntype 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;\n\n constructor(sections: Array) {\n this.type = FormattedType;\n this.sections = sections;\n }\n\n static parse(args: $ReadOnlyArray, 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 = [];\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) {\n const evaluateSection = section => {\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() {\n // Technically the combinatoric set of all children\n // Usually, this.text will be undefined anyway\n return false;\n }\n\n serialize() {\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';\nimport ResolvedImage from '../types/resolved_image';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\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, 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) {\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() {\n // The output of image is determined by the list of available images in the evaluation context\n return false;\n }\n\n serialize() {\n return [\"image\", this.input.serialize()];\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport {BooleanType, ColorType, NumberType, StringType, ValueType} from '../types';\nimport {Color, toString as valueToString, validateRGBA} from '../values';\nimport RuntimeError from '../runtime_error';\nimport Formatted from '../types/formatted';\nimport FormatExpression from '../definitions/format';\nimport ImageExpression from '../definitions/image';\nimport ResolvedImage from '../types/resolved_image';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\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;\n\n constructor(type: Type, args: Array) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray, 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) {\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() {\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';\nimport type {FormattedSection} from './types/formatted';\nimport type {GlobalProperties, Feature, FeatureState} from './index';\nimport type {CanonicalTileID} from '../../source/tile_id';\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;\n canonical: ?CanonicalTileID;\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 }\n\n id() {\n return this.feature && 'id' in this.feature ? this.feature.id : null;\n }\n\n geometryType() {\n return this.feature ? typeof this.feature.type === 'number' ? geometryTypes[this.feature.type] : this.feature.type : null;\n }\n\n geometry() {\n return this.feature && 'geometry' in this.feature ? this.feature.geometry : null;\n }\n\n canonicalID() {\n return this.canonical;\n }\n\n properties() {\n return this.feature && this.feature.properties || {};\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';\n\nimport ParsingContext from './parsing_context';\nimport EvaluationContext from './evaluation_context';\nimport assert from 'assert';\n\nimport type {Expression, ExpressionRegistry} from './expression';\nimport type {Type} from './types';\nimport type {Value} from './values';\n\nexport type Varargs = {| type: Type |};\ntype Signature = Array | Varargs;\ntype Evaluate = (EvaluationContext, Array) => 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;\n\n static definitions: {[_: string]: Definition };\n\n constructor(name: string, type: Type, evaluate: Evaluate, args: Array) {\n this.name = name;\n this.type = type;\n this._evaluate = evaluate;\n this.args = args;\n }\n\n evaluate(ctx: EvaluationContext) {\n return this._evaluate(ctx, this.args);\n }\n\n eachChild(fn: (_: Expression) => void) {\n this.args.forEach(fn);\n }\n\n outputDefined() {\n return false;\n }\n\n serialize(): Array {\n return [this.name].concat(this.args.map(arg => arg.serialize()));\n }\n\n static parse(args: $ReadOnlyArray, 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 = [];\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 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';\nimport Collator from '../types/collator';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\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, 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) {\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() {\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() {\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';\nimport type {Type} from '../types';\nimport {BooleanType} from '../types';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {GeoJSON, GeoJSONPolygon, GeoJSONMultiPolygon} from '@mapbox/geojson-types';\nimport Point from '@mapbox/point-geometry';\nimport type {CanonicalTileID} from '../../../source/tile_id';\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: Point) {\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, 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, p1, p2) {\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, p1, p2) {\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, rings) {\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, polygons) {\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, v2) {\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, p2, q1, q2) {\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, b, c, d) {\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, p2, polygon) {\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, polygon) {\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, polygons) {\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, bbox, canonical) {\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, bbox, canonical) {\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, bbox, polyBBox, worldSize) {\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) {\n bbox[0] = bbox[1] = Infinity;\n bbox[2] = bbox[3] = -Infinity;\n}\n\nfunction getTilePoints(geometry, pointBBox, polyBBox, canonical) {\n const worldSize = Math.pow(2, canonical.z) * EXTENT;\n const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];\n const 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, lineBBox, polyBBox, canonical) {\n const worldSize = Math.pow(2, canonical.z) * EXTENT;\n const shifts = [canonical.x * EXTENT, canonical.y * EXTENT];\n const tileLines = [];\n for (const line of geometry) {\n const tileLine = [];\n for (const point of line) {\n const p = [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\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\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, context: ParsingContext) {\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) {\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(): Array {\n return [\"within\", this.geojson];\n }\n\n}\n\nexport default Within;\n","// @flow\n\nimport CompoundExpression from './compound_expression';\nimport Within from './definitions/within';\nimport type {Expression} from './expression.js';\n\nfunction isFeatureConstant(e: Expression) {\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) {\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) {\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';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\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, context: ParsingContext) {\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) {\n return this.boundExpression.evaluate(ctx);\n }\n\n eachChild() {}\n\n outputDefined() {\n return false;\n }\n\n serialize() {\n return [\"var\", this.name];\n }\n}\n\nexport default Var;\n","// @flow\n\nimport Scope from './scope';\nimport {checkSubtype} from './types';\nimport ParsingError from './parsing_error';\nimport Literal from './definitions/literal';\nimport Assertion from './definitions/assertion';\nimport Coercion from './definitions/coercion';\nimport EvaluationContext from './evaluation_context';\nimport CompoundExpression from './compound_expression';\nimport CollatorExpression from './definitions/collator';\nimport Within from './definitions/within';\nimport {isGlobalPropertyConstant, isFeatureConstant} from './is_constant';\nimport Var from './definitions/var';\n\nimport type {Expression, ExpressionRegistry} from './expression';\nimport type {Type} from './types';\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;\n key: string;\n scope: Scope;\n errors: Array;\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 = [],\n expectedType: ?Type,\n scope: Scope = new Scope(),\n errors: Array = []\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, 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]>) {\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) {\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', 'accumulated', 'is-supported-script']);\n}\n","// @flow\n\nimport RuntimeError from './runtime_error';\n\nimport type {Expression} from './expression';\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, input: 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';\n\nimport {findStopLessThanOrEqualTo} from '../stops';\n\nimport type {Stops} from '../stops';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nclass Step implements Expression {\n type: Type;\n\n input: Expression;\n labels: Array;\n outputs: Array;\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, context: ParsingContext) {\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) {\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() {\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';\n\nexport function number(a: number, b: number, t: number) {\n return (a * (1 - t)) + (b * t);\n}\n\nexport function color(from: Color, to: Color, t: number) {\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, to: Array, t: number): Array {\n return from.map((d, i) => {\n return number(d, to[i], t);\n });\n}\n","// @flow\n\nimport Color from './color';\n\nimport {number as interpolateNumber} from './interpolate';\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) {\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) {\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';\nimport {toString, NumberType, ColorType} from '../types';\nimport {findStopLessThanOrEqualTo} from '../stops';\nimport {hcl, lab} from '../../util/color_spaces';\n\nimport type {Stops} from '../stops';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\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;\n outputs: Array;\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) {\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, context: ParsingContext) {\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) {\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(): Array {\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, 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\nexport default Interpolate;\n","// @flow\n\nimport assert from 'assert';\n\nimport {checkSubtype, ValueType} from '../types';\nimport ResolvedImage from '../types/resolved_image';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\n\nclass Coalesce implements Expression {\n type: Type;\n args: Array;\n\n constructor(type: Type, args: Array) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray, context: ParsingContext) {\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) {\n let result = null;\n let argCount = 0;\n let requestedImageName;\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 name so styleimagemissing can fire\n if (result && result instanceof ResolvedImage && !result.available) {\n if (!requestedImageName) {\n requestedImageName = result.name;\n }\n result = null;\n if (argCount === this.args.length) {\n result = requestedImageName;\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() {\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';\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\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) {\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, context: ParsingContext) {\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() {\n return this.result.outputDefined();\n }\n\n serialize() {\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';\n\nimport RuntimeError from '../runtime_error';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type, ArrayType} from '../types';\nimport type {Value} from '../values';\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, context: ParsingContext) {\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) {\n const index = ((this.index.evaluate(ctx): any): number);\n const array = ((this.input.evaluate(ctx): any): Array);\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() {\n return false;\n }\n\n serialize() {\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';\nimport RuntimeError from '../runtime_error';\nimport {typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\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, context: ParsingContext) {\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) {\n const needle = (this.needle.evaluate(ctx): any);\n const haystack = (this.haystack.evaluate(ctx): any);\n\n if (!haystack) 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() {\n return true;\n }\n\n serialize() {\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';\nimport RuntimeError from '../runtime_error';\nimport {typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\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, context: ParsingContext) {\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) {\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() {\n return false;\n }\n\n serialize() {\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';\nimport {ValueType, type Type} from '../types';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\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;\n otherwise: Expression;\n\n constructor(inputType: Type, outputType: Type, input: Expression, cases: Cases, outputs: Array, 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, context: ParsingContext) {\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;\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) {\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(): Array {\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]> = [];\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) => 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';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\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, context: ParsingContext) {\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) {\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() {\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';\nimport RuntimeError from '../runtime_error';\nimport {typeOf} from '../values';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\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, context: ParsingContext) {\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) {\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() {\n return false;\n }\n\n serialize() {\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';\nimport Assertion from './assertion';\nimport {typeOf} from '../values';\nimport RuntimeError from '../runtime_error';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\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, a, b) { return a === b; }\nfunction neq(ctx, a, b) { return a !== b; }\nfunction lt(ctx, a, b) { return a < b; }\nfunction gt(ctx, a, b) { return a > b; }\nfunction lteq(ctx, a, b) { return a <= b; }\nfunction gteq(ctx, a, b) { return a >= b; }\n\nfunction eqCollate(ctx, a, b, c) { return c.compare(a, b) === 0; }\nfunction neqCollate(ctx, a, b, c) { return !eqCollate(ctx, a, b, c); }\nfunction ltCollate(ctx, a, b, c) { return c.compare(a, b) < 0; }\nfunction gtCollate(ctx, a, b, c) { return c.compare(a, b) > 0; }\nfunction lteqCollate(ctx, a, b, c) { return c.compare(a, b) <= 0; }\nfunction gteqCollate(ctx, a, b, c) { 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, compareWithCollator) {\n const isOrderComparison = op !== '==' && op !== '!=';\n\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 static parse(args: $ReadOnlyArray, 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) {\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() {\n const serialized = [op];\n this.eachChild(child => { serialized.push(child.serialize()); });\n return serialized;\n }\n };\n}\n\nexport const Equals = makeComparison('==', eq, eqCollate);\nexport const NotEquals = makeComparison('!=', neq, neqCollate);\nexport const LessThan = makeComparison('<', lt, ltCollate);\nexport const GreaterThan = makeComparison('>', gt, gtCollate);\nexport const LessThanOrEqual = makeComparison('<=', lteq, lteqCollate);\nexport const GreaterThanOrEqual = makeComparison('>=', gteq, gteqCollate);\n","// @flow\n\nimport {StringType, NumberType} from '../types';\n\nimport type {Expression} from '../expression';\nimport type EvaluationContext from '../evaluation_context';\nimport type ParsingContext from '../parsing_context';\nimport type {Type} from '../types';\n\ndeclare var Intl: {\n NumberFormat: Class\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';\n currency?: 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 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 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.minFractionDigits = minFractionDigits;\n this.maxFractionDigits = maxFractionDigits;\n }\n\n static parse(args: $ReadOnlyArray, 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 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, minFractionDigits, maxFractionDigits);\n }\n\n evaluate(ctx: EvaluationContext) {\n return new Intl.NumberFormat(this.locale ? this.locale.evaluate(ctx) : [],\n {\n style: this.currency ? \"currency\" : \"decimal\",\n currency: this.currency ? this.currency.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.minFractionDigits) {\n fn(this.minFractionDigits);\n }\n if (this.maxFractionDigits) {\n fn(this.maxFractionDigits);\n }\n }\n\n outputDefined() {\n return false;\n }\n\n serialize() {\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.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';\n\nimport {typeOf} from '../values';\nimport RuntimeError from '../runtime_error';\n\nimport type {Expression} from '../expression';\nimport type ParsingContext from '../parsing_context';\nimport type EvaluationContext from '../evaluation_context';\nimport type {Type} from '../types';\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, context: ParsingContext) {\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) {\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() {\n return false;\n }\n\n serialize() {\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';\n\nimport {typeOf, Color, validateRGBA, toString as valueToString} from '../values';\nimport CompoundExpression from '../compound_expression';\nimport RuntimeError from '../runtime_error';\nimport Let from './let';\nimport Var from './var';\nimport Literal from './literal';\nimport Assertion from './assertion';\nimport Coercion from './coercion';\nimport At from './at';\nimport In from './in';\nimport IndexOf from './index_of';\nimport Match from './match';\nimport Case from './case';\nimport Slice from './slice';\nimport Step from './step';\nimport Interpolate from './interpolate';\nimport Coalesce from './coalesce';\nimport {\n Equals,\n NotEquals,\n LessThan,\n GreaterThan,\n LessThanOrEqual,\n GreaterThanOrEqual\n} from './comparison';\nimport CollatorExpression from './collator';\nimport NumberFormat from './number_format';\nimport FormatExpression from './format';\nimport ImageExpression from './image';\nimport Length from './length';\nimport Within from './within';\n\nimport type {Varargs} from '../compound_expression';\nimport type {ExpressionRegistry} from '../expression';\n\nconst expressions: ExpressionRegistry = {\n // special forms\n '==': Equals,\n '!=': NotEquals,\n '>': GreaterThan,\n '<': LessThan,\n '>=': GreaterThanOrEqual,\n '<=': LessThanOrEqual,\n 'array': Assertion,\n 'at': At,\n 'boolean': Assertion,\n 'case': Case,\n 'coalesce': Coalesce,\n 'collator': CollatorExpression,\n 'format': FormatExpression,\n 'image': ImageExpression,\n 'in': In,\n 'index-of': IndexOf,\n 'interpolate': Interpolate,\n 'interpolate-hcl': Interpolate,\n 'interpolate-lab': Interpolate,\n 'length': Length,\n 'let': Let,\n 'literal': Literal,\n 'match': Match,\n 'number': Assertion,\n 'number-format': NumberFormat,\n 'object': Assertion,\n 'slice': Slice,\n 'step': Step,\n 'string': Assertion,\n 'to-boolean': Coercion,\n 'to-color': Coercion,\n 'to-number': Coercion,\n 'to-string': Coercion,\n 'var': Var,\n 'within': Within\n};\n\nfunction rgba(ctx, [r, g, b, a]) {\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, obj) {\n return key in obj;\n}\n\nfunction get(key, obj) {\n const v = obj[key];\n return typeof v === 'undefined' ? null : v;\n}\n\nfunction binarySearch(v, a, i, j) {\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 '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 '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 =\n | {| result: 'success', value: T |}\n | {| result: 'error', value: E |};\n\nexport function success(value: T): Result {\n return {result: 'success', value};\n}\n\nexport function error(value: E): Result {\n return {result: 'error', value};\n}\n","// @flow\n\nimport type {StylePropertySpecification} from '../style-spec';\n\nexport function supportsPropertyExpression(spec: StylePropertySpecification): boolean {\n return spec['property-type'] === 'data-driven' || spec['property-type'] === 'cross-faded-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';\nimport Color from '../util/color';\nimport extend from '../util/extend';\nimport getType from '../util/get_type';\nimport * as interpolate from '../util/interpolate';\nimport Interpolate from '../expression/definitions/interpolate';\nimport Formatted from '../expression/types/formatted';\nimport ResolvedImage from '../expression/types/resolved_image';\nimport {supportsInterpolation} from '../util/properties';\nimport {findStopLessThanOrEqualTo} from '../expression/stops';\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';\nimport ParsingError from './parsing_error';\nimport ParsingContext from './parsing_context';\nimport EvaluationContext from './evaluation_context';\nimport CompoundExpression from './compound_expression';\nimport Step from './definitions/step';\nimport Interpolate from './definitions/interpolate';\nimport Coalesce from './definitions/coalesce';\nimport Let from './definitions/let';\nimport definitions from './definitions';\nimport * as isConstant from './is_constant';\nimport RuntimeError from './runtime_error';\nimport {success, error} from '../util/result';\nimport {supportsPropertyExpression, supportsZoomExpression, supportsInterpolation} from '../util/properties';\n\nimport type {Type, EvaluationKind} from './types';\nimport type {Value} from './values';\nimport type {Expression} from './expression';\nimport type {StylePropertySpecification} from '../style-spec';\nimport type {Result} from '../util/result';\nimport type {InterpolationType} from './definitions/interpolate';\nimport type {PropertyValueSpecification} from '../types';\nimport type {FormattedSection} from './types/formatted';\nimport type Point from '@mapbox/point-geometry';\nimport type {CanonicalTileID} from '../../source/tile_id';\n\nexport type Feature = {\n +type: 1 | 2 | 3 | 'Unknown' | 'Point' | 'MultiPoint' | 'LineString' | 'MultiLineString' | 'Polygon' | 'MultiPolygon',\n +id?: any,\n +properties: {[_: string]: any},\n +patterns?: {[_: string]: {\"min\": string, \"mid\": string, \"max\": string}},\n +geometry?: Array>\n};\n\nexport type FeatureState = {[_: string]: any};\n\nexport type GlobalProperties = $ReadOnly<{\n zoom: number,\n heatmapDensity?: number,\n lineProgress?: 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, formattedSection?: FormattedSection): any {\n this._evaluator.globals = globals;\n this._evaluator.feature = feature;\n this._evaluator.featureState = featureState;\n this._evaluator.canonical = canonical;\n this._evaluator.availableImages = availableImages || null;\n this._evaluator.formattedSection = formattedSection;\n\n return this.expression.evaluate(this._evaluator);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection): any {\n this._evaluator.globals = globals;\n this._evaluator.feature = feature || null;\n this._evaluator.featureState = featureState || null;\n this._evaluator.canonical = canonical;\n this._evaluator.availableImages = availableImages || null;\n this._evaluator.formattedSection = formattedSection || 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) {\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> {\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 {\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, 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, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n}\n\nexport class ZoomDependentExpression {\n kind: Kind;\n zoomStops: Array;\n isStateDependent: boolean;\n\n _styleExpression: StyleExpression;\n interpolationType: ?InterpolationType;\n\n constructor(kind: Kind, expression: StyleExpression, zoomStops: Array, 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, 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, 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 = {\n kind: 'constant',\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array) => any,\n}\n\nexport type SourceExpression = {\n kind: 'source',\n isStateDependent: boolean,\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection) => any,\n};\n\nexport type CameraExpression = {\n kind: 'camera',\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array) => any,\n +interpolationFactor: (input: number, lower: number, upper: number) => number,\n zoomStops: Array,\n interpolationType: ?InterpolationType\n};\n\nexport type CompositeExpression = {\n kind: 'composite',\n isStateDependent: boolean,\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array, formattedSection?: FormattedSection) => any,\n +interpolationFactor: (input: number, lower: number, upper: number) => number,\n zoomStops: Array,\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> {\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']);\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 (new ZoomConstantExpression('constant', expression.value): ConstantExpression) :\n (new ZoomConstantExpression('source', expression.value): SourceExpression));\n }\n\n const interpolationType = zoomCurve instanceof Interpolate ? zoomCurve.interpolation : undefined;\n\n return success(isFeatureConstant ?\n (new ZoomDependentExpression('camera', expression.value, zoomCurve.labels, interpolationType): CameraExpression) :\n (new ZoomDependentExpression('composite', expression.value, zoomCurve.labels, interpolationType): CompositeExpression));\n}\n\nimport {isFunction, createFunction} from '../function';\nimport {Color} from './values';\n\n// serialization wrapper for old-style stop functions normalized to the\n// expression interface\nexport class StylePropertyFunction {\n _parameters: PropertyValueSpecification;\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;\n\n constructor(parameters: PropertyValueSpecification, 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, _specification: StylePropertySpecification}) {\n return ((new StylePropertyFunction(serialized._parameters, serialized._specification)): StylePropertyFunction);\n }\n\n static serialize(input: StylePropertyFunction) {\n return {\n _parameters: input._parameters,\n _specification: input._specification\n };\n }\n}\n\nexport function normalizePropertyExpression(value: PropertyValueSpecification, 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';\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)) {\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\n\nimport assert from 'assert';\n\nimport Grid from 'grid-index';\nimport Color from '../style-spec/util/color';\nimport {StylePropertyFunction, StyleExpression, ZoomDependentExpression, ZoomConstantExpression} from '../style-spec/expression';\nimport CompoundExpression from '../style-spec/expression/compound_expression';\nimport expressions from '../style-spec/expression/definitions';\nimport ResolvedImage from '../style-spec/expression/types/resolved_image';\nimport window from './window';\nconst {ImageData, ImageBitmap} = window;\n\nimport type {Transferable} from '../types/transferable';\n\ntype SerializedObject = {[_: string]: Serialized }; // eslint-disable-line\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\n | SerializedObject;\n\ntype Registry = {\n [_: string]: {\n klass: Class,\n omit: $ReadOnlyArray,\n shallow: $ReadOnlyArray\n }\n};\n\ntype RegisterOptions = {\n omit?: $ReadOnlyArray<$Keys>,\n shallow?: $ReadOnlyArray<$Keys>\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 * @param options.shallow List of properties that should be serialized by a simple shallow copy, rather than by a recursive call to serialize().\n *\n * @private\n */\nexport function register(name: string, klass: Class, options: RegisterOptions = {}) {\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 shallow: options.shallow || []\n };\n}\n\nregister('Object', Object);\n\ntype SerializedGrid = { buffer: ArrayBuffer };\n\nGrid.serialize = function serialize(grid: Grid, transferables?: Array): SerializedGrid {\n const buffer = grid.toArrayBuffer();\n if (transferables) {\n transferables.push(buffer);\n }\n return {buffer};\n};\n\nGrid.deserialize = function deserialize(serialized: SerializedGrid): Grid {\n return new Grid(serialized.buffer);\n};\nregister('Grid', Grid);\n\nregister('Color', Color);\nregister('Error', Error);\nregister('ResolvedImage', ResolvedImage);\n\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 ((expressions[name]: any)._classRegistryKey) continue;\n register(`Expression_${name}`, expressions[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 ImageBitmap &&\n val instanceof 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): 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;\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 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 = [];\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`);\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] = registry[name].shallow.indexOf(key) >= 0 ?\n property :\n 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 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 = Object.create(klass.prototype);\n\n for (const key of Object.keys(input)) {\n if (key === '$name') continue;\n const value = (input: SerializedObject)[key];\n result[key] = registry[name].shallow.indexOf(key) >= 0 ? value : 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 delete this._channel;\n this._callback = () => {};\n }\n}\n\nexport default ThrottledInvoker;\n","// @flow\n\nimport {bindAll, isWorker, isSafari} from './util';\nimport window from './window';\nimport {serialize, deserialize} from './web_worker_transfer';\nimport ThrottledInvoker from './throttled_invoker';\n\nimport type {Transferable} from '../types/transferable';\nimport type {Cancelable} from '../types/cancelable';\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 tasks: { number: any };\n taskQueue: Array;\n cancelCallbacks: { number: Cancelable };\n invoker: ThrottledInvoker;\n globalScope: any;\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.tasks = {};\n this.taskQueue = [];\n this.cancelCallbacks = {};\n bindAll(['receive', 'process'], this);\n this.invoker = new ThrottledInvoker(this.process);\n this.target.addEventListener('message', this.receive, false);\n this.globalScope = isWorker() ? target : window;\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): ?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 this.callbacks[id] = callback;\n }\n const buffers: ?Array = 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: '',\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 === '') {\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 delete this.tasks[id];\n const cancel = this.cancelCallbacks[id];\n delete this.cancelCallbacks[id];\n if (cancel) {\n cancel();\n }\n } else {\n if (isWorker() || data.mustQueue) {\n // In workers, store the tasks that we need to process before actually processing them. This\n // is necessary because we want to keep receiving messages, and in particular,\n // messages. Some tasks may take a while in the worker thread, so before\n // executing the next task in our queue, postMessage preempts this and \n // messages can be processed. We're using a MessageChannel object to get throttle the\n // process() flow to one at a time.\n this.tasks[id] = data;\n this.taskQueue.push(id);\n this.invoker.trigger();\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 process() {\n if (!this.taskQueue.length) {\n return;\n }\n const id = this.taskQueue.shift();\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 this.processTask(id, task);\n }\n\n processTask(id: number, task: any) {\n if (task.type === '') {\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 let completed = false;\n const buffers: ?Array = isSafari(this.globalScope) ? undefined : [];\n const done = task.hasCallback ? (err, data) => {\n completed = true;\n delete this.cancelCallbacks[id];\n this.target.postMessage({\n id,\n type: '',\n sourceMapId: this.mapId,\n error: err ? serialize(err) : null,\n data: serialize(data, buffers)\n }, buffers);\n } : (_) => {\n completed = true;\n };\n\n let callback = null;\n const params = (deserialize(task.data): any);\n if (this.parent[task.type]) {\n // task.type == 'loadTile', 'removeTile', etc.\n callback = 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 callback = 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 if (!completed && callback && callback.cancel) {\n // Allows canceling the task as long as it hasn't been completed yet.\n this.cancelCallbacks[id] = callback.cancel;\n }\n }\n }\n\n remove() {\n this.invoker.remove();\n this.target.removeEventListener('message', this.receive, false);\n }\n}\n\nexport default Actor;\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","\nimport ValidationError from '../error/validation_error';\n\nexport default function validateConstants(options) {\n const key = options.key;\n const constants = options.value;\n\n if (constants) {\n return [new ValidationError(key, constants, 'constants have been deprecated as of v8')];\n } else {\n return [];\n }\n}\n","// @flow\n\n// Turn jsonlint-lines-primitives objects into primitive objects\nexport function unbundle(value: 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","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport validateSpec from './validate';\n\nexport default function validateObject(options) {\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 } else {\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 }, 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","\nimport getType from '../util/get_type';\nimport validate from './validate';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateArray(options) {\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 };\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","\nimport getType from '../util/get_type';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateNumber(options) {\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 && value < valueSpec.minimum) {\n return [new ValidationError(key, value, `${value} is less than the minimum value ${valueSpec.minimum}`)];\n }\n\n if ('maximum' in valueSpec && value > valueSpec.maximum) {\n return [new ValidationError(key, value, `${value} is greater than the maximum value ${valueSpec.maximum}`)];\n }\n\n return [];\n}\n","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport validate from './validate';\nimport validateObject from './validate_object';\nimport validateArray from './validate_array';\nimport validateNumber from './validate_number';\nimport {isExpression} from '../expression';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint';\nimport {\n supportsPropertyExpression,\n supportsZoomExpression,\n supportsInterpolation\n} from '../util/properties';\n\nexport default function validateFunction(options) {\n const functionValueSpec = options.valueSpec;\n const functionType = unbundle(options.value.type);\n let stopKeyType;\n let stopDomainValues = {};\n let previousStopDomainValue;\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) {\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) {\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 if (previousStopDomainZoom && previousStopDomainZoom > unbundle(value[0].zoom)) {\n return [new ValidationError(key, value[0].zoom, 'stop zoom values must appear in ascending order')];\n }\n if (unbundle(value[0].zoom) !== previousStopDomainZoom) {\n previousStopDomainZoom = unbundle(value[0].zoom);\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, stop) {\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') {\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' && (!isFinite(value) || Math.floor(value) !== value)) {\n return [new ValidationError(options.key, reportValue, `integer expected, found ${value}`)];\n }\n\n if (functionType !== 'categorical' && type === '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 in stopDomainValues) {\n return [new ValidationError(options.key, reportValue, 'stop domain values must be unique')];\n } else {\n stopDomainValues[value] = true;\n }\n\n return [];\n }\n\n function validateFunctionDefault(options) {\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';\n\nimport {createExpression, createPropertyExpression} from '../expression';\nimport {deepUnbundle} from '../util/unbundle_jsonlint';\nimport {isStateConstant, isGlobalPropertyConstant, isFeatureConstant} from '../expression/is_constant';\n\nexport default function validateExpression(options: any): Array {\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' && !isStateConstant(expressionObj)) {\n return [new ValidationError(options.key, options.value, '\"feature-state\" data expressions are not supported with filters.')];\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","\nimport ValidationError from '../error/validation_error';\nimport {unbundle} from '../util/unbundle_jsonlint';\n\nexport default function validateEnum(options) {\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';\nimport type {GlobalProperties, Feature} from '../expression';\nimport type {CanonicalTileID} from '../../source/tile_id';\n\ntype FilterExpression = (globalProperties: GlobalProperties, feature: Feature, canonical?: CanonicalTileID) => boolean;\nexport type FeatureFilter ={filter: FilterExpression, needGeometry: boolean};\n\nexport default createFilter;\nexport {isExpressionFilter};\n\nfunction isExpressionFilter(filter: any) {\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\nconst filterSpec = {\n 'type': 'boolean',\n 'default': false,\n 'transition': false,\n 'property-type': 'data-driven',\n 'expression': {\n 'interpolated': false,\n 'parameters': ['zoom', 'feature']\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 * @returns {Function} filter-evaluating function\n */\nfunction createFilter(filter: any): FeatureFilter {\n if (filter === null || filter === undefined) {\n return {filter: () => true, needGeometry: false};\n }\n\n if (!isExpressionFilter(filter)) {\n filter = convertFilter(filter);\n }\n\n const compiled = createExpression(filter, filterSpec);\n if (compiled.result === 'error') {\n throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', '));\n } else {\n const needGeometry = geometryNeeded(filter);\n return {filter: (globalProperties: GlobalProperties, feature: Feature, canonical?: CanonicalTileID) => compiled.value.evaluate(globalProperties, feature, {}, canonical),\n needGeometry};\n }\n}\n\n// Comparison function to sort numbers and strings\nfunction compare(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n\nfunction geometryNeeded(filter) {\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): 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>) {\n return ['any'].concat(filters.map(convertFilter));\n}\n\nfunction convertInOp(property: string, values: Array) {\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","\nimport ValidationError from '../error/validation_error';\nimport validateExpression from './validate_expression';\nimport validateEnum from './validate_enum';\nimport getType from '../util/get_type';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint';\nimport extend from '../util/extend';\nimport {isExpressionFilter} from '../feature_filter';\n\nexport default function validateFilter(options) {\n if (isExpressionFilter(deepUnbundle(options.value))) {\n return validateExpression(extend({}, options, {\n expressionContext: 'filter',\n valueSpec: {value: 'boolean'}\n }));\n } else {\n return validateNonExpressionFilter(options);\n }\n}\n\nfunction validateNonExpressionFilter(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 }));\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","\nimport validate from './validate';\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport {isFunction} from '../function';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint';\nimport {supportsPropertyExpression} from '../util/properties';\n\nexport default function validateProperty(options, propertyType) {\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;\n if (getType(value) === 'string' && supportsPropertyExpression(valueSpec) && !valueSpec.tokens && (tokenMatch = /^{([^}]+)}$/.exec(value))) {\n return [new ValidationError(\n key, value,\n `\"${propertyKey}\" does not support interpolation syntax\\n` +\n `Use an identity property function instead: \\`{ \"type\": \"identity\", \"property\": ${JSON.stringify(tokenMatch[1])} }\\`.`)];\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","\nimport validateProperty from './validate_property';\n\nexport default function validatePaintProperty(options) {\n return validateProperty(options, 'paint');\n}\n","\nimport validateProperty from './validate_property';\n\nexport default function validateLayoutProperty(options) {\n return validateProperty(options, 'layout');\n}\n","\nimport ValidationError from '../error/validation_error';\nimport {unbundle} from '../util/unbundle_jsonlint';\nimport validateObject from './validate_object';\nimport validateFilter from './validate_filter';\nimport validatePaintProperty from './validate_paint_property';\nimport validateLayoutProperty from './validate_layout_property';\nimport validateSpec from './validate';\nimport extend from '../util/extend';\n\nexport default function validateLayer(options) {\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 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 errors.push(new ValidationError(key, layer.ref, `ref layer \"${ref}\" not found`));\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') {\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'] &&\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: validateFilter,\n layout(options) {\n return validateObject({\n layer,\n key: options.key,\n value: options.value,\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 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","\nimport getType from '../util/get_type';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateString(options) {\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","\nimport ValidationError from '../error/validation_error';\nimport {unbundle} from '../util/unbundle_jsonlint';\nimport validateObject from './validate_object';\nimport validateEnum from './validate_enum';\nimport validateExpression from './validate_expression';\nimport validateString from './validate_string';\nimport getType from '../util/get_type';\n\nconst objectElementValidators = {\n promoteId: validatePromoteId\n};\n\nexport default function validateSource(options) {\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: ['vector', 'raster', 'raster-dem', 'geojson', 'video', 'image']},\n style,\n styleSpec\n });\n }\n}\n\nfunction validatePromoteId({key, value}) {\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","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport validate from './validate';\n\nexport default function validateLight(options) {\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","\nimport extend from '../util/extend';\nimport {unbundle, deepUnbundle} from '../util/unbundle_jsonlint';\nimport {isExpression} from '../expression';\nimport {isFunction} from '../function';\n\nimport validateFunction from './validate_function';\nimport validateExpression from './validate_expression';\nimport validateObject from './validate_object';\nimport validateArray from './validate_array';\nimport validateBoolean from './validate_boolean';\nimport validateNumber from './validate_number';\nimport validateColor from './validate_color';\nimport validateConstants from './validate_constants';\nimport validateEnum from './validate_enum';\nimport validateFilter from './validate_filter';\nimport validateLayer from './validate_layer';\nimport validateSource from './validate_source';\nimport validateLight from './validate_light';\nimport validateString from './validate_string';\nimport validateFormatted from './validate_formatted';\nimport validateImage from './validate_image';\n\nconst VALIDATORS = {\n '*'() {\n return [];\n },\n 'array': validateArray,\n 'boolean': validateBoolean,\n 'number': validateNumber,\n 'color': validateColor,\n 'constants': validateConstants,\n 'enum': validateEnum,\n 'filter': validateFilter,\n 'function': validateFunction,\n 'layer': validateLayer,\n 'object': validateObject,\n 'source': validateSource,\n 'light': validateLight,\n 'string': validateString,\n 'formatted': validateFormatted,\n 'resolvedImage': validateImage\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.\n\nexport default function validate(options) {\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","\nimport getType from '../util/get_type';\nimport ValidationError from '../error/validation_error';\n\nexport default function validateBoolean(options) {\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","\nimport ValidationError from '../error/validation_error';\nimport getType from '../util/get_type';\nimport {parseCSSColor} from 'csscolorparser';\n\nexport default function validateColor(options) {\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\nimport validateExpression from './validate_expression';\nimport validateString from './validate_string';\n\nexport default function validateFormatted(options: any) {\n if (validateString(options).length === 0) {\n return [];\n }\n\n return validateExpression(options);\n}\n","// @flow\nimport validateExpression from './validate_expression';\nimport validateString from './validate_string';\n\nexport default function validateImage(options: any) {\n if (validateString(options).length === 0) {\n return [];\n }\n\n return validateExpression(options);\n}\n","\nimport ValidationError from '../error/validation_error';\nimport validateString from './validate_string';\n\nexport default function(options) {\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","\nimport validateConstants from './validate/validate_constants';\nimport validate from './validate/validate';\nimport latestStyleSpec from './reference/latest';\nimport validateGlyphsURL from './validate/validate_glyphs_url';\n\nimport validateSource from './validate/validate_source';\nimport validateLight from './validate/validate_light';\nimport validateLayer from './validate/validate_layer';\nimport validateFilter from './validate/validate_filter';\nimport validatePaintProperty from './validate/validate_paint_property';\nimport validateLayoutProperty from './validate/validate_layout_property';\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}\n * @example\n * var validate = require('mapbox-gl-style-spec/lib/validate_style.min');\n * var errors = validate(style);\n */\nfunction validateStyleMin(style, styleSpec = latestStyleSpec) {\n\n let errors = [];\n\n errors = errors.concat(validate({\n key: '',\n value: style,\n valueSpec: styleSpec.$root,\n styleSpec,\n style,\n objectElementValidators: {\n glyphs: validateGlyphsURL,\n '*'() {\n return [];\n }\n }\n }));\n\n if (style.constants) {\n errors = errors.concat(validateConstants({\n key: 'constants',\n value: style.constants,\n style,\n styleSpec\n }));\n }\n\n return sortErrors(errors);\n}\n\nvalidateStyleMin.source = wrapCleanErrors(validateSource);\nvalidateStyleMin.light = wrapCleanErrors(validateLight);\nvalidateStyleMin.layer = wrapCleanErrors(validateLayer);\nvalidateStyleMin.filter = wrapCleanErrors(validateFilter);\nvalidateStyleMin.paintProperty = wrapCleanErrors(validatePaintProperty);\nvalidateStyleMin.layoutProperty = wrapCleanErrors(validateLayoutProperty);\n\nfunction sortErrors(errors) {\n return [].concat(errors).sort((a, b) => {\n return a.line - b.line;\n });\n}\n\nfunction wrapCleanErrors(inner) {\n return function(...args) {\n return sortErrors(inner.apply(this, args));\n };\n}\n\nexport default validateStyleMin;\n","// @flow\n\nimport {extend} from './util';\n\ntype Listener = (Object) => any;\ntype Listeners = {[_: string]: Array };\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 * Methods mixed in to other classes for event capabilities.\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} `this`\n */\n on(type: *, 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} `this`\n */\n off(type: *, listener: Listener) {\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 The function to be called when the event is fired the first time.\n * @returns {Object} `this`\n */\n once(type: *, listener: Listener) {\n this._oneTimeListeners = this._oneTimeListeners || {};\n _addEventListener(type, listener, this._oneTimeListeners);\n\n return this;\n }\n\n fire(event: Event, properties?: Object) {\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 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 a true if this instance of Evented or any forwardeed instances of Evented have a listener for the specified type.\n *\n * @param {string} type The event type\n * @returns {boolean} `true` if there is at least one registered listener for specified event type, `false` otherwise\n * @private\n */\n listens(type: string) {\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 * @private\n * @returns {Object} `this`\n * @private\n */\n setEventedParent(parent: ?Evented, data?: Object | () => Object) {\n this._eventedParent = parent;\n this._eventedParentData = data;\n\n return this;\n }\n}\n","// @flow\nimport validateStyleMin from '../style-spec/validate_style.min';\nimport {ErrorEvent} from '../util/evented';\n\nimport type {Evented} from '../util/evented';\n\ntype ValidationError = {\n message: string,\n line: number,\n identifier?: string\n};\n\nexport type Validator = (Object) => $ReadOnlyArray;\n\ntype ValidateStyle = {\n (Object, ?Object): $ReadOnlyArray,\n source: Validator,\n layer: Validator,\n light: Validator,\n filter: Validator,\n paintProperty: Validator,\n layoutProperty: Validator\n};\n\nexport const validateStyle = (validateStyleMin: ValidateStyle);\n\nexport const validateSource = validateStyle.source;\nexport const validateLight = validateStyle.light;\nexport const validateFilter = validateStyle.filter;\nexport const validatePaintProperty = validateStyle.paintProperty;\nexport const validateLayoutProperty = validateStyle.layoutProperty;\n\nexport function emitValidationErrors(emitter: Evented, errors: ?$ReadOnlyArray<{message: string, identifier?: string}>): 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","// @flow\n\nclass ZoomHistory {\n lastZoom: number;\n lastFloorZoom: number;\n lastIntegerZoom: number;\n lastIntegerZoomTime: number;\n first: boolean;\n\n constructor() {\n this.first = true;\n }\n\n update(z: number, now: number) {\n const floorZ = Math.floor(z);\n\n if (this.first) {\n this.first = false;\n this.lastIntegerZoom = floorZ;\n this.lastIntegerZoomTime = 0;\n this.lastZoom = z;\n this.lastFloorZoom = floorZ;\n return true;\n }\n\n if (this.lastFloorZoom > floorZ) {\n this.lastIntegerZoom = floorZ + 1;\n this.lastIntegerZoomTime = now;\n } else if (this.lastFloorZoom < floorZ) {\n this.lastIntegerZoom = floorZ;\n this.lastIntegerZoomTime = now;\n }\n\n if (z !== this.lastZoom) {\n this.lastZoom = z;\n this.lastFloorZoom = floorZ;\n return true;\n }\n\n return false;\n }\n}\n\nexport default ZoomHistory;\n","// @flow\n\n// The following table comes from .\n// Keep it synchronized with .\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';\n\nexport function allowsIdeographicBreaking(chars: string) {\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) {\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) {\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) {\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) {\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// .\n// Keep it synchronized with\n// .\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 .\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) {\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) {\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) {\n return !(charHasUprightVerticalOrientation(char) ||\n charHasNeutralVerticalOrientation(char));\n}\n\nexport function charInComplexShapingScript(char: number) {\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) {\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) {\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) {\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\ntype Config = {|\n API_URL: string,\n EVENTS_URL: ?string,\n FEEDBACK_URL: string,\n REQUIRE_ACCESS_TOKEN: boolean,\n ACCESS_TOKEN: ?string,\n MAX_PARALLEL_IMAGE_REQUESTS: number\n|};\n\nconst config: Config = {\n API_URL: 'https://api.mapbox.com',\n get EVENTS_URL() {\n if (!this.API_URL) { return null; }\n if (this.API_URL.indexOf('https://api.mapbox.cn') === 0) {\n return 'https://events.mapbox.cn/events/v2';\n } else if (this.API_URL.indexOf('https://api.mapbox.com') === 0) {\n return 'https://events.mapbox.com/events/v2';\n } else {\n return null;\n }\n },\n FEEDBACK_URL: 'https://apps.mapbox.com/feedback',\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';\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 strict\n\nimport window from './window';\nimport type {Cancelable} from '../types/cancelable';\n\nconst now = window.performance && window.performance.now ?\n window.performance.now.bind(window.performance) :\n Date.now.bind(Date);\n\nconst raf = window.requestAnimationFrame ||\n window.mozRequestAnimationFrame ||\n window.webkitRequestAnimationFrame ||\n window.msRequestAnimationFrame;\n\nconst cancel = window.cancelAnimationFrame ||\n window.mozCancelAnimationFrame ||\n window.webkitCancelAnimationFrame ||\n window.msCancelAnimationFrame;\n\nlet linkEl;\n\nlet reducedMotionQuery: MediaQueryList;\n\n/**\n * @private\n */\nconst exported = {\n /**\n * Provides a function that outputs milliseconds: either performance.now()\n * or a fallback to Date.now()\n */\n now,\n\n frame(fn: (paintStartTimestamp: number) => void): Cancelable {\n const frame = raf(fn);\n return {cancel: () => cancel(frame)};\n },\n\n getImageData(img: CanvasImageSource, padding?: number = 0): ImageData {\n const canvas = window.document.createElement('canvas');\n const context = canvas.getContext('2d');\n if (!context) {\n throw new Error('failed to create canvas 2d context');\n }\n canvas.width = img.width;\n canvas.height = img.height;\n context.drawImage(img, 0, 0, img.width, img.height);\n return context.getImageData(-padding, -padding, img.width + 2 * padding, img.height + 2 * padding);\n },\n\n resolveURL(path: string) {\n if (!linkEl) linkEl = window.document.createElement('a');\n linkEl.href = path;\n return linkEl.href;\n },\n\n hardwareConcurrency: window.navigator && window.navigator.hardwareConcurrency || 4,\n\n get devicePixelRatio() { 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\n/***** START WARNING - IF YOU USE THIS CODE WITH MAPBOX MAPPING APIS, REMOVAL OR\n* MODIFICATION OF THE FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******\n* The following code is used to access Mapbox's Mapping APIs. Removal or modification\n* of this code when used with Mapbox's Mapping APIs 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';\n\nimport browser from './browser';\nimport window from './window';\nimport webpSupported from './webp_supported';\nimport {createSkuToken, SKU_ID} from './sku_token';\nimport {version as sdkVersion} from '../../package.json';\nimport {uuid, validateUuid, storageAvailable, b64DecodeUnicode, b64EncodeUnicode, warnOnce, extend} from './util';\nimport {postData, ResourceType} from './ajax';\n\nimport type {RequestParameters} from './ajax';\nimport type {Cancelable} from '../types/cancelable';\nimport type {TileJSON} from '../types/tilejson';\n\ntype ResourceTypeEnum = $Keys;\nexport type RequestTransformFunction = (url: string, resourceType?: ResourceTypeEnum) => RequestParameters;\n\ntype UrlObject = {|\n protocol: string,\n authority: string,\n path: string,\n params: Array\n|};\n\nexport class RequestManager {\n _skuToken: string;\n _skuTokenExpiresAt: number;\n _transformRequestFn: ?RequestTransformFunction;\n _customAccessToken: ?string;\n\n constructor(transformRequestFn?: RequestTransformFunction, customAccessToken?: string) {\n this._transformRequestFn = transformRequestFn;\n this._customAccessToken = customAccessToken;\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) {\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): 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 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, tileSize?: ?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 tileURLAPIPrefixRe = /^.+\\/v4\\//;\n\n // The v4 mapbox tile API supports 512x512 image tiles only when @2x\n // is appended to the tile URL. If `tileSize: 512` is specified for\n // a Mapbox raster source force the @2x suffix even if a non hidpi device.\n const suffix = browser.devicePixelRatio >= 2 || tileSize === 512 ? '@2x' : '';\n const extension = webpSupported.supported ? '.webp' : '$1';\n urlObject.path = urlObject.path.replace(imageExtensionRe, `${suffix}${extension}`);\n urlObject.path = urlObject.path.replace(tileURLAPIPrefixRe, '/');\n urlObject.path = `/v4${urlObject.path}`;\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) {\n const version = \"/v4/\";\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/, with a valid filename + extension\n if (!urlObject.path.match(/(^\\/v4\\/)/) || !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://tiles/\";\n result += urlObject.path.replace(version, '');\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) {\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://www.mapbox.com/api-documentation/#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 (!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 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\nfunction isMapboxURL(url: string) {\n return url.indexOf('mapbox:') === 0;\n}\n\nconst mapboxHTTPURLRe = /^((https?:)?\\/\\/)?([^\\/]+\\.)?mapbox\\.c(n|om)(\\/|\\?|$)/i;\nfunction isMapboxHTTPURL(url: string): boolean {\n return mapboxHTTPURLRe.test(url);\n}\n\nfunction hasCacheDefeatingSku(url: string) {\n return url.indexOf('sku=') > 0 && isMapboxHTTPURL(url);\n}\n\nfunction getAccessToken(params: Array): 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\nexport {isMapboxURL, isMapboxHTTPURL, hasCacheDefeatingSku};\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';\n\nclass TelemetryEvent {\n eventData: any;\n anonId: ?string;\n queue: Array;\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) {\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: (err: ?Error) => void, 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 sdkIdentifier: 'mapbox-gl-js',\n sdkVersion,\n skuId: SKU_ID,\n userId: this.anonId\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: number | {id: number, timestamp: number}, customAccessToken?: ?string) {\n this.queue.push(event);\n this.processRequests(customAccessToken);\n }\n}\n\nexport class MapLoadEvent extends TelemetryEvent {\n +success: {[_: number]: boolean};\n skuToken: string;\n\n constructor() {\n super('map.load');\n this.success = {};\n this.skuToken = '';\n }\n\n postMapLoadEvent(tileUrls: Array, mapId: number, skuToken: string, customAccessToken: string) {\n this.skuToken = skuToken;\n\n const accessTokenIsSet = !!(customAccessToken || config.ACCESS_TOKEN);\n const usesMapboxTiles = Array.isArray(tileUrls) && tileUrls.some(url => isMapboxURL(url) || isMapboxHTTPURL(url));\n\n // Enabled only when Mapbox Access Token is set and a source uses mapbox tiles.\n if (config.EVENTS_URL && accessTokenIsSet && usesMapboxTiles) {\n this.queueRequest({id: mapId, timestamp: Date.now()}, customAccessToken);\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 this.postEvent(timestamp, {skuToken: this.skuToken}, (err) => {\n if (!err) {\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, 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 return this.processRequests();\n }\n\n this.postEvent(nextUpdate, {\"enabled.telemetry\": false}, (err) => {\n if (!err) {\n this.eventData.lastSuccess = nextUpdate;\n this.eventData.tokenU = tokenU;\n }\n }, customAccessToken);\n }\n}\n\nconst turnstileEvent_ = new TurnstileEvent();\nexport const postTurnstileEvent = turnstileEvent_.postTurnstileEvent.bind(turnstileEvent_);\n\nconst mapLoadEvent_ = new MapLoadEvent();\nexport const postMapLoadEvent = mapLoadEvent_.postMapLoadEvent.bind(mapLoadEvent_);\n\n/***** END WARNING - REMOVAL OR MODIFICATION OF THE\nPRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******/\n","// @flow\n\n/***** START WARNING - IF YOU USE THIS CODE WITH MAPBOX MAPPING APIS, REMOVAL OR\n* MODIFICATION OF THE FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******\n* The following code is used to access Mapbox's Mapping APIs. Removal or modification\n* of this code when used with Mapbox's Mapping APIs 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';\nimport window from './window';\n\nimport type Dispatcher from './dispatcher';\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: window.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;\n\nfunction cacheOpen() {\n if (window.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) {\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 timeUntilExpiry = new Date(options.headers.get('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 stripQueryParameters(url: string) {\n const start = url.indexOf('?');\n return start < 0 ? url : url.slice(0, start);\n}\n\nexport function cacheGet(request: Request, callback: (error: ?any, response: ?Response, fresh: ?boolean) => void) {\n cacheOpen();\n if (!sharedCache) return callback(null);\n\n const strippedURL = stripQueryParameters(request.url);\n\n sharedCache\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) {\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 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';\nimport {extend, warnOnce, isWorker} from './util';\nimport {isMapboxHTTPURL, hasCacheDefeatingSku} from './mapbox';\nimport config from './config';\nimport assert from 'assert';\nimport {cacheGet, cachePut} from './tile_request_cache';\nimport webpSupported from './webp_supported';\nimport offscreenCanvasSupported from './offscreen_canvas_supported';\n\nimport type {Callback} from '../types/callback';\nimport type {Cancelable} from '../types/cancelable';\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 * @example\n * // use transformRequest to modify requests that begin with `http://myHost`\n * transformRequest: function(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 */\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};\n\nexport type ResponseCallback = (error: ?Error, data: ?T, cacheControl: ?string, expires: ?string) => void;\n\nclass 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://www.mapbox.com/api-documentation/#access-tokens-and-token-scopes';\n }\n super(message);\n this.status = status;\n this.url = url;\n\n // work around for https://github.com/Rich-Harris/buble/issues/40\n this.name = this.constructor.name;\n this.message = message;\n }\n\n toString() {\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 = 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 => /^file:/.test(url) || (/^file:/.test(getReferrer()) && !/^\\w+:/.test(url));\n\nfunction makeFetchRequest(requestParameters: RequestParameters, callback: ResponseCallback): 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 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, cachedResponse, responseIsFresh) => {\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);\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\n } else {\n return callback(new AJAXError(response.statusText, response.status, requestParameters.url));\n }\n }).catch(error => {\n if (error.code === 20) {\n // silence expected AbortError\n return;\n }\n callback(new Error(error.message));\n });\n };\n\n const finishRequest = (response, cacheableResponse, requestTime) => {\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): 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): Cancelable {\n // We're trying to use the Fetch API if possible. However, in some situations we can't use it:\n // - IE11 doesn't support it at all. In this case, we dispatch the request to the main thread so\n // that we can get an accruate referrer header.\n // - Safari exposes window.AbortController, but it doesn't work actually abort any requests in\n // some versions (see https://bugs.webkit.org/show_bug.cgi?id=174980#c2)\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): Cancelable {\n return makeRequest(extend(requestParameters, {type: 'json'}), callback);\n};\n\nexport const getArrayBuffer = function(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable {\n return makeRequest(extend(requestParameters, {type: 'arrayBuffer'}), callback);\n};\n\nexport const postData = function(requestParameters: RequestParameters, callback: ResponseCallback): Cancelable {\n return makeRequest(extend(requestParameters, {method: 'POST'}), callback);\n};\n\nfunction sameOrigin(url) {\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: (err: ?Error, image: ?HTMLImageElement) => void, cacheControl: ?string, expires: ?string) {\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: any).cacheControl = cacheControl;\n (img: any).expires = expires;\n img.src = data.byteLength ? URL.createObjectURL(blob) : transparentPngUrl;\n}\n\nfunction arrayBufferToImageBitmap(data: ArrayBuffer, callback: (err: ?Error, image: ?ImageBitmap) => void) {\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: Callback): 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 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 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 (offscreenCanvasSupported()) {\n arrayBufferToImageBitmap(data, callback);\n } else {\n arrayBufferToImage(data, callback, 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, callback: Callback): 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 {Event, Evented} from '../util/evented';\nimport {getArrayBuffer} from '../util/ajax';\nimport browser from '../util/browser';\nimport assert from 'assert';\nimport {isWorker} from '../util/util';\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;\n pluginURL: ?string\n};\n\ntype ErrorCallback = (error: ?Error) => void;\ntype PluginStateSyncCallback = (state: PluginState) => void;\nlet _completionCallback = null;\n\n//Variables defining the current state of the plugin\nlet pluginStatus = status.unavailable;\nlet pluginURL = 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 = new Evented();\n\nexport const getRTLTextPluginStatus = function () {\n return pluginStatus;\n};\n\nexport const registerForPluginStateChange = function(callback: 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: ?ErrorCallback, 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) => Array,\n processStyledBidirectionalText: ?(string, Array, Array) => Array<[string, Array]>,\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 ZoomHistory from './zoom_history';\nimport {isStringInSupportedScript} from '../util/script_detection';\nimport {plugin as rtlTextPlugin} from '../source/rtl_text_plugin';\n\nimport type {TransitionSpecification} from '../style-spec/types';\n\nexport type CrossfadeParameters = {\n fromScale: number,\n toScale: number,\n t: number\n};\n\nclass EvaluationParameters {\n zoom: number;\n now: number;\n fadeDuration: number;\n zoomHistory: ZoomHistory;\n transition: TransitionSpecification;\n\n // \"options\" may also be another EvaluationParameters to copy, see CrossFadedProperty.possiblyEvaluate\n constructor(zoom: number, options?: *) {\n this.zoom = zoom;\n\n if (options) {\n this.now = options.now;\n this.fadeDuration = options.fadeDuration;\n this.zoomHistory = options.zoomHistory;\n this.transition = options.transition;\n } else {\n this.now = 0;\n this.fadeDuration = 0;\n this.zoomHistory = new ZoomHistory();\n this.transition = {};\n }\n }\n\n isSupportedScript(str: string): boolean {\n return isStringInSupportedScript(str, rtlTextPlugin.isLoaded());\n }\n\n crossFadingFactor() {\n if (this.fadeDuration === 0) {\n return 1;\n } else {\n return Math.min((this.now - this.zoomHistory.lastIntegerZoomTime) / this.fadeDuration, 1);\n }\n }\n\n getCrossfadeParameters(): CrossfadeParameters {\n const z = this.zoom;\n const fraction = z - Math.floor(z);\n const t = this.crossFadingFactor();\n\n return z > this.zoomHistory.lastIntegerZoom ?\n {fromScale: 2, toScale: 1, t: fraction + (1 - fraction) * t} :\n {fromScale: 0.5, toScale: 1, t: 1 - (1 - t) * fraction};\n }\n}\n\nexport default EvaluationParameters;\n","// @flow\n\nimport assert from 'assert';\nimport {clone, extend, easeCubicInOut} from '../util/util';\nimport * as interpolate from '../style-spec/util/interpolate';\nimport {normalizePropertyExpression} from '../style-spec/expression';\nimport Color from '../style-spec/util/color';\nimport {register} from '../util/web_worker_transfer';\nimport EvaluationParameters from './evaluation_parameters';\n\nimport type {CanonicalTileID} from '../source/tile_id';\nimport type {StylePropertySpecification} from '../style-spec/style-spec';\nimport type {\n TransitionSpecification,\n PropertyValueSpecification\n} from '../style-spec/types';\n\nimport type {\n Feature,\n FeatureState,\n StylePropertyExpression,\n SourceExpression,\n CompositeExpression\n} from '../style-spec/expression';\n\ntype TimePoint = number;\n\nexport type CrossFaded = {\n to: T,\n from: T\n};\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: one for properties\n * which cross-fade between two values rather than interpolating, one for `heatmap-color` and `line-gradient`,\n * and one for `light-position`.\n *\n * @private\n */\nexport interface Property {\n specification: StylePropertySpecification;\n possiblyEvaluate(value: PropertyValue, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): 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 {\n property: Property;\n value: PropertyValueSpecification | void;\n expression: StylePropertyExpression;\n\n constructor(property: Property, value: PropertyValueSpecification | 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): R {\n return this.property.possiblyEvaluate(this, parameters, canonical, availableImages);\n }\n}\n\n// ------- Transitionable -------\n\nexport type TransitionParameters = {\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 {\n property: Property;\n value: PropertyValue;\n transition: TransitionSpecification | void;\n\n constructor(property: Property) {\n this.property = property;\n this.value = new PropertyValue(property, undefined);\n }\n\n transitioned(parameters: TransitionParameters,\n prior: TransitioningPropertyValue): TransitioningPropertyValue {\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 {\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`, it calculates\n * an object type with the same keys and values of type `TransitionablePropertyValue`.\n *\n * @private\n */\ntype TransitionablePropertyValues\n = $Exact<$ObjMap(p: Property) => TransitionablePropertyValue>>\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 {\n _properties: Properties;\n _values: TransitionablePropertyValues;\n\n constructor(properties: Properties) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultTransitionablePropertyValues): any);\n }\n\n getValue(name: S): PropertyValueSpecification | void {\n return clone(this._values[name].value.value);\n }\n\n setValue(name: S, value: PropertyValueSpecification | 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(name: S): TransitionSpecification | void {\n return clone(this._values[name].transition);\n }\n\n setTransition(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() {\n const result: any = {};\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): Transitioning {\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 {\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 {\n property: Property;\n value: PropertyValue;\n prior: ?TransitioningPropertyValue;\n begin: TimePoint;\n end: TimePoint;\n\n constructor(property: Property,\n value: PropertyValue,\n prior: ?TransitioningPropertyValue,\n transition: TransitionSpecification,\n now: TimePoint) {\n this.property = property;\n this.value = value;\n this.begin = now + transition.delay || 0;\n this.end = this.begin + transition.duration || 0;\n if (property.specification.transition && (transition.delay || transition.duration)) {\n this.prior = prior;\n }\n }\n\n possiblyEvaluate(parameters: EvaluationParameters, canonical: CanonicalTileID, availableImages: Array): 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`, it calculates\n * an object type with the same keys and values of type `TransitioningPropertyValue`.\n *\n * @private\n */\ntype TransitioningPropertyValues\n = $Exact<$ObjMap(p: Property) => TransitioningPropertyValue>>\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 {\n _properties: Properties;\n _values: TransitioningPropertyValues;\n\n constructor(properties: Properties) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultTransitioningPropertyValues): any);\n }\n\n possiblyEvaluate(parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): PossiblyEvaluated {\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() {\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`, it calculates\n * an object type with the same keys and values of type `PropertyValue`.\n *\n * @private\n */\ntype PropertyValues\n = $Exact<$ObjMap(p: Property) => PropertyValue>>\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 {\n _properties: Properties;\n _values: PropertyValues;\n\n constructor(properties: Properties) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultPropertyValues): any);\n }\n\n getValue(name: S) {\n return clone(this._values[name].value);\n }\n\n setValue(name: S, value: *) {\n this._values[name] = new PropertyValue(this._values[name].property, value === null ? undefined : clone(value));\n }\n\n serialize() {\n const result: any = {};\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): PossiblyEvaluated {\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 */\ntype PossiblyEvaluatedValue =\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 {\n property: DataDrivenProperty;\n value: PossiblyEvaluatedValue;\n parameters: EvaluationParameters;\n\n constructor(property: DataDrivenProperty, value: PossiblyEvaluatedValue, 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): 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`, 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`, but flow will not complain about comparing this to a number using `===`.\n * See https://github.com/facebook/flow/issues/2359.)\n *\n * There's also a third, special case possiblity for `R`: for cross-faded properties, it's `?CrossFaded`.\n *\n * @private\n */\ntype PossiblyEvaluatedPropertyValues\n = $Exact<$ObjMap(p: Property) => 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 {\n _properties: Properties;\n _values: PossiblyEvaluatedPropertyValues;\n\n constructor(properties: Properties) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultPossiblyEvaluatedValues): any);\n }\n\n get(name: S): $ElementType, 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 implements Property {\n specification: StylePropertySpecification;\n\n constructor(specification: StylePropertySpecification) {\n this.specification = specification;\n }\n\n possiblyEvaluate(value: PropertyValue, parameters: EvaluationParameters): T {\n assert(!value.isDataDriven());\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`; obtaining\n * a scalar value `T` requires further evaluation on a per-feature basis.\n *\n * @private\n */\nexport class DataDrivenProperty implements Property> {\n specification: StylePropertySpecification;\n overrides: ?Object;\n\n constructor(specification: StylePropertySpecification, overrides?: Object) {\n this.specification = specification;\n this.overrides = overrides;\n }\n\n possiblyEvaluate(value: PropertyValue>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): PossiblyEvaluatedPropertyValue {\n if (value.expression.kind === 'constant' || value.expression.kind === 'camera') {\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,\n b: PossiblyEvaluatedPropertyValue,\n t: number): PossiblyEvaluatedPropertyValue {\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, parameters: EvaluationParameters, feature: Feature, featureState: FeatureState, canonical?: CanonicalTileID, availableImages?: Array): T {\n if (value.kind === 'constant') {\n return value.value;\n } else {\n return value.evaluate(parameters, feature, featureState, canonical, availableImages);\n }\n }\n}\n\n/**\n * An implementation of `Property` for data driven `line-pattern` which are transitioned by cross-fading\n * rather than interpolation.\n *\n * @private\n */\n\nexport class CrossFadedDataDrivenProperty extends DataDrivenProperty> {\n\n possiblyEvaluate(value: PropertyValue, PossiblyEvaluatedPropertyValue>>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): PossiblyEvaluatedPropertyValue> {\n if (value.value === undefined) {\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: undefined}, parameters);\n } else if (value.expression.kind === 'constant') {\n const evaluatedValue = value.expression.evaluate(parameters, (null: any), {}, canonical, availableImages);\n const isImageExpression = value.property.specification.type === 'resolvedImage';\n const constantValue = isImageExpression && typeof evaluatedValue !== 'string' ? evaluatedValue.name : evaluatedValue;\n const constant = this._calculate(constantValue, constantValue, constantValue, parameters);\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: constant}, parameters);\n } else if (value.expression.kind === 'camera') {\n const cameraVal = this._calculate(\n value.expression.evaluate({zoom: parameters.zoom - 1.0}),\n value.expression.evaluate({zoom: parameters.zoom}),\n value.expression.evaluate({zoom: parameters.zoom + 1.0}),\n parameters);\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: cameraVal}, parameters);\n } else {\n // source or composite expression\n return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters);\n }\n }\n\n evaluate(value: PossiblyEvaluatedValue>, globals: EvaluationParameters, feature: Feature, featureState: FeatureState, canonical?: CanonicalTileID, availableImages?: Array): ?CrossFaded {\n if (value.kind === 'source') {\n const constant = value.evaluate(globals, feature, featureState, canonical, availableImages);\n return this._calculate(constant, constant, constant, globals);\n } else if (value.kind === 'composite') {\n return this._calculate(\n value.evaluate({zoom: Math.floor(globals.zoom) - 1.0}, feature, featureState),\n value.evaluate({zoom: Math.floor(globals.zoom)}, feature, featureState),\n value.evaluate({zoom: Math.floor(globals.zoom) + 1.0}, feature, featureState),\n globals);\n } else {\n return value.value;\n }\n }\n\n _calculate(min: T, mid: T, max: T, parameters: EvaluationParameters): CrossFaded {\n const z = parameters.zoom;\n return z > parameters.zoomHistory.lastIntegerZoom ? {from: min, to: mid} : {from: max, to: mid};\n }\n\n interpolate(a: PossiblyEvaluatedPropertyValue>): PossiblyEvaluatedPropertyValue> {\n return a;\n }\n}\n/**\n * An implementation of `Property` for `*-pattern` and `line-dasharray`, which are transitioned by cross-fading\n * rather than interpolation.\n *\n * @private\n */\nexport class CrossFadedProperty implements Property> {\n specification: StylePropertySpecification;\n\n constructor(specification: StylePropertySpecification) {\n this.specification = specification;\n }\n\n possiblyEvaluate(value: PropertyValue>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): ?CrossFaded {\n if (value.value === undefined) {\n return undefined;\n } else if (value.expression.kind === 'constant') {\n const constant = value.expression.evaluate(parameters, (null: any), {}, canonical, availableImages);\n return this._calculate(constant, constant, constant, parameters);\n } else {\n assert(!value.isDataDriven());\n return this._calculate(\n value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom - 1.0), parameters)),\n value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom), parameters)),\n value.expression.evaluate(new EvaluationParameters(Math.floor(parameters.zoom + 1.0), parameters)),\n parameters);\n }\n }\n\n _calculate(min: T, mid: T, max: T, parameters: EvaluationParameters): ?CrossFaded {\n const z = parameters.zoom;\n return z > parameters.zoomHistory.lastIntegerZoom ? {from: min, to: mid} : {from: max, to: mid};\n }\n\n interpolate(a: ?CrossFaded): ?CrossFaded {\n return a;\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 */\n\nexport class ColorRampProperty implements Property {\n specification: StylePropertySpecification;\n\n constructor(specification: StylePropertySpecification) {\n this.specification = specification;\n }\n\n possiblyEvaluate(value: PropertyValue, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array): boolean {\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 {\n properties: Props;\n defaultPropertyValues: PropertyValues;\n defaultTransitionablePropertyValues: TransitionablePropertyValues;\n defaultTransitioningPropertyValues: TransitioningPropertyValues;\n defaultPossiblyEvaluatedValues: PossiblyEvaluatedPropertyValues;\n overridableProperties: Array;\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 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(({}: any));\n }\n }\n}\n\nregister('DataDrivenProperty', DataDrivenProperty);\nregister('DataConstantProperty', DataConstantProperty);\nregister('CrossFadedDataDrivenProperty', CrossFadedDataDrivenProperty);\nregister('CrossFadedProperty', CrossFadedProperty);\nregister('ColorRampProperty', ColorRampProperty);\n","// @flow\n\nimport {endsWith, filterObject} from '../util/util';\n\nimport styleSpec from '../style-spec/reference/latest';\nimport {\n validateStyle,\n validateLayoutProperty,\n validatePaintProperty,\n emitValidationErrors\n} from './validate_style';\nimport {Evented} from '../util/evented';\nimport {Layout, Transitionable, Transitioning, Properties, PossiblyEvaluated, PossiblyEvaluatedPropertyValue} from './properties';\nimport {supportsPropertyExpression} from '../style-spec/util/properties';\n\nimport type {FeatureState} from '../style-spec/expression';\nimport type {Bucket} from '../data/bucket';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureFilter} from '../style-spec/feature_filter';\nimport type {TransitionParameters, PropertyValue} from './properties';\nimport type EvaluationParameters, {CrossfadeParameters} from './evaluation_parameters';\nimport type Transform from '../geo/transform';\nimport type {\n LayerSpecification,\n FilterSpecification\n} from '../style-spec/types';\nimport type {CustomLayerInterface} from './style_layer/custom_style_layer';\nimport type Map from '../ui/map';\nimport type {StyleSetterOptions} from './style';\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 _crossfadeParameters: CrossfadeParameters;\n\n _unevaluatedLayout: Layout;\n +layout: mixed;\n\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n +paint: mixed;\n\n _featureFilter: FeatureFilter;\n\n +queryRadius: (bucket: Bucket) => number;\n +queryIntersectsFeature: (queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number,\n pixelPosMatrix: Float32Array) => 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};\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') {\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 getCrossfadeParameters() {\n return this._crossfadeParameters;\n }\n\n getLayoutProperty(name: string) {\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) {\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 = {}) {\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 isCrossFadedProperty = transitionable.property.specification[\"property-type\"] === 'cross-faded-data-driven';\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\n // if a cross-faded 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 || isCrossFadedProperty || this._handleOverridablePaintPropertyUpdate(name, oldValue, newValue);\n }\n }\n\n _handleSpecialPaintPropertyUpdate(_: string) {\n // No-op; can be overridden by derived classes.\n }\n\n // eslint-disable-next-line no-unused-vars\n _handleOverridablePaintPropertyUpdate(name: string, oldValue: PropertyValue, newValue: PropertyValue): boolean {\n // No-op; can be overridden by derived classes.\n return false;\n }\n\n isHidden(zoom: number) {\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() {\n return this._transitioningPaint.hasTransition();\n }\n\n recalculate(parameters: EvaluationParameters, availableImages: Array) {\n if (parameters.getCrossfadeParameters) {\n this._crossfadeParameters = parameters.getCrossfadeParameters();\n }\n\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() {\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 = {}) {\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() {\n return false;\n }\n\n isTileClipped() {\n return false;\n }\n\n hasOffscreenPass() {\n return false;\n }\n\n resize() {\n // noop\n }\n\n isStateDependent() {\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\nexport default StyleLayer;\n","// @flow\n\n// Note: all \"sizes\" are measured in bytes\n\nimport assert from 'assert';\n\nimport type {Transferable} from '../types/transferable';\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;\n\n/**\n * @private\n */\nclass Struct {\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,\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;\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): 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) {\n const structArray = 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;\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() {\n throw new Error('_refreshViews() must be implemented by each concrete StructArray layout');\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// @flow\n\nimport assert from 'assert';\nimport {Struct, StructArray} from '../util/struct_array';\nimport {register} from '../util/web_worker_transfer';\nimport Point from '@mapbox/point-geometry';\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) {\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) {\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[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) {\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) {\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]: Int16[4]\n *\n * @private\n */\nclass StructArrayLayout2i4i12 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) {\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) {\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\nStructArrayLayout2i4i12.prototype.bytesPerElement = 12;\nregister('StructArrayLayout2i4i12', StructArrayLayout2i4i12);\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[2]\n * [4]: Uint8[4]\n *\n * @private\n */\nclass StructArrayLayout2i4ub8 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) {\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) {\n const o2 = i * 4;\n const o1 = i * 8;\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 return i;\n }\n}\n\nStructArrayLayout2i4ub8.prototype.bytesPerElement = 8;\nregister('StructArrayLayout2i4ub8', StructArrayLayout2i4ub8);\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) {\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) {\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\n/**\n * Implementation of the StructArray layout:\n * [0]: Uint16[10]\n *\n * @private\n */\nclass StructArrayLayout10ui20 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, v4: number, v5: number, v6: number, v7: number, v8: number, v9: 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);\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) {\n const o2 = i * 10;\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.uint16[o2 + 4] = v4;\n this.uint16[o2 + 5] = v5;\n this.uint16[o2 + 6] = v6;\n this.uint16[o2 + 7] = v7;\n this.uint16[o2 + 8] = v8;\n this.uint16[o2 + 9] = v9;\n return i;\n }\n}\n\nStructArrayLayout10ui20.prototype.bytesPerElement = 20;\nregister('StructArrayLayout10ui20', StructArrayLayout10ui20);\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) {\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) {\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]: 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) {\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) {\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]: 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) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0);\n }\n\n emplace(i: number, v0: 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[6]\n * [12]: Uint32[1]\n * [16]: Uint16[2]\n *\n * @private\n */\nclass StructArrayLayout6i1ul2ui20 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\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.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) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6, v7, v8);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: 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.int16[o2 + 3] = v3;\n this.int16[o2 + 4] = v4;\n this.int16[o2 + 5] = v5;\n this.uint32[o4 + 3] = v6;\n this.uint16[o2 + 8] = v7;\n this.uint16[o2 + 9] = v8;\n return i;\n }\n}\n\nStructArrayLayout6i1ul2ui20.prototype.bytesPerElement = 20;\nregister('StructArrayLayout6i1ul2ui20', StructArrayLayout6i1ul2ui20);\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[2]\n * [4]: Int16[2]\n * [8]: Int16[2]\n *\n * @private\n */\nclass StructArrayLayout2i2i2i12 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) {\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) {\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\nStructArrayLayout2i2i2i12.prototype.bytesPerElement = 12;\nregister('StructArrayLayout2i2i2i12', StructArrayLayout2i2i2i12);\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) {\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) {\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) {\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) {\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]: 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) {\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) {\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[2]\n * [4]: Uint16[2]\n * [8]: Uint32[3]\n * [20]: Uint16[3]\n * [28]: Float32[2]\n * [36]: Uint8[3]\n * [40]: Uint32[1]\n * [44]: Int16[1]\n *\n * @private\n */\nclass StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n uint16: Uint16Array;\n uint32: Uint32Array;\n float32: Float32Array;\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 this.uint32 = new Uint32Array(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, v7: number, v8: number, v9: number, v10: number, v11: number, v12: number, v13: number, v14: number, v15: number, v16: 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);\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) {\n const o2 = i * 24;\n const o4 = i * 12;\n const o1 = i * 48;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.uint16[o2 + 2] = v2;\n this.uint16[o2 + 3] = v3;\n this.uint32[o4 + 2] = v4;\n this.uint32[o4 + 3] = v5;\n this.uint32[o4 + 4] = v6;\n this.uint16[o2 + 10] = v7;\n this.uint16[o2 + 11] = v8;\n this.uint16[o2 + 12] = v9;\n this.float32[o4 + 7] = v10;\n this.float32[o4 + 8] = v11;\n this.uint8[o1 + 36] = v12;\n this.uint8[o1 + 37] = v13;\n this.uint8[o1 + 38] = v14;\n this.uint32[o4 + 10] = v15;\n this.int16[o2 + 22] = v16;\n return i;\n }\n}\n\nStructArrayLayout2i2ui3ul3ui2f3ub1ul1i48.prototype.bytesPerElement = 48;\nregister('StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48', StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48);\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Int16[8]\n * [16]: Uint16[15]\n * [48]: Uint32[1]\n * [52]: Float32[4]\n *\n * @private\n */\nclass StructArrayLayout8i15ui1ul4f68 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n uint16: Uint16Array;\n uint32: Uint32Array;\n float32: Float32Array;\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 this.uint32 = new Uint32Array(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, 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) {\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);\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) {\n const o2 = i * 34;\n const o4 = i * 17;\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 this.int16[o2 + 6] = v6;\n this.int16[o2 + 7] = v7;\n this.uint16[o2 + 8] = v8;\n this.uint16[o2 + 9] = v9;\n this.uint16[o2 + 10] = v10;\n this.uint16[o2 + 11] = v11;\n this.uint16[o2 + 12] = v12;\n this.uint16[o2 + 13] = v13;\n this.uint16[o2 + 14] = v14;\n this.uint16[o2 + 15] = v15;\n this.uint16[o2 + 16] = v16;\n this.uint16[o2 + 17] = v17;\n this.uint16[o2 + 18] = v18;\n this.uint16[o2 + 19] = v19;\n this.uint16[o2 + 20] = v20;\n this.uint16[o2 + 21] = v21;\n this.uint16[o2 + 22] = v22;\n this.uint32[o4 + 12] = v23;\n this.float32[o4 + 13] = v24;\n this.float32[o4 + 14] = v25;\n this.float32[o4 + 15] = v26;\n this.float32[o4 + 16] = v27;\n return i;\n }\n}\n\nStructArrayLayout8i15ui1ul4f68.prototype.bytesPerElement = 68;\nregister('StructArrayLayout8i15ui1ul4f68', StructArrayLayout8i15ui1ul4f68);\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) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0);\n }\n\n emplace(i: number, v0: 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]: 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) {\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) {\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]: Uint32[1]\n * [4]: Uint16[2]\n *\n * @private\n */\nclass StructArrayLayout1ul2ui8 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) {\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) {\n const o4 = i * 2;\n const o2 = i * 4;\n this.uint32[o4 + 0] = v0;\n this.uint16[o2 + 2] = v1;\n this.uint16[o2 + 3] = v2;\n return i;\n }\n}\n\nStructArrayLayout1ul2ui8.prototype.bytesPerElement = 8;\nregister('StructArrayLayout1ul2ui8', StructArrayLayout1ul2ui8);\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) {\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) {\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) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0);\n }\n\n emplace(i: number, v0: 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[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) {\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) {\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\nclass CollisionBoxStruct extends Struct {\n _structArray: CollisionBoxArray;\n anchorPointX: number;\n anchorPointY: number;\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n featureIndex: number;\n sourceLayerIndex: number;\n bucketIndex: number;\n anchorPoint: Point;\n get anchorPointX() { return this._structArray.int16[this._pos2 + 0]; }\n get anchorPointY() { return this._structArray.int16[this._pos2 + 1]; }\n get x1() { return this._structArray.int16[this._pos2 + 2]; }\n get y1() { return this._structArray.int16[this._pos2 + 3]; }\n get x2() { return this._structArray.int16[this._pos2 + 4]; }\n get y2() { return this._structArray.int16[this._pos2 + 5]; }\n get featureIndex() { return this._structArray.uint32[this._pos4 + 3]; }\n get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 8]; }\n get bucketIndex() { return this._structArray.uint16[this._pos2 + 9]; }\n get anchorPoint() { return new Point(this.anchorPointX, this.anchorPointY); }\n}\n\nCollisionBoxStruct.prototype.size = 20;\n\nexport type CollisionBox = CollisionBoxStruct;\n\n/**\n * @private\n */\nexport class CollisionBoxArray extends StructArrayLayout6i1ul2ui20 {\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 return new CollisionBoxStruct(this, index);\n }\n}\n\nregister('CollisionBoxArray', CollisionBoxArray);\n\nclass PlacedSymbolStruct extends Struct {\n _structArray: PlacedSymbolArray;\n anchorX: number;\n anchorY: number;\n glyphStartIndex: number;\n numGlyphs: number;\n vertexStartIndex: number;\n lineStartIndex: number;\n lineLength: number;\n segment: number;\n lowerSize: number;\n upperSize: number;\n lineOffsetX: number;\n lineOffsetY: number;\n writingMode: number;\n placedOrientation: number;\n hidden: number;\n crossTileID: number;\n associatedIconIndex: number;\n get anchorX() { return this._structArray.int16[this._pos2 + 0]; }\n get anchorY() { return this._structArray.int16[this._pos2 + 1]; }\n get glyphStartIndex() { return this._structArray.uint16[this._pos2 + 2]; }\n get numGlyphs() { return this._structArray.uint16[this._pos2 + 3]; }\n get vertexStartIndex() { return this._structArray.uint32[this._pos4 + 2]; }\n get lineStartIndex() { return this._structArray.uint32[this._pos4 + 3]; }\n get lineLength() { return this._structArray.uint32[this._pos4 + 4]; }\n get segment() { return this._structArray.uint16[this._pos2 + 10]; }\n get lowerSize() { return this._structArray.uint16[this._pos2 + 11]; }\n get upperSize() { return this._structArray.uint16[this._pos2 + 12]; }\n get lineOffsetX() { return this._structArray.float32[this._pos4 + 7]; }\n get lineOffsetY() { return this._structArray.float32[this._pos4 + 8]; }\n get writingMode() { return this._structArray.uint8[this._pos1 + 36]; }\n get placedOrientation() { return this._structArray.uint8[this._pos1 + 37]; }\n set placedOrientation(x: number) { this._structArray.uint8[this._pos1 + 37] = x; }\n get hidden() { return this._structArray.uint8[this._pos1 + 38]; }\n set hidden(x: number) { this._structArray.uint8[this._pos1 + 38] = x; }\n get crossTileID() { return this._structArray.uint32[this._pos4 + 10]; }\n set crossTileID(x: number) { this._structArray.uint32[this._pos4 + 10] = x; }\n get associatedIconIndex() { return this._structArray.int16[this._pos2 + 22]; }\n}\n\nPlacedSymbolStruct.prototype.size = 48;\n\nexport type PlacedSymbol = PlacedSymbolStruct;\n\n/**\n * @private\n */\nexport class PlacedSymbolArray extends StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48 {\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 return new PlacedSymbolStruct(this, index);\n }\n}\n\nregister('PlacedSymbolArray', PlacedSymbolArray);\n\nclass SymbolInstanceStruct extends Struct {\n _structArray: SymbolInstanceArray;\n anchorX: number;\n anchorY: number;\n rightJustifiedTextSymbolIndex: number;\n centerJustifiedTextSymbolIndex: number;\n leftJustifiedTextSymbolIndex: number;\n verticalPlacedTextSymbolIndex: number;\n placedIconSymbolIndex: number;\n verticalPlacedIconSymbolIndex: number;\n key: number;\n textBoxStartIndex: number;\n textBoxEndIndex: number;\n verticalTextBoxStartIndex: number;\n verticalTextBoxEndIndex: number;\n iconBoxStartIndex: number;\n iconBoxEndIndex: number;\n verticalIconBoxStartIndex: number;\n verticalIconBoxEndIndex: number;\n featureIndex: number;\n numHorizontalGlyphVertices: number;\n numVerticalGlyphVertices: number;\n numIconVertices: number;\n numVerticalIconVertices: number;\n useRuntimeCollisionCircles: number;\n crossTileID: number;\n textBoxScale: number;\n textOffset0: number;\n textOffset1: number;\n collisionCircleDiameter: number;\n get anchorX() { return this._structArray.int16[this._pos2 + 0]; }\n get anchorY() { return this._structArray.int16[this._pos2 + 1]; }\n get rightJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 2]; }\n get centerJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 3]; }\n get leftJustifiedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 4]; }\n get verticalPlacedTextSymbolIndex() { return this._structArray.int16[this._pos2 + 5]; }\n get placedIconSymbolIndex() { return this._structArray.int16[this._pos2 + 6]; }\n get verticalPlacedIconSymbolIndex() { return this._structArray.int16[this._pos2 + 7]; }\n get key() { return this._structArray.uint16[this._pos2 + 8]; }\n get textBoxStartIndex() { return this._structArray.uint16[this._pos2 + 9]; }\n get textBoxEndIndex() { return this._structArray.uint16[this._pos2 + 10]; }\n get verticalTextBoxStartIndex() { return this._structArray.uint16[this._pos2 + 11]; }\n get verticalTextBoxEndIndex() { return this._structArray.uint16[this._pos2 + 12]; }\n get iconBoxStartIndex() { return this._structArray.uint16[this._pos2 + 13]; }\n get iconBoxEndIndex() { return this._structArray.uint16[this._pos2 + 14]; }\n get verticalIconBoxStartIndex() { return this._structArray.uint16[this._pos2 + 15]; }\n get verticalIconBoxEndIndex() { return this._structArray.uint16[this._pos2 + 16]; }\n get featureIndex() { return this._structArray.uint16[this._pos2 + 17]; }\n get numHorizontalGlyphVertices() { return this._structArray.uint16[this._pos2 + 18]; }\n get numVerticalGlyphVertices() { return this._structArray.uint16[this._pos2 + 19]; }\n get numIconVertices() { return this._structArray.uint16[this._pos2 + 20]; }\n get numVerticalIconVertices() { return this._structArray.uint16[this._pos2 + 21]; }\n get useRuntimeCollisionCircles() { return this._structArray.uint16[this._pos2 + 22]; }\n get crossTileID() { return this._structArray.uint32[this._pos4 + 12]; }\n set crossTileID(x: number) { this._structArray.uint32[this._pos4 + 12] = x; }\n get textBoxScale() { return this._structArray.float32[this._pos4 + 13]; }\n get textOffset0() { return this._structArray.float32[this._pos4 + 14]; }\n get textOffset1() { return this._structArray.float32[this._pos4 + 15]; }\n get collisionCircleDiameter() { return this._structArray.float32[this._pos4 + 16]; }\n}\n\nSymbolInstanceStruct.prototype.size = 68;\n\nexport type SymbolInstance = SymbolInstanceStruct;\n\n/**\n * @private\n */\nexport class SymbolInstanceArray extends StructArrayLayout8i15ui1ul4f68 {\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 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) { return this.float32[index * 1 + 0]; }\n}\n\nregister('GlyphOffsetArray', GlyphOffsetArray);\n\n/**\n * @private\n */\nexport class SymbolLineVertexArray extends StructArrayLayout3i6 {\n getx(index: number) { return this.int16[index * 3 + 0]; }\n gety(index: number) { return this.int16[index * 3 + 1]; }\n gettileUnitDistanceFromAnchor(index: number) { return this.int16[index * 3 + 2]; }\n}\n\nregister('SymbolLineVertexArray', SymbolLineVertexArray);\n\nclass FeatureIndexStruct extends Struct {\n _structArray: FeatureIndexArray;\n featureIndex: number;\n sourceLayerIndex: number;\n bucketIndex: number;\n get featureIndex() { return this._structArray.uint32[this._pos4 + 0]; }\n get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 2]; }\n get bucketIndex() { return this._structArray.uint16[this._pos2 + 3]; }\n}\n\nFeatureIndexStruct.prototype.size = 8;\n\nexport type FeatureIndex = FeatureIndexStruct;\n\n/**\n * @private\n */\nexport class FeatureIndexArray extends StructArrayLayout1ul2ui8 {\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 return new FeatureIndexStruct(this, index);\n }\n}\n\nregister('FeatureIndexArray', FeatureIndexArray);\n\nexport {\n StructArrayLayout2i4,\n StructArrayLayout4i8,\n StructArrayLayout2i4i12,\n StructArrayLayout2i4ub8,\n StructArrayLayout2f8,\n StructArrayLayout10ui20,\n StructArrayLayout4i4ui4i24,\n StructArrayLayout3f12,\n StructArrayLayout1ul4,\n StructArrayLayout6i1ul2ui20,\n StructArrayLayout2i2i2i12,\n StructArrayLayout2f1f2i16,\n StructArrayLayout2ub2f12,\n StructArrayLayout3ui6,\n StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48,\n StructArrayLayout8i15ui1ul4f68,\n StructArrayLayout1f4,\n StructArrayLayout3i6,\n StructArrayLayout1ul2ui8,\n StructArrayLayout2ui4,\n StructArrayLayout1ui2,\n StructArrayLayout4f16,\n StructArrayLayout2i4 as PosArray,\n StructArrayLayout4i8 as RasterBoundsArray,\n StructArrayLayout2i4 as CircleLayoutArray,\n StructArrayLayout2i4 as FillLayoutArray,\n StructArrayLayout2i4i12 as FillExtrusionLayoutArray,\n StructArrayLayout2i4 as HeatmapLayoutArray,\n StructArrayLayout2i4ub8 as LineLayoutArray,\n StructArrayLayout2f8 as LineExtLayoutArray,\n StructArrayLayout10ui20 as PatternLayoutArray,\n StructArrayLayout4i4ui4i24 as SymbolLayoutArray,\n StructArrayLayout3f12 as SymbolDynamicLayoutArray,\n StructArrayLayout1ul4 as SymbolOpacityArray,\n StructArrayLayout2i2i2i12 as CollisionBoxLayoutArray,\n StructArrayLayout2f1f2i16 as CollisionCircleLayoutArray,\n StructArrayLayout2ub2f12 as CollisionVertexArray,\n StructArrayLayout3ui6 as QuadTriangleArray,\n StructArrayLayout3ui6 as TriangleIndexArray,\n StructArrayLayout2ui4 as LineIndexArray,\n StructArrayLayout1ui2 as LineStripIndexArray\n};\n","// @flow\nimport {createLayout} from '../../util/struct_array';\n\nconst layout = createLayout([\n {name: 'a_pos', components: 2, type: 'Int16'}\n], 4);\n\nexport default layout;\nexport const {members, size, alignment} = layout;\n","// @flow\n\nimport {warnOnce} from '../util/util';\n\nimport {register} from '../util/web_worker_transfer';\n\nimport type VertexArrayObject from '../render/vertex_array_object';\nimport type {StructArray} from '../util/struct_array';\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;\n\n constructor(segments?: Array = []) {\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() {\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\nimport {clamp} from '../util/util';\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) {\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\nimport {createLayout} from '../../util/struct_array';\n\nconst patternAttributes = createLayout([\n // [tl.x, tl.y, br.x, br.y]\n {name: 'a_pattern_from', components: 4, type: 'Uint16'},\n {name: 'a_pattern_to', components: 4, type: 'Uint16'},\n {name: 'a_pixel_ratio_from', components: 1, type: 'Uint16'},\n {name: 'a_pixel_ratio_to', components: 1, type: 'Uint16'},\n]);\n\nexport default patternAttributes;\n","/**\n * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)\n * \n * @author Gary Court\n * @see http://github.com/garycourt/murmurhash-js\n * @author Austin Appleby\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 Gary Court\n * @see http://github.com/garycourt/murmurhash-js\n * @author Austin Appleby\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';\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;\n positions: Array;\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 {\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): 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\nconst MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;\n\nfunction getNumericId(value: mixed) {\n const numValue = +value;\n if (!isNaN(numValue) && numValue <= 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, positions, left, right) {\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, i, j) {\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';\n\nimport type Context from '../gl/context';\n\nexport type UniformValues\n = $Exact<$ObjMap(u: Uniform) => V>>;\nexport type UniformLocations = {[_: string]: WebGLUniformLocation};\n\nclass Uniform {\n gl: WebGLRenderingContext;\n location: ?WebGLUniformLocation;\n current: T;\n\n constructor(context: Context, location: WebGLUniformLocation) {\n this.gl = context.gl;\n this.location = location;\n }\n\n +set: (v: T) => void;\n}\n\nclass Uniform1i extends Uniform {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = 0;\n }\n\n set(v: number): void {\n if (this.current !== v) {\n this.current = v;\n this.gl.uniform1i(this.location, v);\n }\n }\n}\n\nclass Uniform1f extends Uniform {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = 0;\n }\n\n set(v: number): void {\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, location: WebGLUniformLocation) {\n super(context, location);\n this.current = [0, 0];\n }\n\n set(v: [number, number]): void {\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, location: WebGLUniformLocation) {\n super(context, location);\n this.current = [0, 0, 0];\n }\n\n set(v: [number, number, number]): void {\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, location: WebGLUniformLocation) {\n super(context, location);\n this.current = [0, 0, 0, 0];\n }\n\n set(v: [number, number, number, number]): void {\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 {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = Color.transparent;\n }\n\n set(v: Color): void {\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 {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = emptyMat4;\n }\n\n set(v: Float32Array): void {\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\nexport {\n Uniform,\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform3f,\n Uniform4f,\n UniformColor,\n UniformMatrix4f\n};\n\nexport type UniformBindings = {[_: string]: Uniform};\n","// @flow\n\nimport {packUint8ToFloat} from '../shaders/encode_attribute';\nimport Color from '../style-spec/util/color';\nimport {supportsPropertyExpression} from '../style-spec/util/properties';\nimport {register} from '../util/web_worker_transfer';\nimport {PossiblyEvaluatedPropertyValue} from '../style/properties';\nimport {StructArrayLayout1f4, StructArrayLayout2f8, StructArrayLayout4f16, PatternLayoutArray} from './array_types';\nimport {clamp} from '../util/util';\nimport patternAttributes from './bucket/pattern_attributes';\nimport EvaluationParameters from '../style/evaluation_parameters';\nimport FeaturePositionMap from './feature_position_map';\nimport {\n Uniform,\n Uniform1f,\n UniformColor,\n Uniform4f,\n type UniformLocations\n} from '../render/uniform_binding';\n\nimport type {CanonicalTileID} from '../source/tile_id';\nimport type Context from '../gl/context';\nimport type {TypedStyleLayer} from '../style/style_layer/typed_style_layer';\nimport type {CrossfadeParameters} from '../style/evaluation_parameters';\nimport type {StructArray, StructArrayMember} from '../util/struct_array';\nimport type VertexBuffer from '../gl/vertex_buffer';\nimport type {ImagePosition} from '../render/image_atlas';\nimport type {\n Feature,\n FeatureState,\n GlobalProperties,\n SourceExpression,\n CompositeExpression\n} from '../style-spec/expression';\nimport type {PossiblyEvaluated} from '../style/properties';\nimport type {FeatureStates} from '../source/source_state';\nimport type {FormattedSection} from '../style-spec/expression/types/formatted';\n\nexport type BinderUniform = {\n name: string,\n property: string,\n binding: Uniform\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 multliple 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 accomodate this.\n *\n * @private\n */\n\ninterface AttributeBinder {\n populatePaintArray(length: number, feature: Feature, imagePositions: {[_: string]: ImagePosition}, canonical?: CanonicalTileID, formattedSection?: FormattedSection): void;\n updatePaintArray(start: number, length: number, feature: Feature, featureState: FeatureState, imagePositions: {[_: string]: ImagePosition}): void;\n upload(Context): void;\n destroy(): void;\n}\n\ninterface UniformBinder {\n uniformNames: Array;\n setUniform(uniform: Uniform<*>, globals: GlobalProperties, currentValue: PossiblyEvaluatedPropertyValue<*>, uniformName: string): void;\n getBinding(context: Context, location: WebGLUniformLocation, name: string): $Shape>;\n}\n\nclass ConstantBinder implements UniformBinder {\n value: mixed;\n type: string;\n uniformNames: Array;\n\n constructor(value: mixed, names: Array, type: string) {\n this.value = value;\n this.uniformNames = names.map(name => `u_${name}`);\n this.type = type;\n }\n\n setUniform(uniform: Uniform<*>, globals: GlobalProperties, currentValue: PossiblyEvaluatedPropertyValue): void {\n uniform.set(currentValue.constantOr(this.value));\n }\n\n getBinding(context: Context, location: WebGLUniformLocation, _: string): $Shape> {\n return (this.type === 'color') ?\n new UniformColor(context, location) :\n new Uniform1f(context, location);\n }\n}\n\nclass CrossFadedConstantBinder implements UniformBinder {\n uniformNames: Array;\n patternFrom: ?Array;\n patternTo: ?Array;\n pixelRatioFrom: number;\n pixelRatioTo: number;\n\n constructor(value: mixed, names: Array) {\n this.uniformNames = names.map(name => `u_${name}`);\n this.patternFrom = null;\n this.patternTo = null;\n this.pixelRatioFrom = 1.0;\n this.pixelRatioTo = 1.0;\n }\n\n setConstantPatternPositions(posTo: ImagePosition, posFrom: ImagePosition) {\n this.pixelRatioFrom = posFrom.pixelRatio;\n this.pixelRatioTo = posTo.pixelRatio;\n this.patternFrom = posFrom.tlbr;\n this.patternTo = posTo.tlbr;\n }\n\n setUniform(uniform: Uniform<*>, globals: GlobalProperties, currentValue: PossiblyEvaluatedPropertyValue, uniformName: string) {\n const pos =\n uniformName === 'u_pattern_to' ? this.patternTo :\n uniformName === 'u_pattern_from' ? this.patternFrom :\n uniformName === 'u_pixel_ratio_to' ? this.pixelRatioTo :\n uniformName === 'u_pixel_ratio_from' ? this.pixelRatioFrom : null;\n if (pos) uniform.set(pos);\n }\n\n getBinding(context: Context, location: WebGLUniformLocation, name: string): $Shape> {\n return name.substr(0, 9) === 'u_pattern' ?\n new Uniform4f(context, location) :\n new Uniform1f(context, location);\n }\n}\n\nclass SourceExpressionBinder implements AttributeBinder {\n expression: SourceExpression;\n type: string;\n maxValue: number;\n\n paintVertexArray: StructArray;\n paintVertexAttributes: Array;\n paintVertexBuffer: ?VertexBuffer;\n\n constructor(expression: SourceExpression, names: Array, type: string, PaintVertexArray: Class) {\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: {[_: string]: ImagePosition}, canonical?: CanonicalTileID, formattedSection?: FormattedSection) {\n const start = this.paintVertexArray.length;\n const value = this.expression.evaluate(new EvaluationParameters(0), feature, {}, canonical, [], formattedSection);\n this.paintVertexArray.resize(newLength);\n this._setPaintValue(start, newLength, value);\n }\n\n updatePaintArray(start: number, end: number, feature: Feature, featureState: FeatureState) {\n const value = this.expression.evaluate({zoom: 0}, feature, featureState);\n this._setPaintValue(start, end, value);\n }\n\n _setPaintValue(start, end, value) {\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;\n type: string;\n useIntegerZoom: boolean;\n zoom: number;\n maxValue: number;\n\n paintVertexArray: StructArray;\n paintVertexAttributes: Array;\n paintVertexBuffer: ?VertexBuffer;\n\n constructor(expression: CompositeExpression, names: Array, type: string, useIntegerZoom: boolean, zoom: number, PaintVertexArray: Class) {\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: {[_: string]: ImagePosition}, canonical?: CanonicalTileID, formattedSection?: FormattedSection) {\n const min = this.expression.evaluate(new EvaluationParameters(this.zoom), feature, {}, canonical, [], formattedSection);\n const max = this.expression.evaluate(new EvaluationParameters(this.zoom + 1), feature, {}, canonical, [], 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) {\n const min = this.expression.evaluate({zoom: this.zoom}, feature, featureState);\n const max = this.expression.evaluate({zoom: this.zoom + 1}, feature, featureState);\n this._setPaintValue(start, end, min, max);\n }\n\n _setPaintValue(start, end, min, max) {\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(uniform: Uniform<*>, globals: GlobalProperties): 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(factor);\n }\n\n getBinding(context: Context, location: WebGLUniformLocation, _: string): Uniform1f {\n return new Uniform1f(context, location);\n }\n}\n\nclass CrossFadedCompositeBinder implements AttributeBinder {\n expression: CompositeExpression;\n type: string;\n useIntegerZoom: boolean;\n zoom: number;\n layerId: string;\n\n zoomInPaintVertexArray: StructArray;\n zoomOutPaintVertexArray: StructArray;\n zoomInPaintVertexBuffer: ?VertexBuffer;\n zoomOutPaintVertexBuffer: ?VertexBuffer;\n paintVertexAttributes: Array;\n\n constructor(expression: CompositeExpression, type: string, useIntegerZoom: boolean, zoom: number, PaintVertexArray: Class, layerId: string) {\n this.expression = expression;\n this.type = type;\n this.useIntegerZoom = useIntegerZoom;\n this.zoom = zoom;\n this.layerId = layerId;\n\n this.zoomInPaintVertexArray = new PaintVertexArray();\n this.zoomOutPaintVertexArray = new PaintVertexArray();\n }\n\n populatePaintArray(length: number, feature: Feature, imagePositions: {[_: string]: ImagePosition}) {\n const start = this.zoomInPaintVertexArray.length;\n this.zoomInPaintVertexArray.resize(length);\n this.zoomOutPaintVertexArray.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, imagePositions: {[_: string]: ImagePosition}) {\n this._setPaintValues(start, end, feature.patterns && feature.patterns[this.layerId], imagePositions);\n }\n\n _setPaintValues(start, end, patterns, positions) {\n if (!positions || !patterns) return;\n\n const {min, mid, max} = patterns;\n const imageMin = positions[min];\n const imageMid = positions[mid];\n const imageMax = positions[max];\n if (!imageMin || !imageMid || !imageMax) return;\n\n // We populate two paint arrays because, for cross-faded properties, we don't know which direction\n // we're cross-fading to at layout time. In order to keep vertex attributes to a minimum and not pass\n // unnecessary vertex data to the shaders, we determine which to upload at draw time.\n for (let i = start; i < end; i++) {\n this.zoomInPaintVertexArray.emplace(i,\n imageMid.tl[0], imageMid.tl[1], imageMid.br[0], imageMid.br[1],\n imageMin.tl[0], imageMin.tl[1], imageMin.br[0], imageMin.br[1],\n imageMid.pixelRatio,\n imageMin.pixelRatio,\n );\n this.zoomOutPaintVertexArray.emplace(i,\n imageMid.tl[0], imageMid.tl[1], imageMid.br[0], imageMid.br[1],\n imageMax.tl[0], imageMax.tl[1], imageMax.br[0], imageMax.br[1],\n imageMid.pixelRatio,\n imageMax.pixelRatio,\n );\n }\n }\n\n upload(context: Context) {\n if (this.zoomInPaintVertexArray && this.zoomInPaintVertexArray.arrayBuffer && this.zoomOutPaintVertexArray && this.zoomOutPaintVertexArray.arrayBuffer) {\n this.zoomInPaintVertexBuffer = context.createVertexBuffer(this.zoomInPaintVertexArray, patternAttributes.members, this.expression.isStateDependent);\n this.zoomOutPaintVertexBuffer = context.createVertexBuffer(this.zoomOutPaintVertexArray, patternAttributes.members, this.expression.isStateDependent);\n }\n }\n\n destroy() {\n if (this.zoomOutPaintVertexBuffer) this.zoomOutPaintVertexBuffer.destroy();\n if (this.zoomInPaintVertexBuffer) this.zoomInPaintVertexBuffer.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;\n\n constructor(layer: TypedStyleLayer, zoom: number, filterProperties: (_: string) => boolean) {\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 propType = value.property.specification['property-type'];\n const isCrossFaded = propType === 'cross-faded' || propType === 'cross-faded-data-driven';\n\n if (expression.kind === 'constant') {\n this.binders[property] = isCrossFaded ?\n new CrossFadedConstantBinder(expression.value, names) :\n new ConstantBinder(expression.value, names, type);\n keys.push(`/u_${property}`);\n\n } else if (expression.kind === 'source' || isCrossFaded) {\n const StructArrayLayout = layoutType(property, type, 'source');\n this.binders[property] = isCrossFaded ?\n new CrossFadedCompositeBinder(expression, type, useIntegerZoom, zoom, StructArrayLayout, layer.id) :\n new SourceExpressionBinder(expression, names, type, StructArrayLayout);\n keys.push(`/a_${property}`);\n\n } else {\n const StructArrayLayout = layoutType(property, type, 'composite');\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: {[_: string]: ImagePosition}, 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 CrossFadedCompositeBinder)\n (binder: AttributeBinder).populatePaintArray(newLength, feature, imagePositions, canonical, formattedSection);\n }\n }\n setConstantPatternPositions(posTo: ImagePosition, posFrom: ImagePosition) {\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof CrossFadedConstantBinder)\n binder.setConstantPatternPositions(posTo, posFrom);\n }\n }\n\n updatePaintArrays(featureStates: FeatureStates, featureMap: FeaturePositionMap, vtLayer: VectorTileLayer, layer: TypedStyleLayer, imagePositions: {[_: string]: ImagePosition}): 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 CrossFadedCompositeBinder) && (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], imagePositions);\n dirty = true;\n }\n }\n }\n }\n return dirty;\n }\n\n defines(): Array {\n const result = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder) {\n result.push(...binder.uniformNames.map(name => `#define HAS_UNIFORM_${name}`));\n }\n }\n return result;\n }\n\n getBinderAttributes(): Array {\n const result = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) {\n for (let i = 0; i < binder.paintVertexAttributes.length; i++) {\n result.push(binder.paintVertexAttributes[i].name);\n }\n } else if (binder instanceof CrossFadedCompositeBinder) {\n for (let i = 0; i < patternAttributes.members.length; i++) {\n result.push(patternAttributes.members[i].name);\n }\n }\n }\n return result;\n }\n\n getBinderUniforms(): Array {\n const uniforms = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || 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 {\n return this._buffers;\n }\n\n getUniforms(context: Context, locations: UniformLocations): Array {\n const uniforms = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof ConstantBinder || binder instanceof CrossFadedConstantBinder || binder instanceof CompositeExpressionBinder) {\n for (const name of binder.uniformNames) {\n if (locations[name]) {\n const binding = binder.getBinding(context, locations[name], name);\n uniforms.push({name, property, binding});\n }\n }\n }\n }\n return uniforms;\n }\n\n setUniforms(context: Context, binderUniforms: Array, properties: PossiblyEvaluated, globals: GlobalProperties) {\n // Uniform state bindings are owned by the Program, but we set them\n // from within the ProgramConfiguraton's binder members.\n for (const {name, property, binding} of binderUniforms) {\n (this.binders[property]: any).setUniform(binding, globals, properties.get(property), name);\n }\n }\n\n updatePaintBuffers(crossfade?: CrossfadeParameters) {\n this._buffers = [];\n\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (crossfade && binder instanceof CrossFadedCompositeBinder) {\n const patternVertexBuffer = crossfade.fromScale === 2 ? binder.zoomInPaintVertexBuffer : binder.zoomOutPaintVertexBuffer;\n if (patternVertexBuffer) this._buffers.push(patternVertexBuffer);\n\n } else if ((binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) && 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 CrossFadedCompositeBinder)\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 CrossFadedCompositeBinder)\n binder.destroy();\n }\n }\n}\n\nexport class ProgramConfigurationSet {\n programConfigurations: {[_: string]: ProgramConfiguration};\n needsUpload: boolean;\n _featureMap: FeaturePositionMap;\n _bufferOffset: number;\n\n constructor(layers: $ReadOnlyArray, 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: {[_: string]: ImagePosition}, canonical: CanonicalTileID, formattedSection?: FormattedSection) {\n for (const key in this.programConfigurations) {\n this.programConfigurations[key].populatePaintArrays(length, feature, imagePositions, 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: VectorTileLayer, layers: $ReadOnlyArray, imagePositions: {[_: string]: ImagePosition}) {\n for (const layer of layers) {\n this.needsUpload = this.programConfigurations[layer.id].updatePaintArrays(featureStates, this._featureMap, vtLayer, layer, imagePositions) || this.needsUpload;\n }\n }\n\n get(layerId: string) {\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\nfunction paintAttributeNames(property, type) {\n const 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_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'],\n 'fill-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'],\n 'fill-extrusion-pattern': ['pattern_to', 'pattern_from', 'pixel_ratio_to', 'pixel_ratio_from'],\n };\n\n return attributeNameExceptions[property] || [property.replace(`${type}-`, '').replace(/-/g, '_')];\n}\n\nfunction getLayoutException(property) {\n const 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 };\n\n return propertyExceptions[property];\n}\n\nfunction layoutType(property, type, binderType) {\n const defaultLayouts = {\n 'color': {\n 'source': StructArrayLayout2f8,\n 'composite': StructArrayLayout4f16\n },\n 'number': {\n 'source': StructArrayLayout1f4,\n 'composite': StructArrayLayout2f8\n }\n };\n\n const layoutException = getLayoutException(property);\n return layoutException && layoutException[binderType] || defaultLayouts[type][binderType];\n}\n\nregister('ConstantBinder', ConstantBinder);\nregister('CrossFadedConstantBinder', CrossFadedConstantBinder);\nregister('SourceExpressionBinder', SourceExpressionBinder);\nregister('CrossFadedCompositeBinder', CrossFadedCompositeBinder);\nregister('CompositeExpressionBinder', CompositeExpressionBinder);\nregister('ProgramConfiguration', ProgramConfiguration, {omit: ['_buffers']});\nregister('ProgramConfigurationSet', ProgramConfigurationSet);\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 {warnOnce, clamp} from '../util/util';\n\nimport EXTENT from './extent';\n\nimport type Point from '@mapbox/point-geometry';\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 cordinates 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\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: VectorTileFeature): Array> {\n const scale = EXTENT / feature.extent;\n const geometry = feature.loadGeometry();\n for (let r = 0; r < geometry.length; r++) {\n const ring = geometry[r];\n for (let p = 0; p < ring.length; p++) {\n const point = ring[p];\n // round here because mapbox-gl-native uses integers to represent\n // points and we need to do the same to avoid renering differences.\n const x = Math.round(point.x * scale);\n const y = Math.round(point.y * scale);\n\n point.x = clamp(x, MIN, MAX);\n point.y = clamp(y, MIN, MAX);\n\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 }\n }\n return geometry;\n}\n","// @flow\n\nimport loadGeometry from './load_geometry';\n\ntype EvaluationFeature = {\n +type: 1 | 2 | 3 | 'Unknown' | 'Point' | 'MultiPoint' | 'LineString' | 'MultiLineString' | 'Polygon' | 'MultiPolygon',\n +id?: any,\n +properties: {[_: string]: any},\n +patterns?: {[_: string]: {\"min\": string, \"mid\": string, \"max\": string}},\n geometry: Array>\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: VectorTileFeature, 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} from '../array_types';\n\nimport {members as layoutAttributes} from './circle_attributes';\nimport SegmentVector from '../segment';\nimport {ProgramConfigurationSet} from '../program_configuration';\nimport {TriangleIndexArray} from '../index_array_type';\nimport loadGeometry from '../load_geometry';\nimport toEvaluationFeature from '../evaluation_feature';\nimport EXTENT from '../extent';\nimport {register} from '../../util/web_worker_transfer';\nimport EvaluationParameters from '../../style/evaluation_parameters';\n\nimport type {CanonicalTileID} from '../../source/tile_id';\nimport type {\n Bucket,\n BucketParameters,\n BucketFeature,\n IndexedFeature,\n PopulateParameters\n} from '../bucket';\nimport type CircleStyleLayer from '../../style/style_layer/circle_style_layer';\nimport type HeatmapStyleLayer from '../../style/style_layer/heatmap_style_layer';\nimport type Context from '../../gl/context';\nimport type IndexBuffer from '../../gl/index_buffer';\nimport type VertexBuffer from '../../gl/vertex_buffer';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureStates} from '../../source/source_state';\nimport type {ImagePosition} from '../../render/image_atlas';\n\nfunction addCircleVertex(layoutVertexArray, x, y, extrudeX, extrudeY) {\n layoutVertexArray.emplaceBack(\n (x * 2) + ((extrudeX + 1) / 2),\n (y * 2) + ((extrudeY + 1) / 2));\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 implements Bucket {\n index: number;\n zoom: number;\n overscaling: number;\n layerIds: Array;\n layers: Array;\n stateDependentLayers: Array;\n stateDependentLayerIds: Array;\n\n layoutVertexArray: CircleLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n hasPattern: boolean;\n programConfigurations: ProgramConfigurationSet;\n segments: SegmentVector;\n uploaded: boolean;\n\n constructor(options: BucketParameters) {\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\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, options: PopulateParameters, canonical: CanonicalTileID) {\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 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),\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 for (const bucketFeature of bucketFeatures) {\n const {geometry, index, sourceLayerIndex} = bucketFeature;\n const feature = features[index].feature;\n\n this.addFeature(bucketFeature, geometry, index, canonical);\n options.featureIndex.insert(feature, geometry, index, sourceLayerIndex, this.index);\n }\n }\n\n update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: {[_: string]: ImagePosition}) {\n if (!this.stateDependentLayers.length) return;\n this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions);\n }\n\n isEmpty() {\n return this.layoutVertexArray.length === 0;\n }\n\n uploadPending() {\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 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 addFeature(feature: BucketFeature, geometry: Array>, index: number, canonical: CanonicalTileID) {\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 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 + 3, index + 2);\n\n segment.vertexLength += 4;\n segment.primitiveLength += 2;\n }\n }\n\n this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, {}, canonical);\n }\n}\n\nregister('CircleBucket', CircleBucket, {omit: ['layers']});\n\nexport default CircleBucket;\n","// @flow\n\nimport {isCounterClockwise} from './util';\n\nimport Point from '@mapbox/point-geometry';\n\nexport {polygonIntersectsBufferedPoint, polygonIntersectsMultiPolygon, polygonIntersectsBufferedMultiLine, polygonIntersectsPolygon, distToSegmentSquared, polygonIntersectsBox};\n\ntype Line = Array;\ntype MultiLine = Array;\ntype Ring = Array;\ntype Polygon = Array;\ntype MultiPolygon = Array;\n\nfunction polygonIntersectsPolygon(polygonA: Polygon, polygonB: Polygon) {\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) {\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) {\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) {\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) {\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: Array, 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) {\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) {\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) {\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\";\nimport type StyleLayer from '../style/style_layer';\nimport type CircleBucket from '../data/bucket/circle_bucket';\nimport type LineBucket from '../data/bucket/line_bucket';\n\nexport function getMaximumPaintValue(property: string, layer: StyleLayer, bucket: CircleBucket<*> | LineBucket): number {\n const value = ((layer.paint: any).get(property): PossiblyEvaluatedPropertyValue).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]) {\n return Math.sqrt(translate[0] * translate[0] + translate[1] * translate[1]);\n}\n\nexport function translate(queryGeometry: Array,\n translate: [number, number],\n translateAnchor: 'viewport' | 'map',\n bearing: number,\n pixelsToTileUnits: number) {\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","// 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';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image';\n\nexport type LayoutProps = {|\n \"circle-sort-key\": DataDrivenProperty,\n|};\n\nconst layout: Properties = new Properties({\n \"circle-sort-key\": new DataDrivenProperty(styleSpec[\"layout_circle\"][\"circle-sort-key\"]),\n});\n\nexport type PaintProps = {|\n \"circle-radius\": DataDrivenProperty,\n \"circle-color\": DataDrivenProperty,\n \"circle-blur\": DataDrivenProperty,\n \"circle-opacity\": DataDrivenProperty,\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,\n \"circle-stroke-color\": DataDrivenProperty,\n \"circle-stroke-opacity\": DataDrivenProperty,\n|};\n\nconst paint: Properties = 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, layout: Properties\n}>);\n","/**\r\n * Common utilities\r\n * @module glMatrix\r\n */\n// Configuration Constants\nexport var EPSILON = 0.000001;\nexport var ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array;\nexport var RANDOM = Math.random;\n/**\r\n * Sets the type of array used when creating new vectors and matrices\r\n *\r\n * @param {Type} type Array type, such as Float32Array or Array\r\n */\n\nexport function setMatrixArrayType(type) {\n ARRAY_TYPE = type;\n}\nvar degree = Math.PI / 180;\n/**\r\n * Convert Degree To Radian\r\n *\r\n * @param {Number} a Angle in Degrees\r\n */\n\nexport function toRadian(a) {\n return a * degree;\n}\n/**\r\n * Tests whether or not the arguments have approximately the same value, within an absolute\r\n * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less\r\n * than or equal to 1.0, and a relative tolerance is used for larger values)\r\n *\r\n * @param {Number} a The first number to test.\r\n * @param {Number} b The second number to test.\r\n * @returns {Boolean} True if the numbers are approximately equal, false otherwise.\r\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/**\r\n * 4x4 Matrix
Format: column-major, when typed out it looks like row-major
The matrices are being post multiplied.\r\n * @module mat4\r\n */\n\n/**\r\n * Creates a new identity mat4\r\n *\r\n * @returns {mat4} a new 4x4 matrix\r\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/**\r\n * Creates a new mat4 initialized with values from an existing matrix\r\n *\r\n * @param {mat4} a matrix to clone\r\n * @returns {mat4} a new 4x4 matrix\r\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/**\r\n * Copy the values from one mat4 to another\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the source matrix\r\n * @returns {mat4} out\r\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/**\r\n * Create a new mat4 with the given values\r\n *\r\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\r\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\r\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\r\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\r\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\r\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\r\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\r\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\r\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\r\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\r\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\r\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\r\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\r\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\r\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\r\n * @returns {mat4} A new mat4\r\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/**\r\n * Set the components of a mat4 to the given values\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {Number} m00 Component in column 0, row 0 position (index 0)\r\n * @param {Number} m01 Component in column 0, row 1 position (index 1)\r\n * @param {Number} m02 Component in column 0, row 2 position (index 2)\r\n * @param {Number} m03 Component in column 0, row 3 position (index 3)\r\n * @param {Number} m10 Component in column 1, row 0 position (index 4)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 5)\r\n * @param {Number} m12 Component in column 1, row 2 position (index 6)\r\n * @param {Number} m13 Component in column 1, row 3 position (index 7)\r\n * @param {Number} m20 Component in column 2, row 0 position (index 8)\r\n * @param {Number} m21 Component in column 2, row 1 position (index 9)\r\n * @param {Number} m22 Component in column 2, row 2 position (index 10)\r\n * @param {Number} m23 Component in column 2, row 3 position (index 11)\r\n * @param {Number} m30 Component in column 3, row 0 position (index 12)\r\n * @param {Number} m31 Component in column 3, row 1 position (index 13)\r\n * @param {Number} m32 Component in column 3, row 2 position (index 14)\r\n * @param {Number} m33 Component in column 3, row 3 position (index 15)\r\n * @returns {mat4} out\r\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/**\r\n * Set a mat4 to the identity matrix\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @returns {mat4} out\r\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/**\r\n * Transpose the values of a mat4\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the source matrix\r\n * @returns {mat4} out\r\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/**\r\n * Inverts a mat4\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the source matrix\r\n * @returns {mat4} out\r\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/**\r\n * Calculates the adjugate of a mat4\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the source matrix\r\n * @returns {mat4} out\r\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/**\r\n * Calculates the determinant of a mat4\r\n *\r\n * @param {mat4} a the source matrix\r\n * @returns {Number} determinant of a\r\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/**\r\n * Multiplies two mat4s\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the first operand\r\n * @param {mat4} b the second operand\r\n * @returns {mat4} out\r\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/**\r\n * Translate a mat4 by the given vector\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the matrix to translate\r\n * @param {vec3} v vector to translate by\r\n * @returns {mat4} out\r\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/**\r\n * Scales the mat4 by the dimensions in the given vec3 not using vectorization\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the matrix to scale\r\n * @param {vec3} v the vec3 to scale the matrix by\r\n * @returns {mat4} out\r\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/**\r\n * Rotates a mat4 by the given angle around the given axis\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @param {vec3} axis the axis to rotate around\r\n * @returns {mat4} out\r\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/**\r\n * Rotates a matrix by the given angle around the X axis\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\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/**\r\n * Rotates a matrix by the given angle around the Y axis\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\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/**\r\n * Rotates a matrix by the given angle around the Z axis\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from a vector translation\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.translate(dest, dest, vec);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {vec3} v Translation vector\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from a vector scaling\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.scale(dest, dest, vec);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {vec3} v Scaling vector\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from a given angle around a given axis\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.rotate(dest, dest, rad, axis);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @param {vec3} axis the axis to rotate around\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from the given angle around the X axis\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.rotateX(dest, dest, rad);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from the given angle around the Y axis\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.rotateY(dest, dest, rad);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from the given angle around the Z axis\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.rotateZ(dest, dest, rad);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from a quaternion rotation and vector translation\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.translate(dest, vec);\r\n * let quatMat = mat4.create();\r\n * quat4.toMat4(quat, quatMat);\r\n * mat4.multiply(dest, quatMat);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {quat4} q Rotation quaternion\r\n * @param {vec3} v Translation vector\r\n * @returns {mat4} out\r\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/**\r\n * Creates a new mat4 from a dual quat.\r\n *\r\n * @param {mat4} out Matrix\r\n * @param {quat2} a Dual Quaternion\r\n * @returns {mat4} mat4 receiving operation result\r\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/**\r\n * Returns the translation vector component of a transformation\r\n * matrix. If a matrix is built with fromRotationTranslation,\r\n * the returned vector will be the same as the translation vector\r\n * originally supplied.\r\n * @param {vec3} out Vector to receive translation component\r\n * @param {mat4} mat Matrix to be decomposed (input)\r\n * @return {vec3} out\r\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/**\r\n * Returns the scaling factor component of a transformation\r\n * matrix. If a matrix is built with fromRotationTranslationScale\r\n * with a normalized Quaternion paramter, the returned vector will be\r\n * the same as the scaling vector\r\n * originally supplied.\r\n * @param {vec3} out Vector to receive scaling factor component\r\n * @param {mat4} mat Matrix to be decomposed (input)\r\n * @return {vec3} out\r\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/**\r\n * Returns a quaternion representing the rotational component\r\n * of a transformation matrix. If a matrix is built with\r\n * fromRotationTranslation, the returned quaternion will be the\r\n * same as the quaternion originally supplied.\r\n * @param {quat} out Quaternion to receive the rotation component\r\n * @param {mat4} mat Matrix to be decomposed (input)\r\n * @return {quat} out\r\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/**\r\n * Creates a matrix from a quaternion rotation, vector translation and vector scale\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.translate(dest, vec);\r\n * let quatMat = mat4.create();\r\n * quat4.toMat4(quat, quatMat);\r\n * mat4.multiply(dest, quatMat);\r\n * mat4.scale(dest, scale)\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {quat4} q Rotation quaternion\r\n * @param {vec3} v Translation vector\r\n * @param {vec3} s Scaling vector\r\n * @returns {mat4} out\r\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/**\r\n * Creates a matrix from a quaternion rotation, vector translation and vector scale, rotating and scaling around the given origin\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat4.identity(dest);\r\n * mat4.translate(dest, vec);\r\n * mat4.translate(dest, origin);\r\n * let quatMat = mat4.create();\r\n * quat4.toMat4(quat, quatMat);\r\n * mat4.multiply(dest, quatMat);\r\n * mat4.scale(dest, scale)\r\n * mat4.translate(dest, negativeOrigin);\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {quat4} q Rotation quaternion\r\n * @param {vec3} v Translation vector\r\n * @param {vec3} s Scaling vector\r\n * @param {vec3} o The origin vector around which to scale and rotate\r\n * @returns {mat4} out\r\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/**\r\n * Calculates a 4x4 matrix from the given quaternion\r\n *\r\n * @param {mat4} out mat4 receiving operation result\r\n * @param {quat} q Quaternion to create matrix from\r\n *\r\n * @returns {mat4} out\r\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/**\r\n * Generates a frustum matrix with the given bounds\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {Number} left Left bound of the frustum\r\n * @param {Number} right Right bound of the frustum\r\n * @param {Number} bottom Bottom bound of the frustum\r\n * @param {Number} top Top bound of the frustum\r\n * @param {Number} near Near bound of the frustum\r\n * @param {Number} far Far bound of the frustum\r\n * @returns {mat4} out\r\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/**\r\n * Generates a perspective projection matrix with the given bounds.\r\n * Passing null/undefined/no value for far will generate infinite projection matrix.\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {number} fovy Vertical field of view in radians\r\n * @param {number} aspect Aspect ratio. typically viewport width/height\r\n * @param {number} near Near bound of the frustum\r\n * @param {number} far Far bound of the frustum, can be null or Infinity\r\n * @returns {mat4} out\r\n */\n\nexport function perspective(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/**\r\n * Generates a perspective projection matrix with the given field of view.\r\n * This is primarily useful for generating projection matrices to be used\r\n * with the still experiemental WebVR API.\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {Object} fov Object containing the following values: upDegrees, downDegrees, leftDegrees, rightDegrees\r\n * @param {number} near Near bound of the frustum\r\n * @param {number} far Far bound of the frustum\r\n * @returns {mat4} out\r\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/**\r\n * Generates a orthogonal projection matrix with the given bounds\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {number} left Left bound of the frustum\r\n * @param {number} right Right bound of the frustum\r\n * @param {number} bottom Bottom bound of the frustum\r\n * @param {number} top Top bound of the frustum\r\n * @param {number} near Near bound of the frustum\r\n * @param {number} far Far bound of the frustum\r\n * @returns {mat4} out\r\n */\n\nexport function ortho(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/**\r\n * Generates a look-at matrix with the given eye position, focal point, and up axis.\r\n * If you want a matrix that actually makes an object look at another object, you should use targetTo instead.\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {vec3} eye Position of the viewer\r\n * @param {vec3} center Point the viewer is looking at\r\n * @param {vec3} up vec3 pointing up\r\n * @returns {mat4} out\r\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/**\r\n * Generates a matrix that makes something look at something else.\r\n *\r\n * @param {mat4} out mat4 frustum matrix will be written into\r\n * @param {vec3} eye Position of the viewer\r\n * @param {vec3} center Point the viewer is looking at\r\n * @param {vec3} up vec3 pointing up\r\n * @returns {mat4} out\r\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/**\r\n * Returns a string representation of a mat4\r\n *\r\n * @param {mat4} a matrix to represent as a string\r\n * @returns {String} string representation of the matrix\r\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/**\r\n * Returns Frobenius norm of a mat4\r\n *\r\n * @param {mat4} a the matrix to calculate Frobenius norm of\r\n * @returns {Number} Frobenius norm\r\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/**\r\n * Adds two mat4's\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the first operand\r\n * @param {mat4} b the second operand\r\n * @returns {mat4} out\r\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/**\r\n * Subtracts matrix b from matrix a\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the first operand\r\n * @param {mat4} b the second operand\r\n * @returns {mat4} out\r\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/**\r\n * Multiply each element of the matrix by a scalar.\r\n *\r\n * @param {mat4} out the receiving matrix\r\n * @param {mat4} a the matrix to scale\r\n * @param {Number} b amount to scale the matrix's elements by\r\n * @returns {mat4} out\r\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/**\r\n * Adds two mat4's after multiplying each element of the second operand by a scalar value.\r\n *\r\n * @param {mat4} out the receiving vector\r\n * @param {mat4} a the first operand\r\n * @param {mat4} b the second operand\r\n * @param {Number} scale the amount to scale b's elements by before adding\r\n * @returns {mat4} out\r\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/**\r\n * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {mat4} a The first matrix.\r\n * @param {mat4} b The second matrix.\r\n * @returns {Boolean} True if the matrices are equal, false otherwise.\r\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/**\r\n * Returns whether or not the matrices have approximately the same elements in the same position.\r\n *\r\n * @param {mat4} a The first matrix.\r\n * @param {mat4} b The second matrix.\r\n * @returns {Boolean} True if the matrices are equal, false otherwise.\r\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/**\r\n * Alias for {@link mat4.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link mat4.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;","import * as glMatrix from \"./common.js\";\n/**\r\n * 4 Dimensional Vector\r\n * @module vec4\r\n */\n\n/**\r\n * Creates a new, empty vec4\r\n *\r\n * @returns {vec4} a new 4D vector\r\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/**\r\n * Creates a new vec4 initialized with values from an existing vector\r\n *\r\n * @param {vec4} a vector to clone\r\n * @returns {vec4} a new 4D vector\r\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/**\r\n * Creates a new vec4 initialized with the given values\r\n *\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @param {Number} z Z component\r\n * @param {Number} w W component\r\n * @returns {vec4} a new 4D vector\r\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/**\r\n * Copy the values from one vec4 to another\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the source vector\r\n * @returns {vec4} out\r\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/**\r\n * Set the components of a vec4 to the given values\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @param {Number} z Z component\r\n * @param {Number} w W component\r\n * @returns {vec4} out\r\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/**\r\n * Adds two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\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/**\r\n * Subtracts vector b from vector a\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\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/**\r\n * Multiplies two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\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/**\r\n * Divides two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\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/**\r\n * Math.ceil the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to ceil\r\n * @returns {vec4} out\r\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/**\r\n * Math.floor the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to floor\r\n * @returns {vec4} out\r\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/**\r\n * Returns the minimum of two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\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/**\r\n * Returns the maximum of two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {vec4} out\r\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/**\r\n * Math.round the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to round\r\n * @returns {vec4} out\r\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/**\r\n * Scales a vec4 by a scalar number\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the vector to scale\r\n * @param {Number} b amount to scale the vector by\r\n * @returns {vec4} out\r\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/**\r\n * Adds two vec4's after scaling the second operand by a scalar value\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @param {Number} scale the amount to scale b by before adding\r\n * @returns {vec4} out\r\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/**\r\n * Calculates the euclidian distance between two vec4's\r\n *\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {Number} distance between a and b\r\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/**\r\n * Calculates the squared euclidian distance between two vec4's\r\n *\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {Number} squared distance between a and b\r\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/**\r\n * Calculates the length of a vec4\r\n *\r\n * @param {vec4} a vector to calculate length of\r\n * @returns {Number} length of a\r\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/**\r\n * Calculates the squared length of a vec4\r\n *\r\n * @param {vec4} a vector to calculate squared length of\r\n * @returns {Number} squared length of a\r\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/**\r\n * Negates the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to negate\r\n * @returns {vec4} out\r\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/**\r\n * Returns the inverse of the components of a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to invert\r\n * @returns {vec4} out\r\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/**\r\n * Normalize a vec4\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a vector to normalize\r\n * @returns {vec4} out\r\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/**\r\n * Calculates the dot product of two vec4's\r\n *\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @returns {Number} dot product of a and b\r\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/**\r\n * Returns the cross-product of three vectors in a 4-dimensional space\r\n *\r\n * @param {vec4} result the receiving vector\r\n * @param {vec4} U the first vector\r\n * @param {vec4} V the second vector\r\n * @param {vec4} W the third vector\r\n * @returns {vec4} result\r\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/**\r\n * Performs a linear interpolation between two vec4's\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the first operand\r\n * @param {vec4} b the second operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec4} out\r\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/**\r\n * Generates a random vector with the given scale\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned\r\n * @returns {vec4} out\r\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/**\r\n * Transforms the vec4 with a mat4.\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the vector to transform\r\n * @param {mat4} m matrix to transform with\r\n * @returns {vec4} out\r\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/**\r\n * Transforms the vec4 with a quat\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @param {vec4} a the vector to transform\r\n * @param {quat} q quaternion to transform with\r\n * @returns {vec4} out\r\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/**\r\n * Set the components of a vec4 to zero\r\n *\r\n * @param {vec4} out the receiving vector\r\n * @returns {vec4} out\r\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/**\r\n * Returns a string representation of a vector\r\n *\r\n * @param {vec4} a vector to represent as a string\r\n * @returns {String} string representation of the vector\r\n */\n\nexport function str(a) {\n return \"vec4(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\r\n * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {vec4} a The first vector.\r\n * @param {vec4} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\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/**\r\n * Returns whether or not the vectors have approximately the same elements in the same position.\r\n *\r\n * @param {vec4} a The first vector.\r\n * @param {vec4} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\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/**\r\n * Alias for {@link vec4.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;\n/**\r\n * Alias for {@link vec4.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link vec4.divide}\r\n * @function\r\n */\n\nexport var div = divide;\n/**\r\n * Alias for {@link vec4.distance}\r\n * @function\r\n */\n\nexport var dist = distance;\n/**\r\n * Alias for {@link vec4.squaredDistance}\r\n * @function\r\n */\n\nexport var sqrDist = squaredDistance;\n/**\r\n * Alias for {@link vec4.length}\r\n * @function\r\n */\n\nexport var len = length;\n/**\r\n * Alias for {@link vec4.squaredLength}\r\n * @function\r\n */\n\nexport var sqrLen = squaredLength;\n/**\r\n * Perform some operation over an array of vec4s.\r\n *\r\n * @param {Array} a the array of vectors to iterate over\r\n * @param {Number} stride Number of elements between the start of each vec4. If 0 assumes tightly packed\r\n * @param {Number} offset Number of elements to skip at the beginning of the array\r\n * @param {Number} count Number of vec4s to iterate over. If 0 iterates over entire array\r\n * @param {Function} fn Function to call for each vector in the array\r\n * @param {Object} [arg] additional argument to pass to fn\r\n * @returns {Array} a\r\n * @function\r\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}();","// @flow\n\nimport StyleLayer from '../style_layer';\n\nimport CircleBucket from '../../data/bucket/circle_bucket';\nimport {polygonIntersectsBufferedPoint} from '../../util/intersection_tests';\nimport {getMaximumPaintValue, translateDistance, translate} from '../query_utils';\nimport properties from './circle_style_layer_properties';\nimport {Transitionable, Transitioning, Layout, PossiblyEvaluated} from '../properties';\nimport {vec4} from 'gl-matrix';\nimport Point from '@mapbox/point-geometry';\n\nimport type {FeatureState} from '../../style-spec/expression';\nimport type Transform from '../../geo/transform';\nimport type {Bucket, BucketParameters} from '../../data/bucket';\nimport type {LayoutProps, PaintProps} from './circle_style_layer_properties';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass CircleStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout;\n layout: PossiblyEvaluated;\n\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n createBucket(parameters: BucketParameters<*>) {\n return new CircleBucket(parameters);\n }\n\n queryRadius(bucket: Bucket): number {\n const circleBucket: CircleBucket = (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 queryIntersectsFeature(queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number,\n pixelPosMatrix: Float32Array): boolean {\n const translatedPolygon = translate(queryGeometry,\n this.paint.get('circle-translate'),\n this.paint.get('circle-translate-anchor'),\n transform.angle, pixelsToTileUnits);\n const radius = this.paint.get('circle-radius').evaluate(feature, featureState);\n const stroke = this.paint.get('circle-stroke-width').evaluate(feature, featureState);\n const size = radius + stroke;\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 const alignWithMap = this.paint.get('circle-pitch-alignment') === 'map';\n const transformedPolygon = alignWithMap ? translatedPolygon : projectQueryGeometry(translatedPolygon, pixelPosMatrix);\n const transformedSize = alignWithMap ? size * pixelsToTileUnits : size;\n\n for (const ring of geometry) {\n for (const point of ring) {\n\n const transformedPoint = alignWithMap ? point : projectPoint(point, pixelPosMatrix);\n\n let adjustedSize = transformedSize;\n const projectedCenter = vec4.transformMat4([], [point.x, point.y, 0, 1], pixelPosMatrix);\n if (this.paint.get('circle-pitch-scale') === 'viewport' && this.paint.get('circle-pitch-alignment') === 'map') {\n adjustedSize *= projectedCenter[3] / transform.cameraToCenterDistance;\n } else if (this.paint.get('circle-pitch-scale') === 'map' && this.paint.get('circle-pitch-alignment') === 'viewport') {\n adjustedSize *= transform.cameraToCenterDistance / projectedCenter[3];\n }\n\n if (polygonIntersectsBufferedPoint(transformedPolygon, transformedPoint, adjustedSize)) return true;\n }\n }\n\n return false;\n }\n}\n\nfunction projectPoint(p: Point, pixelPosMatrix: Float32Array) {\n const point = vec4.transformMat4([], [p.x, p.y, 0, 1], pixelPosMatrix);\n return new Point(point[0] / point[3], point[1] / point[3]);\n}\n\nfunction projectQueryGeometry(queryGeometry: Array, pixelPosMatrix: Float32Array) {\n return queryGeometry.map((p) => {\n return projectPoint(p, pixelPosMatrix);\n });\n}\n\nexport default CircleStyleLayer;\n","// @flow\n\nimport CircleBucket from './circle_bucket';\n\nimport {register} from '../../util/web_worker_transfer';\n\nimport type HeatmapStyleLayer from '../../style/style_layer/heatmap_style_layer';\n\nclass HeatmapBucket extends CircleBucket {\n // Needed for flow to accept omit: ['layers'] below, due to\n // https://github.com/facebook/flow/issues/4262\n layers: Array;\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';\n\nexport type Size = {\n width: number,\n height: number\n};\n\ntype Point = {\n x: number,\n y: number\n};\n\nfunction createImage(image: *, {width, height}: Size, channels: number, data?: Uint8Array | Uint8ClampedArray) {\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(image: *, {width, height}: Size, channels: number) {\n if (width === image.width && height === image.height) {\n return;\n }\n\n const newImage = createImage({}, {width, height}, channels);\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(srcImg: *, dstImg: *, srcPt: Point, dstPt: Point, size: Size, channels: number) {\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, size, 1);\n }\n\n clone() {\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, 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() {\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';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image';\n\n\nexport type PaintProps = {|\n \"heatmap-radius\": DataDrivenProperty,\n \"heatmap-weight\": DataDrivenProperty,\n \"heatmap-intensity\": DataConstantProperty,\n \"heatmap-color\": ColorRampProperty,\n \"heatmap-opacity\": DataConstantProperty,\n|};\n\nconst paint: Properties = 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\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer';\n\nimport HeatmapBucket from '../../data/bucket/heatmap_bucket';\nimport {RGBAImage} from '../../util/image';\nimport properties from './heatmap_style_layer_properties';\nimport {renderColorRamp} from '../../util/color_ramp';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties';\n\nimport type Texture from '../../render/texture';\nimport type Framebuffer from '../../gl/framebuffer';\nimport type {PaintProps} from './heatmap_style_layer_properties';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass HeatmapStyleLayer extends StyleLayer {\n\n heatmapFbo: ?Framebuffer;\n colorRamp: RGBAImage;\n colorRampTexture: ?Texture;\n\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n createBucket(options: any) {\n return new HeatmapBucket(options);\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 queryRadius(): number {\n return 0;\n }\n\n queryIntersectsFeature(): boolean {\n return false;\n }\n\n hasOffscreenPass() {\n return this.paint.get('heatmap-opacity') !== 0 && this.visibility !== 'none';\n }\n}\n\nexport default HeatmapStyleLayer;\n","// @flow\n\nimport {RGBAImage} from './image';\nimport {isPowerOfTwo} from './util';\nimport assert from 'assert';\n\nimport type {StylePropertyExpression} from '../style-spec/expression/index';\n\nexport type ColorRampParams = {\n expression: StylePropertyExpression;\n evaluationKey: string;\n resolution?: number;\n image?: RGBAImage;\n clips?: Array;\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, index, progress) => {\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';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image';\n\n\nexport type PaintProps = {|\n \"hillshade-illumination-direction\": DataConstantProperty,\n \"hillshade-illumination-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"hillshade-exaggeration\": DataConstantProperty,\n \"hillshade-shadow-color\": DataConstantProperty,\n \"hillshade-highlight-color\": DataConstantProperty,\n \"hillshade-accent-color\": DataConstantProperty,\n|};\n\nconst paint: Properties = 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\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer';\n\nimport properties from './hillshade_style_layer_properties';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties';\n\nimport type {PaintProps} from './hillshade_style_layer_properties';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass HillshadeStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n hasOffscreenPass() {\n return this.paint.get('hillshade-exaggeration') !== 0 && this.visibility !== 'none';\n }\n}\n\nexport default HillshadeStyleLayer;\n","// @flow\nimport {createLayout} from '../../util/struct_array';\n\nconst layout = 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 ? 1 / invSize : 0;\n }\n\n earcutLinked(outerNode, triangles, dim, minX, minY, invSize);\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);\n triangles.push(ear.i / dim);\n triangles.push(next.i / dim);\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 p = ear.next.next;\n\n while (p !== ear.prev) {\n if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, 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 // triangle bbox; min & max are calculated like this for speed\n var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),\n minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),\n maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),\n maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);\n\n // z-order range for the current triangle bbox;\n var minZ = zOrder(minTX, minTY, minX, minY, invSize),\n maxZ = zOrder(maxTX, maxTY, 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 !== ear.prev && p !== ear.next &&\n pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&\n area(p.prev, p, p.next) >= 0) return false;\n p = p.prevZ;\n\n if (n !== ear.prev && n !== ear.next &&\n pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&\n 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 !== ear.prev && p !== ear.next &&\n pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&\n 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 !== ear.prev && n !== ear.next &&\n pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&\n 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);\n triangles.push(p.i / dim);\n triangles.push(b.i / dim);\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);\n earcutLinked(c, triangles, dim, minX, minY, invSize);\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 eliminateHole(queue[i], outerNode);\n outerNode = filterPoints(outerNode, outerNode.next);\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 outerNode = findHoleBridge(hole, outerNode);\n if (outerNode) {\n var b = splitPolygon(outerNode, hole);\n\n // filter collinear points around the cuts\n filterPoints(outerNode, outerNode.next);\n filterPoints(b, b.next);\n }\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 if (x === hx) {\n if (hy === p.y) return p;\n if (hy === p.next.y) return p.next;\n }\n m = p.x < p.next.x ? p : p.next;\n }\n }\n p = p.next;\n } while (p !== outerNode);\n\n if (!m) return null;\n\n if (hx === qx) return m; // hole touches outer segment; pick leftmost endpoint\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 === null) 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 = 32767 * (x - minX) * invSize;\n y = 32767 * (y - minY) * invSize;\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) >= 0 &&\n (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&\n (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;\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 = null;\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';\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>, maxRings: number) {\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, b) {\n return b.area - a.area;\n}\n","// @flow\nimport type FillStyleLayer from '../../style/style_layer/fill_style_layer';\nimport type FillExtrusionStyleLayer from '../../style/style_layer/fill_extrusion_style_layer';\nimport type LineStyleLayer from '../../style/style_layer/line_style_layer';\n\nimport type {\n BucketFeature,\n PopulateParameters\n} from '../bucket';\n\ntype PatternStyleLayers =\n Array |\n Array |\n Array;\n\nexport function hasPattern(type: string, layers: PatternStyleLayers, options: PopulateParameters) {\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.to] = true;\n patterns[constantPattern.from] = true;\n }\n }\n\n return hasPattern;\n}\n\nexport function addPatternDependencies(type: string, layers: PatternStyleLayers, patternFeature: BucketFeature, zoom: number, options: PopulateParameters) {\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 min = patternPropertyValue.evaluate({zoom: zoom - 1}, patternFeature, {}, options.availableImages);\n let mid = patternPropertyValue.evaluate({zoom}, patternFeature, {}, options.availableImages);\n let max = patternPropertyValue.evaluate({zoom: zoom + 1}, patternFeature, {}, options.availableImages);\n min = min && min.name ? min.name : min;\n mid = mid && mid.name ? mid.name : mid;\n max = max && max.name ? max.name : max;\n // add to patternDependencies\n patterns[min] = true;\n patterns[mid] = true;\n patterns[max] = true;\n\n // save for layout\n patternFeature.patterns[layer.id] = {min, mid, max};\n }\n }\n return patternFeature;\n}\n","// @flow\n\nimport {FillLayoutArray} from '../array_types';\n\nimport {members as layoutAttributes} from './fill_attributes';\nimport SegmentVector from '../segment';\nimport {ProgramConfigurationSet} from '../program_configuration';\nimport {LineIndexArray, TriangleIndexArray} from '../index_array_type';\nimport earcut from 'earcut';\nimport classifyRings from '../../util/classify_rings';\nimport assert from 'assert';\nconst EARCUT_MAX_RINGS = 500;\nimport {register} from '../../util/web_worker_transfer';\nimport {hasPattern, addPatternDependencies} from './pattern_bucket_features';\nimport loadGeometry from '../load_geometry';\nimport toEvaluationFeature from '../evaluation_feature';\nimport EvaluationParameters from '../../style/evaluation_parameters';\n\nimport type {CanonicalTileID} from '../../source/tile_id';\nimport type {\n Bucket,\n BucketParameters,\n BucketFeature,\n IndexedFeature,\n PopulateParameters\n} from '../bucket';\nimport type FillStyleLayer from '../../style/style_layer/fill_style_layer';\nimport type Context from '../../gl/context';\nimport type IndexBuffer from '../../gl/index_buffer';\nimport type VertexBuffer from '../../gl/vertex_buffer';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureStates} from '../../source/source_state';\nimport type {ImagePosition} from '../../render/image_atlas';\n\nclass FillBucket implements Bucket {\n index: number;\n zoom: number;\n overscaling: number;\n layers: Array;\n layerIds: Array;\n stateDependentLayers: Array;\n stateDependentLayerIds: Array;\n patternFeatures: Array;\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;\n segments: SegmentVector;\n segments2: SegmentVector;\n uploaded: boolean;\n\n constructor(options: BucketParameters) {\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 }\n\n populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID) {\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 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),\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, {});\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: VectorTileLayer, imagePositions: {[_: string]: ImagePosition}) {\n if (!this.stateDependentLayers.length) return;\n this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions);\n }\n\n addFeatures(options: PopulateParameters, canonical: CanonicalTileID, imagePositions: {[_: string]: ImagePosition}) {\n for (const feature of this.patternFeatures) {\n this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions);\n }\n }\n\n isEmpty() {\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>, index: number, canonical: CanonicalTileID, imagePositions: {[_: string]: ImagePosition}) {\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, 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';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image';\n\nexport type LayoutProps = {|\n \"fill-sort-key\": DataDrivenProperty,\n|};\n\nconst layout: Properties = new Properties({\n \"fill-sort-key\": new DataDrivenProperty(styleSpec[\"layout_fill\"][\"fill-sort-key\"]),\n});\n\nexport type PaintProps = {|\n \"fill-antialias\": DataConstantProperty,\n \"fill-opacity\": DataDrivenProperty,\n \"fill-color\": DataDrivenProperty,\n \"fill-outline-color\": DataDrivenProperty,\n \"fill-translate\": DataConstantProperty<[number, number]>,\n \"fill-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"fill-pattern\": CrossFadedDataDrivenProperty,\n|};\n\nconst paint: Properties = 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 CrossFadedDataDrivenProperty(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, layout: Properties\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer';\n\nimport FillBucket from '../../data/bucket/fill_bucket';\nimport {polygonIntersectsMultiPolygon} from '../../util/intersection_tests';\nimport {translateDistance, translate} from '../query_utils';\nimport properties from './fill_style_layer_properties';\nimport {Transitionable, Transitioning, Layout, PossiblyEvaluated} from '../properties';\n\nimport type {FeatureState} from '../../style-spec/expression';\nimport type {BucketParameters} from '../../data/bucket';\nimport type Point from '@mapbox/point-geometry';\nimport type {LayoutProps, PaintProps} from './fill_style_layer_properties';\nimport type EvaluationParameters from '../evaluation_parameters';\nimport type Transform from '../../geo/transform';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass FillStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout;\n layout: PossiblyEvaluated;\n\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n recalculate(parameters: EvaluationParameters, availableImages: Array) {\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<*>) {\n return new FillBucket(parameters);\n }\n\n queryRadius(): number {\n return translateDistance(this.paint.get('fill-translate'));\n }\n\n queryIntersectsFeature(queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number): boolean {\n const translatedPolygon = translate(queryGeometry,\n this.paint.get('fill-translate'),\n this.paint.get('fill-translate-anchor'),\n transform.angle, pixelsToTileUnits);\n return polygonIntersectsMultiPolygon(translatedPolygon, geometry);\n }\n\n isTileClipped() {\n return true;\n }\n}\n\nexport default FillStyleLayer;\n","// @flow\nimport {createLayout} from '../../util/struct_array';\n\nconst layout = createLayout([\n {name: 'a_pos', components: 2, type: 'Int16'},\n {name: 'a_normal_ed', components: 4, type: 'Int16'},\n], 4);\n\nexport default layout;\nexport const {members, size, alignment} = layout;\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 {FillExtrusionLayoutArray} from '../array_types';\n\nimport {members as layoutAttributes} from './fill_extrusion_attributes';\nimport SegmentVector from '../segment';\nimport {ProgramConfigurationSet} from '../program_configuration';\nimport {TriangleIndexArray} from '../index_array_type';\nimport EXTENT from '../extent';\nimport earcut from 'earcut';\nimport mvt from '@mapbox/vector-tile';\nconst vectorTileFeatureTypes = mvt.VectorTileFeature.types;\nimport classifyRings from '../../util/classify_rings';\nimport assert from 'assert';\nconst EARCUT_MAX_RINGS = 500;\nimport {register} from '../../util/web_worker_transfer';\nimport {hasPattern, addPatternDependencies} from './pattern_bucket_features';\nimport loadGeometry from '../load_geometry';\nimport toEvaluationFeature from '../evaluation_feature';\nimport EvaluationParameters from '../../style/evaluation_parameters';\n\nimport type {CanonicalTileID} from '../../source/tile_id';\nimport type {\n Bucket,\n BucketParameters,\n BucketFeature,\n IndexedFeature,\n PopulateParameters\n} from '../bucket';\n\nimport type FillExtrusionStyleLayer from '../../style/style_layer/fill_extrusion_style_layer';\nimport type Context from '../../gl/context';\nimport type IndexBuffer from '../../gl/index_buffer';\nimport type VertexBuffer from '../../gl/vertex_buffer';\nimport type Point from '@mapbox/point-geometry';\nimport type {FeatureStates} from '../../source/source_state';\nimport type {ImagePosition} from '../../render/image_atlas';\n\nconst FACTOR = Math.pow(2, 13);\n\nfunction addVertex(vertexArray, x, y, nx, ny, nz, t, e) {\n vertexArray.emplaceBack(\n // a_pos\n x,\n y,\n // a_normal_ed: 3-component normal and 1-component edgedistance\n Math.floor(nx * FACTOR) * 2 + t,\n ny * FACTOR * 2,\n nz * FACTOR * 2,\n // edgedistance (used for wrapping patterns around extrusion sides)\n Math.round(e)\n );\n}\n\nclass FillExtrusionBucket implements Bucket {\n index: number;\n zoom: number;\n overscaling: number;\n layers: Array;\n layerIds: Array;\n stateDependentLayers: Array;\n stateDependentLayerIds: Array;\n\n layoutVertexArray: FillExtrusionLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n hasPattern: boolean;\n programConfigurations: ProgramConfigurationSet;\n segments: SegmentVector;\n uploaded: boolean;\n features: Array;\n\n constructor(options: BucketParameters) {\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\n this.layoutVertexArray = new FillExtrusionLayoutArray();\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\n }\n\n populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID) {\n this.features = [];\n this.hasPattern = hasPattern('fill-extrusion', this.layers, options);\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 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),\n properties: feature.properties,\n type: feature.type,\n patterns: {}\n };\n\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, {});\n }\n\n options.featureIndex.insert(feature, bucketFeature.geometry, index, sourceLayerIndex, this.index, true);\n }\n }\n\n addFeatures(options: PopulateParameters, canonical: CanonicalTileID, imagePositions: {[_: string]: ImagePosition}) {\n for (const feature of this.features) {\n const {geometry} = feature;\n this.addFeature(feature, geometry, feature.index, canonical, imagePositions);\n }\n }\n\n update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: {[_: string]: ImagePosition}) {\n if (!this.stateDependentLayers.length) return;\n this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions);\n }\n\n isEmpty() {\n return this.layoutVertexArray.length === 0;\n }\n\n uploadPending() {\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 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 addFeature(feature: BucketFeature, geometry: Array>, index: number, canonical: CanonicalTileID, imagePositions: {[_: string]: ImagePosition}) {\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 let segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray);\n\n for (const ring of polygon) {\n if (ring.length === 0) {\n continue;\n }\n\n if (isEntirelyOutside(ring)) {\n continue;\n }\n\n let edgeDistance = 0;\n\n for (let p = 0; p < ring.length; p++) {\n const p1 = ring[p];\n\n if (p >= 1) {\n const p2 = ring[p - 1];\n\n if (!isBoundaryEdge(p1, p2)) {\n if (segment.vertexLength + 4 > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {\n segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray);\n }\n\n const perp = p1.sub(p2)._perp()._unit();\n const dist = p2.dist(p1);\n if (edgeDistance + dist > 32768) edgeDistance = 0;\n\n addVertex(this.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 0, edgeDistance);\n addVertex(this.layoutVertexArray, p1.x, p1.y, perp.x, perp.y, 0, 1, edgeDistance);\n\n edgeDistance += dist;\n\n addVertex(this.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 0, edgeDistance);\n addVertex(this.layoutVertexArray, p2.x, p2.y, perp.x, perp.y, 0, 1, edgeDistance);\n\n const bottomRight = segment.vertexLength;\n\n // ┌──────┐\n // │ 0 1 │ Counter-clockwise winding order.\n // │ │ Triangle 1: 0 => 2 => 1\n // │ 2 3 │ Triangle 2: 1 => 2 => 3\n // └──────┘\n this.indexArray.emplaceBack(bottomRight, bottomRight + 2, bottomRight + 1);\n this.indexArray.emplaceBack(bottomRight + 1, bottomRight + 2, bottomRight + 3);\n\n segment.vertexLength += 4;\n segment.primitiveLength += 2;\n }\n }\n }\n }\n\n if (segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) {\n segment = this.segments.prepareSegment(numVertices, this.layoutVertexArray, this.indexArray);\n }\n\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 if (vectorTileFeatureTypes[feature.type] !== 'Polygon')\n continue;\n\n const flattened = [];\n const holeIndices = [];\n const triangleIndex = segment.vertexLength;\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 for (let i = 0; i < ring.length; i++) {\n const p = ring[i];\n\n addVertex(this.layoutVertexArray, p.x, p.y, 0, 0, 1, 1, 0);\n\n flattened.push(p.x);\n flattened.push(p.y);\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 // Counter-clockwise winding order.\n this.indexArray.emplaceBack(\n triangleIndex + indices[j],\n triangleIndex + indices[j + 2],\n triangleIndex + indices[j + 1]);\n }\n\n segment.primitiveLength += indices.length / 3;\n segment.vertexLength += numVertices;\n }\n\n this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical);\n }\n}\n\nregister('FillExtrusionBucket', FillExtrusionBucket, {omit: ['layers', 'features']});\n\nexport default FillExtrusionBucket;\n\nfunction isBoundaryEdge(p1, p2) {\n return (p1.x === p2.x && (p1.x < 0 || p1.x > EXTENT)) ||\n (p1.y === p2.y && (p1.y < 0 || p1.y > EXTENT));\n}\n\nfunction isEntirelyOutside(ring) {\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","// 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';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image';\n\n\nexport type PaintProps = {|\n \"fill-extrusion-opacity\": DataConstantProperty,\n \"fill-extrusion-color\": DataDrivenProperty,\n \"fill-extrusion-translate\": DataConstantProperty<[number, number]>,\n \"fill-extrusion-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"fill-extrusion-pattern\": CrossFadedDataDrivenProperty,\n \"fill-extrusion-height\": DataDrivenProperty,\n \"fill-extrusion-base\": DataDrivenProperty,\n \"fill-extrusion-vertical-gradient\": DataConstantProperty,\n|};\n\nconst paint: Properties = 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 CrossFadedDataDrivenProperty(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});\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\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer';\n\nimport FillExtrusionBucket from '../../data/bucket/fill_extrusion_bucket';\nimport {polygonIntersectsPolygon, polygonIntersectsMultiPolygon} from '../../util/intersection_tests';\nimport {translateDistance, translate} from '../query_utils';\nimport properties from './fill_extrusion_style_layer_properties';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties';\nimport {vec4} from 'gl-matrix';\nimport Point from '@mapbox/point-geometry';\n\nimport type {FeatureState} from '../../style-spec/expression';\nimport type {BucketParameters} from '../../data/bucket';\nimport type {PaintProps} from './fill_extrusion_style_layer_properties';\nimport type Transform from '../../geo/transform';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass FillExtrusionStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n createBucket(parameters: BucketParameters) {\n return new FillExtrusionBucket(parameters);\n }\n\n queryRadius(): number {\n return translateDistance(this.paint.get('fill-extrusion-translate'));\n }\n\n is3D(): boolean {\n return true;\n }\n\n queryIntersectsFeature(queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number,\n pixelPosMatrix: Float32Array): boolean | number {\n\n const translatedPolygon = translate(queryGeometry,\n this.paint.get('fill-extrusion-translate'),\n this.paint.get('fill-extrusion-translate-anchor'),\n transform.angle, pixelsToTileUnits);\n\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 projectedQueryGeometry = projectQueryGeometry(translatedPolygon, pixelPosMatrix, transform, 0);\n\n const projected = projectExtrusion(geometry, base, height, pixelPosMatrix);\n const projectedBase = projected[0];\n const projectedTop = projected[1];\n return checkIntersection(projectedBase, projectedTop, projectedQueryGeometry);\n }\n}\n\nfunction dot(a, b) {\n return a.x * b.x + a.y * b.y;\n}\n\nexport function getIntersectionDistance(projectedQueryGeometry: Array, projectedFace: Array) {\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, projectedTop: Array, projectedQueryGeometry: Array) {\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\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 projectExtrusion(geometry: Array>, zBase: number, zTop: number, 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;\n const y = p.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 = sW + baseWZ;\n\n const topX = sX + topXZ;\n const topY = sY + topYZ;\n const topZ = sZ + topZZ;\n const topW = sW + topWZ;\n\n const b = new Point(baseX / baseW, baseY / baseW);\n b.z = baseZ / baseW;\n ringBase.push(b);\n\n const t = new Point(topX / topW, topY / topW);\n t.z = topZ / topW;\n ringTop.push(t);\n }\n projectedBase.push(ringBase);\n projectedTop.push(ringTop);\n }\n return [projectedBase, projectedTop];\n}\n\nfunction projectQueryGeometry(queryGeometry: Array, pixelPosMatrix: Float32Array, transform: Transform, z: number) {\n const projectedQueryGeometry = [];\n for (const p of queryGeometry) {\n const v = [p.x, p.y, z, 1];\n vec4.transformMat4(v, v, pixelPosMatrix);\n projectedQueryGeometry.push(new Point(v[0] / v[3], v[1] / v[3]));\n }\n return projectedQueryGeometry;\n}\n\nexport default FillExtrusionStyleLayer;\n","// @flow\nimport {createLayout} from '../../util/struct_array';\n\nconst lineLayoutAttributes = createLayout([\n {name: 'a_pos_normal', components: 2, type: 'Int16'},\n {name: 'a_data', components: 4, type: 'Uint8'}\n], 4);\n\nexport default lineLayoutAttributes;\nexport const {members, size, alignment} = lineLayoutAttributes;\n","// @flow\nimport {createLayout} from '../../util/struct_array';\n\nconst lineLayoutAttributesExt = createLayout([\n {name: 'a_uv_x', components: 1, type: 'Float32'},\n {name: 'a_split_index', components: 1, type: 'Float32'},\n]);\n\nexport default lineLayoutAttributesExt;\nexport const {members, size, alignment} = lineLayoutAttributesExt;\n","// @flow\n\nimport {LineLayoutArray, LineExtLayoutArray} from '../array_types';\n\nimport {members as layoutAttributes} from './line_attributes';\nimport {members as layoutAttributesExt} from './line_attributes_ext';\nimport SegmentVector from '../segment';\nimport {ProgramConfigurationSet} from '../program_configuration';\nimport {TriangleIndexArray} from '../index_array_type';\nimport EXTENT from '../extent';\nimport mvt from '@mapbox/vector-tile';\nconst vectorTileFeatureTypes = mvt.VectorTileFeature.types;\nimport {register} from '../../util/web_worker_transfer';\nimport {hasPattern, addPatternDependencies} from './pattern_bucket_features';\nimport loadGeometry from '../load_geometry';\nimport toEvaluationFeature from '../evaluation_feature';\nimport EvaluationParameters from '../../style/evaluation_parameters';\n\nimport type {CanonicalTileID} from '../../source/tile_id';\nimport type {\n Bucket,\n BucketParameters,\n BucketFeature,\n IndexedFeature,\n PopulateParameters\n} from '../bucket';\nimport type LineStyleLayer from '../../style/style_layer/line_style_layer';\nimport type Point from '@mapbox/point-geometry';\nimport type {Segment} from '../segment';\nimport {RGBAImage} from '../../util/image';\nimport type Context from '../../gl/context';\nimport type Texture from '../../render/texture';\nimport type IndexBuffer from '../../gl/index_buffer';\nimport type VertexBuffer from '../../gl/vertex_buffer';\nimport type {FeatureStates} from '../../source/source_state';\nimport type {ImagePosition} from '../../render/image_atlas';\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\n// The number of bits that is used to store the line distance in the buffer.\nconst LINE_DISTANCE_BUFFER_BITS = 15;\n\n// We don't have enough bits for the line distance as we'd like to have, so\n// use this value to scale the line distance (in tile units) down to a smaller\n// value. This lets us store longer distances while sacrificing precision.\nconst LINE_DISTANCE_SCALE = 1 / 2;\n\n// The maximum line distance, in tile units, that fits in the buffer.\nconst MAX_LINE_DISTANCE = Math.pow(2, LINE_DISTANCE_BUFFER_BITS - 1) / LINE_DISTANCE_SCALE;\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 lineClips: ?LineClips;\n\n e1: number;\n e2: number;\n\n index: number;\n zoom: number;\n overscaling: number;\n layers: Array;\n layerIds: Array;\n gradients: {[string]: GradientTexture};\n stateDependentLayers: Array;\n stateDependentLayerIds: Array;\n patternFeatures: Array;\n lineClipsArray: Array;\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;\n segments: SegmentVector;\n uploaded: boolean;\n\n constructor(options: BucketParameters) {\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 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, options: PopulateParameters, canonical: CanonicalTileID) {\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 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),\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 for (const bucketFeature of bucketFeatures) {\n const {geometry, index, sourceLayerIndex} = bucketFeature;\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 } else {\n this.addFeature(bucketFeature, geometry, index, canonical, {});\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: VectorTileLayer, imagePositions: {[_: string]: ImagePosition}) {\n if (!this.stateDependentLayers.length) return;\n this.programConfigurations.updatePaintArrays(states, vtLayer, this.stateDependentLayers, imagePositions);\n }\n\n addFeatures(options: PopulateParameters, canonical: CanonicalTileID, imagePositions: {[_: string]: ImagePosition}) {\n for (const feature of this.patternFeatures) {\n this.addFeature(feature, feature.geometry, feature.index, canonical, imagePositions);\n }\n }\n\n isEmpty() {\n return this.layoutVertexArray.length === 0;\n }\n\n uploadPending() {\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>, index: number, canonical: CanonicalTileID, imagePositions: {[_: string]: ImagePosition}) {\n const layout = this.layers[0].layout;\n const join = layout.get('line-join').evaluate(feature, {});\n const cap = layout.get('line-cap');\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, canonical);\n }\n\n addLine(vertices: Array, feature: BucketFeature, join: string, cap: string, miterLimit: number, roundLimit: number) {\n this.distance = 0;\n this.scaledDistance = 0;\n this.totalDistance = 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 this.addCurrentVertex(currentVertex, joinNormal, offset, offset, segment);\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 // There is a maximum \"distance along the line\" that we can store in the buffers.\n // When we get close to the distance, reset it to zero and add the vertex again with\n // a distance of zero. The max distance is determined by the number of bits we allocate\n // to `linesofar`.\n if (this.distance > MAX_LINE_DISTANCE / 2 && this.totalDistance === 0) {\n this.distance = 0;\n this.addCurrentVertex(p, normal, endLeft, endRight, segment, round);\n }\n }\n\n addHalfVertex({x, y}: Point, extrudeX: number, extrudeY: number, round: boolean, up: boolean, dir: number, segment: Segment) {\n const totalDistance = this.lineClips ? this.scaledDistance * (MAX_LINE_DISTANCE - 1) : this.scaledDistance;\n // scale down so that we can store longer distances while sacrificing precision.\n const linesofarScaled = totalDistance * LINE_DISTANCE_SCALE;\n\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 // Encode the -1/0/1 direction value into the first two bits of .z of a_data.\n // Combine it with the lower 6 bits of `linesofarScaled` (shifted by 2 bits to make\n // room for the direction value). The upper 8 bits of `linesofarScaled` are placed in\n // the `w` component.\n ((dir === 0 ? 0 : (dir < 0 ? -1 : 1)) + 1) | ((linesofarScaled & 0x3F) << 2),\n linesofarScaled >> 6);\n\n // Constructs a second vertex buffer with higher precision line progress\n if (this.lineClips) {\n const progressRealigned = this.scaledDistance - this.lineClips.start;\n const endClipRealigned = this.lineClips.end - this.lineClips.start;\n const uvX = progressRealigned / endClipRealigned;\n this.layoutVertexArray2.emplaceBack(uvX, this.lineClipsArray.length);\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 and scale it to [0, 2^15)\n this.scaledDistance = this.lineClips ?\n this.lineClips.start + (this.lineClips.end - this.lineClips.start) * this.distance / this.totalDistance :\n this.distance;\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';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image';\n\nexport type LayoutProps = {|\n \"line-cap\": DataConstantProperty<\"butt\" | \"round\" | \"square\">,\n \"line-join\": DataDrivenProperty<\"bevel\" | \"round\" | \"miter\">,\n \"line-miter-limit\": DataConstantProperty,\n \"line-round-limit\": DataConstantProperty,\n \"line-sort-key\": DataDrivenProperty,\n|};\n\nconst layout: Properties = new Properties({\n \"line-cap\": new DataConstantProperty(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,\n \"line-color\": DataDrivenProperty,\n \"line-translate\": DataConstantProperty<[number, number]>,\n \"line-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"line-width\": DataDrivenProperty,\n \"line-gap-width\": DataDrivenProperty,\n \"line-offset\": DataDrivenProperty,\n \"line-blur\": DataDrivenProperty,\n \"line-dasharray\": CrossFadedProperty>,\n \"line-pattern\": CrossFadedDataDrivenProperty,\n \"line-gradient\": ColorRampProperty,\n|};\n\nconst paint: Properties = 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 CrossFadedProperty(styleSpec[\"paint_line\"][\"line-dasharray\"]),\n \"line-pattern\": new CrossFadedDataDrivenProperty(styleSpec[\"paint_line\"][\"line-pattern\"]),\n \"line-gradient\": new ColorRampProperty(styleSpec[\"paint_line\"][\"line-gradient\"]),\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, layout: Properties\n}>);\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport StyleLayer from '../style_layer';\nimport LineBucket from '../../data/bucket/line_bucket';\nimport {polygonIntersectsBufferedMultiLine} from '../../util/intersection_tests';\nimport {getMaximumPaintValue, translateDistance, translate} from '../query_utils';\nimport properties from './line_style_layer_properties';\nimport {extend, MAX_SAFE_INTEGER} from '../../util/util';\nimport EvaluationParameters from '../evaluation_parameters';\nimport {Transitionable, Transitioning, Layout, PossiblyEvaluated, DataDrivenProperty} from '../properties';\n\nimport Step from '../../style-spec/expression/definitions/step';\nimport type {FeatureState, ZoomConstantExpression} from '../../style-spec/expression';\nimport type {Bucket, BucketParameters} from '../../data/bucket';\nimport type {LayoutProps, PaintProps} from './line_style_layer_properties';\nimport type Transform from '../../geo/transform';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass LineFloorwidthProperty extends DataDrivenProperty {\n useIntegerZoom: true;\n\n possiblyEvaluate(value, parameters) {\n parameters = new EvaluationParameters(Math.floor(parameters.zoom), {\n now: parameters.now,\n fadeDuration: parameters.fadeDuration,\n zoomHistory: parameters.zoomHistory,\n transition: parameters.transition\n });\n return super.possiblyEvaluate(value, parameters);\n }\n\n evaluate(value, globals, feature, featureState) {\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;\n layout: PossiblyEvaluated;\n\n gradientVersion: number;\n stepInterpolant: boolean;\n\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\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 instanceof Step;\n this.gradientVersion = (this.gradientVersion + 1) % MAX_SAFE_INTEGER;\n }\n }\n\n gradientExpression() {\n return this._transitionablePaint._values['line-gradient'].value.expression;\n }\n\n recalculate(parameters: EvaluationParameters, availableImages: Array) {\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<*>) {\n return new LineBucket(parameters);\n }\n\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 queryIntersectsFeature(queryGeometry: Array,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array>,\n zoom: number,\n transform: Transform,\n pixelsToTileUnits: number): boolean {\n const translatedPolygon = translate(queryGeometry,\n this.paint.get('line-translate'),\n this.paint.get('line-translate-anchor'),\n transform.angle, pixelsToTileUnits);\n const halfWidth = pixelsToTileUnits / 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 * pixelsToTileUnits);\n }\n\n return polygonIntersectsBufferedMultiLine(translatedPolygon, geometry, halfWidth);\n }\n\n isTileClipped() {\n return true;\n }\n}\n\nexport default LineStyleLayer;\n\nfunction getLineWidth(lineWidth, lineGapWidth) {\n if (lineGapWidth > 0) {\n return lineGapWidth + 2 * lineWidth;\n } else {\n return lineWidth;\n }\n}\n\nfunction offsetLine(rings, offset) {\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\n\nimport {createLayout} from '../../util/struct_array';\n\nexport const symbolLayoutAttributes = createLayout([\n {name: 'a_pos_offset', components: 4, type: 'Int16'},\n {name: 'a_data', components: 4, type: 'Uint16'},\n {name: 'a_pixeloffset', components: 4, type: 'Int16'}\n], 4);\n\nexport const dynamicLayoutAttributes = createLayout([\n {name: 'a_projected_pos', components: 3, type: 'Float32'}\n], 4);\n\nexport const placementOpacityAttributes = createLayout([\n {name: 'a_fade_opacity', components: 1, type: 'Uint32'}\n], 4);\n\nexport const collisionVertexAttributes = createLayout([\n {name: 'a_placed', components: 2, type: 'Uint8'},\n {name: 'a_shift', components: 2, type: 'Float32'}\n]);\n\nexport const collisionBox = createLayout([\n // the box is centered around the anchor point\n {type: 'Int16', name: 'anchorPointX'},\n {type: 'Int16', name: 'anchorPointY'},\n\n // distances to the edges from the anchor\n {type: 'Int16', name: 'x1'},\n {type: 'Int16', name: 'y1'},\n {type: 'Int16', name: 'x2'},\n {type: 'Int16', name: 'y2'},\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 = createLayout([ // used to render collision boxes for debugging purposes\n {name: 'a_pos', components: 2, 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 = createLayout([ // used to render collision circles for debugging purposes\n {name: 'a_pos', 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 = createLayout([\n {name: 'triangle', components: 3, type: 'Uint16'},\n]);\n\nexport const placement = createLayout([\n {type: 'Int16', name: 'anchorX'},\n {type: 'Int16', name: 'anchorY'},\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]);\n\nexport const symbolInstance = createLayout([\n {type: 'Int16', name: 'anchorX'},\n {type: 'Int16', name: 'anchorY'},\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', name: 'textBoxScale'},\n {type: 'Float32', components: 2, name: 'textOffset'},\n {type: 'Float32', name: 'collisionCircleDiameter'},\n]);\n\nexport const glyphOffset = createLayout([\n {type: 'Float32', name: 'offsetX'}\n]);\n\nexport const lineVertex = createLayout([\n {type: 'Int16', name: 'x'},\n {type: 'Int16', name: 'y'},\n {type: 'Int16', name: 'tileUnitDistanceFromAnchor'}\n]);\n","// @flow\n\nimport {plugin as rtlTextPlugin} from '../source/rtl_text_plugin';\n\nimport type SymbolStyleLayer from '../style/style_layer/symbol_style_layer';\nimport type {Feature} from '../style-spec/expression';\nimport Formatted from '../style-spec/expression/types/formatted';\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 {\n charHasRotatedVerticalOrientation,\n} from './script_detection';\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\nexport default function verticalizePunctuation(input: 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 = (\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\n","exports.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","'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","\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';\nimport {register} from '../util/web_worker_transfer';\nimport potpack from 'potpack';\n\nimport type {StyleImage} from '../style/style_image';\nimport type ImageManager from './image_manager';\nimport type Texture from './texture';\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 {\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 tlbr(): Array {\n return this.tl.concat(this.br);\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;\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) {\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 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';\nimport verticalizePunctuation from '../util/verticalize_punctuation';\nimport {plugin as rtlTextPlugin} from '../source/rtl_text_plugin';\nimport ONE_EM from './one_em';\nimport {warnOnce} from '../util/util';\n\nimport type {StyleGlyph, GlyphMetrics} from '../style/style_glyph';\nimport {GLYPH_PBF_BORDER} from '../style/parse_glyph_pbf';\nimport type {ImagePosition} from '../render/image_atlas';\nimport {IMAGE_PADDING} from '../render/image_atlas';\nimport type {Rect, GlyphPosition} from '../render/glyph_atlas';\nimport Formatted, {FormattedSection} from '../style-spec/expression/types/formatted';\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: Rect | null\n};\n\nexport type PositionedLine = {\n positionedGlyphs: Array,\n lineOffset: number\n};\n\n// A collection of positioned glyphs and some metadata\nexport type Shaping = {\n positionedLines: Array,\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};\n\nfunction isEmpty(positionedLines: Array) {\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 | null, fontStack: string) {\n const textOptions = new SectionOptions();\n textOptions.scale = scale || 1;\n textOptions.fontStack = fontStack;\n return textOptions;\n }\n\n static forImage(imageName: string) {\n const imageOptions = new SectionOptions();\n imageOptions.imageName = imageName;\n return imageOptions;\n }\n\n}\n\nclass TaggedString {\n text: string;\n sectionIndex: Array // maps each character in 'text' to its corresponding entry in 'sections'\n sections: Array\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) {\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 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() {\n this.text = verticalizePunctuation(this.text);\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() {\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): Array {\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]: {[_: number]: ?StyleGlyph}},\n glyphPositions: {[_: string]: {[_: number]: GlyphPosition}},\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 symbolPlacement: string,\n layoutTextSize: number,\n layoutTextSizeThisZoom: number): Shaping | false {\n const logicalInput = TaggedString.fromFeature(text, defaultFontStack);\n\n if (writingMode === WritingMode.vertical) {\n logicalInput.verticalizePunctuation();\n }\n\n let lines: Array;\n\n const {processBidirectionalText, processStyledBidirectionalText} = rtlTextPlugin;\n if (processBidirectionalText && logicalInput.sections.length === 1) {\n // Bidi doesn't have to be style-aware\n lines = [];\n const untaggedLines =\n processBidirectionalText(logicalInput.toString(),\n determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, symbolPlacement, layoutTextSize));\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\n // with formatting\n lines = [];\n const processedLines =\n processStyledBidirectionalText(logicalInput.text,\n logicalInput.sectionIndex,\n determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, symbolPlacement, layoutTextSize));\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, determineLineBreaks(logicalInput, spacing, maxWidth, glyphMap, imagePositions, symbolPlacement, layoutTextSize));\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 };\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]: {[_: number]: ?StyleGlyph}},\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[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]: {[_: number]: ?StyleGlyph}},\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,\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 {\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]: {[_: number]: ?StyleGlyph}},\n imagePositions: {[_: string]: ImagePosition},\n symbolPlacement: string,\n layoutTextSize: number): Array {\n if (symbolPlacement !== 'point')\n return [];\n\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) {\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]: {[_: number]: ?StyleGlyph}},\n glyphPositions: {[_: string]: {[_: number]: GlyphPosition}},\n imagePositions: {[_: string]: ImagePosition},\n lines: Array,\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 = SHAPING_DEFAULT_OFFSET;\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 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 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 let baselineOffset = 0.0;\n let metrics = null;\n let rect = null;\n let imageName = null;\n let verticalAdvance = ONE_EM;\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 const positions = glyphPositions[section.fontStack];\n const glyphPosition = positions && positions[codePoint];\n if (glyphPosition && glyphPosition.rect) {\n rect = glyphPosition.rect;\n metrics = glyphPosition.metrics;\n } else {\n const glyphs = glyphMap[section.fontStack];\n const glyph = glyphs && glyphs[codePoint];\n if (!glyph) continue;\n metrics = glyph.metrics;\n }\n\n // We don't know the baseline, but since we're laying out\n // at 24 points, we can calculate how much it will move when\n // we scale up or down.\n baselineOffset = (lineMaxScale - section.scale) * ONE_EM;\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 section.scale = section.scale * 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\n // Difference between one EM and an image size.\n // Aligns bottom of an image to a baseline level.\n const imageOffset = ONE_EM - size[1] * section.scale;\n baselineOffset = maxLineOffset + imageOffset;\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] * section.scale - ONE_EM * lineMaxScale :\n size[1] * section.scale - 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 + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect});\n x += metrics.advance * section.scale + spacing;\n } else {\n shaping.verticalizable = true;\n positionedGlyphs.push({glyph: codePoint, imageName, x, y: y + baselineOffset, vertical, scale: section.scale, fontStack: section.fontStack, sectionIndex, metrics, rect});\n x += verticalAdvance * section.scale + 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 justifyLine(positionedGlyphs, 0, positionedGlyphs.length - 1, justify, lineOffset);\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 // Calculate the bounding box and justify / align text block.\n const height = y - SHAPING_DEFAULT_OFFSET;\n const {horizontalAlign, verticalAlign} = getAnchorAlignment(textAnchor);\n align(shaping.positionedLines, justify, horizontalAlign, verticalAlign, maxLineLength, maxLineHeight, lineHeight, height, lines.length);\n\n shaping.top += -verticalAlign * height;\n shaping.bottom = shaping.top + height;\n shaping.left += -horizontalAlign * maxLineLength;\n shaping.right = shaping.left + maxLineLength;\n}\n\n// justify right = 1, left = 0, center = 0.5\nfunction justifyLine(positionedGlyphs: Array,\n start: number,\n end: number,\n justify: 1 | 0 | 0.5,\n lineOffset: number) {\n if (!justify && !lineOffset)\n return;\n\n const lastPositionedGlyph = positionedGlyphs[end];\n const lastAdvance = lastPositionedGlyph.metrics.advance * lastPositionedGlyph.scale;\n const lineIndent = (positionedGlyphs[end].x + lastAdvance) * justify;\n\n for (let j = start; j <= end; j++) {\n positionedGlyphs[j].x -= lineIndent;\n positionedGlyphs[j].y += lineOffset;\n }\n}\n\nfunction align(positionedLines: Array,\n justify: number,\n horizontalAlign: number,\n verticalAlign: number,\n maxLineLength: number,\n maxLineHeight: number,\n lineHeight: number,\n blockHeight: number,\n lineCount: number) {\n const shiftX = (justify - horizontalAlign) * maxLineLength;\n let shiftY = 0;\n\n if (maxLineHeight !== lineHeight) {\n shiftY = -blockHeight * verticalAlign - SHAPING_DEFAULT_OFFSET;\n } else {\n shiftY = (-verticalAlign * lineCount + 0.5) * lineHeight;\n }\n\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 {AlphaImage} from '../util/image';\n\nimport Protobuf from 'pbf';\nconst border = 3;\n\nimport type {StyleGlyph} from './style_glyph';\n\nfunction readFontstacks(tag: number, glyphs: Array, pbf: Protobuf) {\n if (tag === 1) {\n pbf.readMessage(readFontstack, glyphs);\n }\n}\n\nfunction readFontstack(tag: number, glyphs: Array, pbf: Protobuf) {\n if (tag === 3) {\n const {id, bitmap, width, height, left, top, advance} = pbf.readMessage(readGlyph, {});\n 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 }\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): Array {\n return new Protobuf(data).readFields(readFontstacks, []);\n}\n\nexport const GLYPH_PBF_BORDER = border;\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport {register} from '../util/web_worker_transfer';\n\nclass Anchor extends Point {\n angle: any;\n segment: number | void;\n\n constructor(x: number, y: number, angle: number, segment?: number) {\n super(x, y);\n this.angle = angle;\n if (segment !== undefined) {\n this.segment = segment;\n }\n }\n\n clone() {\n return new Anchor(this.x, this.y, this.angle, this.segment);\n }\n}\n\nregister('Anchor', Anchor);\n\nexport default Anchor;\n","// @flow\n\nimport {number as interpolate} from '../style-spec/util/interpolate';\nimport Interpolate from '../style-spec/expression/definitions/interpolate';\nimport {clamp} from '../util/util';\nimport EvaluationParameters from '../style/evaluation_parameters';\n\nimport type {PropertyValue, PossiblyEvaluatedPropertyValue} from '../style/properties';\nimport type {InterpolationType} from '../style-spec/expression/definitions/interpolate';\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\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>): SizeData {\n const {expression} = value;\n\n if (expression.kind === 'constant') {\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 const minSize = expression.evaluate(new EvaluationParameters(minZoom));\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}: { uSize: number, uSizeT: number },\n {lowerSize, upperSize}: { lowerSize: number, upperSize: 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) {\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\nexport default checkMaxAngle;\n\nimport type Point from '@mapbox/point-geometry';\nimport type Anchor from './anchor';\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, anchor: Anchor, labelLength: number, windowSize: number, maxAngle: number) {\n\n // horizontal labels always pass\n if (anchor.segment === undefined) return true;\n\n let p = 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';\n\nimport Anchor from '../symbol/anchor';\nimport checkMaxAngle from './check_max_angle';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {Shaping, PositionedIcon} from './shaping';\n\nexport {getAnchors, getCenterAnchor};\n\nfunction getLineLength(line: Array): 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,\n maxAngle: number,\n shapedText: ?Shaping,\n shapedIcon: ?PositionedIcon,\n glyphSize: number,\n boxScale: number) {\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, b.angleTo(a), i);\n anchor._round();\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,\n spacing: number,\n maxAngle: number,\n shapedText: ?Shaping,\n shapedIcon: ?PositionedIcon,\n glyphSize: number,\n boxScale: number,\n overscaling: number,\n tileExtent: number) {\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, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, placeAtMiddle, tileExtent) {\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, 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 Point from '@mapbox/point-geometry';\n\nimport {GLYPH_PBF_BORDER} from '../style/parse_glyph_pbf';\n\nimport type Anchor from './anchor';\nimport type {PositionedIcon, Shaping} from './shaping';\nimport {SHAPING_DEFAULT_OFFSET} from './shaping';\nimport {IMAGE_PADDING} from '../render/image_atlas';\nimport type SymbolStyleLayer from '../style/style_layer/symbol_style_layer';\nimport type {Feature} from '../style-spec/expression';\nimport type {StyleImage} from '../style/style_image';\nimport ONE_EM from './one_em';\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 {\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, range) => 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, top, right, bottom) => {\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, min, max) {\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, fixedSize, stretchSize) {\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, stretchSize, iconSize, iconOffset) {\n return stretchOffset / stretchSize * iconSize + iconOffset;\n}\n\nfunction getPxOffset(fixedOffset, fixedSize, stretchOffset, stretchSize) {\n return fixedOffset - fixedSize * stretchOffset / stretchSize;\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 {\n\n const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}) * Math.PI / 180;\n const quads = [];\n\n for (const line of shaping.positionedLines) {\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\n const rotateVerticalGlyph = (alongLine || allowVerticalPlacement) && positionedGlyph.vertical;\n const halfAdvance = positionedGlyph.metrics.advance * positionedGlyph.scale / 2;\n\n // Align images and scaled glyphs in the middle of a vertical line.\n if (allowVerticalPlacement && shaping.verticalizable) {\n const scaledGlyphOffset = (positionedGlyph.scale - 1) * ONE_EM;\n const imageOffset = (ONE_EM - positionedGlyph.metrics.width * positionedGlyph.scale) / 2;\n lineOffset = line.lineOffset / 2 - (positionedGlyph.imageName ? -imageOffset : scaledGlyphOffset);\n }\n\n if (positionedGlyph.imageName) {\n const image = imageMap[positionedGlyph.imageName];\n isSDF = image.sdf;\n pixelRatio = image.pixelRatio;\n rectBuffer = IMAGE_PADDING / pixelRatio;\n }\n\n const glyphOffset = alongLine ?\n [positionedGlyph.x + halfAdvance, positionedGlyph.y] :\n [0, 0];\n\n let builtInOffset = alongLine ?\n [0, 0] :\n [positionedGlyph.x + halfAdvance + textOffset[0], positionedGlyph.y + textOffset[1] - lineOffset];\n\n let verticalizedLabelOffset = [0, 0];\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 = builtInOffset;\n builtInOffset = [0, 0];\n }\n\n const x1 = (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset[0];\n const y1 = (-positionedGlyph.metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset[1];\n const x2 = x1 + textureRect.w * positionedGlyph.scale / pixelRatio;\n const y2 = y1 + textureRect.h * positionedGlyph.scale / pixelRatio;\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 if (rotateVerticalGlyph) {\n // Vertical-supporting glyphs are laid out in 24x24 point boxes (1 square em)\n // In horizontal orientation, the y values for glyphs are below the midline\n // and we use a \"yOffset\" of -17 to pull them up to the middle.\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 center\n // of the glyphs with the horizontal midline, so the yOffset is no longer\n // necessary, but we also pull the glyph to the left along the x axis.\n // The y coordinate includes baseline yOffset, thus needs to be accounted\n // for when glyph is rotated and translated.\n const center = new Point(-halfAdvance, halfAdvance - SHAPING_DEFAULT_OFFSET);\n const verticalRotation = -Math.PI / 2;\n\n // xHalfWidthOffsetCorrection is a difference between full-width and half-width\n // advance, should be 0 for full-width glyphs and will pull up half-width glyphs.\n const xHalfWidthOffsetCorrection = ONE_EM / 2 - halfAdvance;\n const yImageOffsetCorrection = positionedGlyph.imageName ? xHalfWidthOffsetCorrection : 0.0;\n const halfWidthOffsetCorrection = new Point(5 - SHAPING_DEFAULT_OFFSET - xHalfWidthOffsetCorrection, -yImageOffsetCorrection);\n const verticalOffsetCorrection = new Point(...verticalizedLabelOffset);\n tl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);\n tr._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);\n bl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);\n br._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);\n }\n\n if (textRotate) {\n const sin = Math.sin(textRotate),\n cos = Math.cos(textRotate),\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 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","// @flow\n\nimport type {CollisionBoxArray} from '../data/array_types';\nimport Point from '@mapbox/point-geometry';\nimport type Anchor from './anchor';\n\n/**\n * A CollisionFeature represents the area of the tile covered by a single label.\n * It is used with CollisionIndex to check if the label overlaps with any\n * previous labels. A CollisionFeature is mostly just a set of CollisionBox\n * objects.\n *\n * @private\n */\nclass CollisionFeature {\n boxStartIndex: number;\n boxEndIndex: number;\n circleDiameter: ?number;\n\n /**\n * Create a CollisionFeature, adding its collision box data to the given collisionBoxArray in the process.\n * For line aligned labels a collision circle diameter is computed instead.\n *\n * @param anchor The point along the line around which the label is anchored.\n * @param shaped The text or icon shaping results.\n * @param boxScale A magic number used to convert from glyph metrics units to geometry units.\n * @param padding The amount of padding to add around the label edges.\n * @param alignLine Whether the label is aligned with the line or the viewport.\n * @private\n */\n constructor(collisionBoxArray: CollisionBoxArray,\n anchor: Anchor,\n featureIndex: number,\n sourceLayerIndex: number,\n bucketIndex: number,\n shaped: Object,\n boxScale: number,\n padding: number,\n alignLine: boolean,\n rotate: number) {\n\n this.boxStartIndex = collisionBoxArray.length;\n\n if (alignLine) {\n // Compute height of the shape in glyph metrics and apply collision padding.\n // Note that the pixel based 'text-padding' is applied at runtime\n let top = shaped.top;\n let bottom = shaped.bottom;\n const collisionPadding = shaped.collisionPadding;\n\n if (collisionPadding) {\n top -= collisionPadding[1];\n bottom += collisionPadding[3];\n }\n\n let height = bottom - top;\n\n if (height > 0) {\n // set minimum box height to avoid very many small labels\n height = Math.max(10, height);\n this.circleDiameter = height;\n }\n } else {\n let y1 = shaped.top * boxScale - padding;\n let y2 = shaped.bottom * boxScale + padding;\n let x1 = shaped.left * boxScale - padding;\n let x2 = shaped.right * boxScale + padding;\n\n const collisionPadding = shaped.collisionPadding;\n if (collisionPadding) {\n x1 -= collisionPadding[0] * boxScale;\n y1 -= collisionPadding[1] * boxScale;\n x2 += collisionPadding[2] * boxScale;\n y2 += collisionPadding[3] * boxScale;\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 = rotate * Math.PI / 180;\n\n tl._rotate(rotateRadians);\n tr._rotate(rotateRadians);\n bl._rotate(rotateRadians);\n br._rotate(rotateRadians);\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 collisionBoxArray.emplaceBack(anchor.x, anchor.y, x1, y1, x2, y2, featureIndex, sourceLayerIndex, bucketIndex);\n }\n\n this.boxEndIndex = collisionBoxArray.length;\n }\n}\n\nexport default CollisionFeature;\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';\n\n/**\n * Finds an approximation of a polygon's Pole Of Inaccessibiliy 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 Inaccessibiliy.\n * @private\n */\nexport default function (polygonRings: Array>, 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, b) {\n return b.max - a.max;\n}\n\nfunction Cell(x, y, h, polygon) {\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// signed distance from point to polygon outline (negative if point is outside)\nfunction pointToPolygonDist(p, polygon) {\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) {\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';\n\nimport {getAnchors, getCenterAnchor} from './get_anchors';\nimport clipLine from './clip_line';\nimport {shapeText, shapeIcon, WritingMode, fitIconToText} from './shaping';\nimport {getGlyphQuads, getIconQuads} from './quads';\nimport CollisionFeature from './collision_feature';\nimport {warnOnce} from '../util/util';\nimport {\n allowsVerticalWritingMode,\n allowsLetterSpacing\n} from '../util/script_detection';\nimport findPoleOfInaccessibility from '../util/find_pole_of_inaccessibility';\nimport classifyRings from '../util/classify_rings';\nimport EXTENT from '../data/extent';\nimport SymbolBucket from '../data/bucket/symbol_bucket';\nimport EvaluationParameters from '../style/evaluation_parameters';\nimport {SIZE_PACK_FACTOR} from './symbol_size';\nimport ONE_EM from './one_em';\nimport type {CanonicalTileID} from '../source/tile_id';\nimport type {Shaping, PositionedIcon, TextJustify} from './shaping';\nimport type {CollisionBoxArray} from '../data/array_types';\nimport type {SymbolFeature} from '../data/bucket/symbol_bucket';\nimport type {StyleImage} from '../style/style_image';\nimport type {StyleGlyph} from '../style/style_glyph';\nimport type SymbolStyleLayer from '../style/style_layer/symbol_style_layer';\nimport type {ImagePosition} from '../render/image_atlas';\nimport type {GlyphPosition} from '../render/glyph_atlas';\nimport type {PossiblyEvaluatedPropertyValue} from '../style/properties';\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, // (3)\n layoutIconSize: PossiblyEvaluatedPropertyValue, // (3)\n textMaxSize: PossiblyEvaluatedPropertyValue, // (4)\n compositeTextSizes: [PossiblyEvaluatedPropertyValue, PossiblyEvaluatedPropertyValue], // (5)\n compositeIconSizes: [PossiblyEvaluatedPropertyValue, PossiblyEvaluatedPropertyValue], // (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;\n\nexport function evaluateVariableOffset(anchor: TextAnchor, offset: [number, number]) {\n\n function fromRadialOffset(anchor: TextAnchor, radialOffset: number) {\n let x = 0, y = 0;\n if (radialOffset < 0) radialOffset = 0; // Ignore negative offset.\n // solve for r where r^2 + r^2 = radialOffset^2\n const hypotenuse = radialOffset / Math.sqrt(2);\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 = -radialOffset + baselineOffset;\n break;\n case 'top':\n y = radialOffset - 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 = radialOffset;\n break;\n case 'right':\n x = -radialOffset;\n break;\n }\n\n return [x, y];\n }\n\n function fromTextOffset(anchor: TextAnchor, offsetX: number, offsetY: number) {\n let x = 0, y = 0;\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 return [x, y];\n }\n\n return (offset[1] !== INVALID_TEXT_OFFSET) ? fromTextOffset(anchor, offset[0], offset[1]) : fromRadialOffset(anchor, offset[0]);\n}\n\nexport function performSymbolLayout(bucket: SymbolBucket,\n glyphMap: {[_: string]: {[number]: ?StyleGlyph}},\n glyphPositions: {[_: string]: {[number]: GlyphPosition}},\n imageMap: {[_: string]: StyleImage},\n imagePositions: {[_: string]: ImagePosition},\n showCollisionBoxes: boolean,\n canonical: CanonicalTileID) {\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(bucket.zoom + 1), canonical);\n sizes.layoutIconSize = unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(bucket.zoom + 1), canonical);\n sizes.textMaxSize = unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(18));\n\n const lineHeight = layout.get('text-line-height') * ONE_EM;\n const textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point';\n const keepUpright = layout.get('text-keep-upright');\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 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 symbolPlacement = layout.get('symbol-placement');\n const maxWidth = symbolPlacement === 'point' ?\n layout.get('text-max-width').evaluate(feature, {}, canonical) * ONE_EM :\n 0;\n\n const addVerticalShapingForPointLabelIfNeeded = () => {\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 'left', spacingIfAllowed, textOffset, WritingMode.vertical, true, symbolPlacement, 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, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom);\n if (shaping) {\n shapedTextOrientations.horizontal[justification] = shaping;\n singleLine = shaping.positionedLines.length === 1;\n }\n }\n }\n\n addVerticalShapingForPointLabelIfNeeded();\n } else {\n if (textJustify === \"auto\") {\n textJustify = getAnchorJustification(textAnchor);\n }\n\n // Horizontal point or line label.\n const shaping = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify, spacingIfAllowed,\n textOffset, WritingMode.horizontal, false, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom);\n if (shaping) shapedTextOrientations.horizontal[textJustify] = shaping;\n\n // Vertical point label (if allowVerticalPlacement is enabled).\n addVerticalShapingForPointLabelIfNeeded();\n\n // Verticalized line label.\n if (allowsVerticalWritingMode(unformattedText) && textAlongLine && keepUpright) {\n shapedTextOrientations.vertical = shapeText(text, glyphMap, glyphPositions, imagePositions, fontstack, maxWidth, lineHeight, textAnchor, textJustify,\n spacingIfAllowed, textOffset, WritingMode.vertical, false, symbolPlacement, layoutTextSize, layoutTextSizeThisZoom);\n }\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 bucket.iconsInText = shapedText ? shapedText.iconsInText : false;\n if (shapedText || shapedIcon) {\n addFeature(bucket, feature, shapedTextOrientations, shapedIcon, imageMap, sizes, layoutTextSize, layoutIconSize, textOffset, isSDFIcon, canonical);\n }\n }\n\n if (showCollisionBoxes) {\n bucket.generateCollisionDebugBuffers();\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 * 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 timePlaceSymbols#place() selects which of these instances to\n * 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, canonical: CanonicalTileID) {\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, {});\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 defaultHorizontalShaping = getDefaultHorizontalShaping(shapedTextOrientations.horizontal);\n const glyphSize = 24,\n fontScale = layoutTextSize / glyphSize,\n textBoxScale = bucket.tilePixelRatio * fontScale,\n textMaxBoxScale = bucket.tilePixelRatio * textMaxSize / glyphSize,\n iconBoxScale = bucket.tilePixelRatio * layoutIconSize,\n symbolMinDistance = bucket.tilePixelRatio * layout.get('symbol-spacing'),\n textPadding = layout.get('text-padding') * bucket.tilePixelRatio,\n iconPadding = layout.get('icon-padding') * bucket.tilePixelRatio,\n textMaxAngle = layout.get('text-max-angle') / 180 * Math.PI,\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 // 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 (defaultHorizontalShaping) {\n shapedIcon = fitIconToText(shapedIcon, defaultHorizontalShaping, iconTextFit,\n layout.get('icon-text-fit-padding'), iconOffset, fontScale);\n }\n }\n\n const addSymbolAtAnchor = (line, anchor) => {\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 addSymbol(bucket, anchor, line, shapedTextOrientations, shapedIcon, imageMap, verticallyShapedIcon, bucket.layers[0],\n bucket.collisionBoxArray, feature.index, feature.sourceLayerIndex, bucket.index,\n textBoxScale, textPadding, textAlongLine, textOffset,\n iconBoxScale, iconPadding, iconAlongLine, iconOffset,\n feature, sizes, isSDFIcon, canonical, layoutTextSize);\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 || defaultHorizontalShaping,\n shapedIcon,\n glyphSize,\n textMaxBoxScale,\n bucket.overscaling,\n EXTENT\n );\n for (const anchor of anchors) {\n const shapedText = defaultHorizontalShaping;\n if (!shapedText || !anchorIsTooClose(bucket, shapedText.text, textRepeatDistance, anchor)) {\n addSymbolAtAnchor(line, anchor);\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 || defaultHorizontalShaping,\n shapedIcon,\n glyphSize,\n textMaxBoxScale);\n if (anchor) {\n addSymbolAtAnchor(line, anchor);\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));\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));\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));\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 anchor: Point,\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 canonical: CanonicalTileID) {\n const glyphQuads = getGlyphQuads(anchor, 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, {})\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 anchor,\n lineArray.lineStartIndex,\n lineArray.lineLength,\n placedIconIndex,\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\n/**\n * Add a single label & icon placement.\n *\n * @private\n */\nfunction addSymbol(bucket: SymbolBucket,\n anchor: Anchor,\n line: Array,\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 textBoxScale: 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 canonical: CanonicalTileID,\n layoutTextSize: number) {\n const lineArray = bucket.addToLineVertexArray(anchor, line);\n\n let textCollisionFeature, iconCollisionFeature, verticalTextCollisionFeature, verticalIconCollisionFeature;\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\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 textRotation = layer.layout.get('text-rotate').evaluate(feature, {}, canonical);\n const verticalTextRotation = textRotation + 90.0;\n const verticalShaping = shapedTextOrientations.vertical;\n verticalTextCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textBoxScale, textPadding, textAlongLine, verticalTextRotation);\n\n if (verticallyShapedIcon) {\n verticalIconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticallyShapedIcon, iconBoxScale, iconPadding, textAlongLine, verticalTextRotation);\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 if (shapedIcon) {\n const iconRotate = layer.layout.get('icon-rotate').evaluate(feature, {});\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 iconCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconBoxScale, iconPadding, /*align boxes to line*/false, iconRotate);\n\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, {})\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 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, 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 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, 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 (!textCollisionFeature) {\n key = murmur3(shaping.text);\n const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}, canonical);\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 textCollisionFeature = new CollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textBoxScale, textPadding, textAlongLine, textRotate);\n }\n\n const singleLine = shaping.positionedLines.length === 1;\n numHorizontalGlyphVertices += addTextVertices(\n bucket, 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, canonical);\n\n if (singleLine) {\n break;\n }\n }\n\n if (shapedTextOrientations.vertical) {\n numVerticalGlyphVertices += addTextVertices(\n bucket, anchor, shapedTextOrientations.vertical, imageMap, layer, textAlongLine, feature,\n textOffset, lineArray, WritingMode.vertical, ['vertical'], placedTextSymbolIndices, verticalPlacedIconSymbolIndex, sizes, canonical);\n }\n\n const textBoxStartIndex = textCollisionFeature ? textCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;\n const textBoxEndIndex = textCollisionFeature ? textCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;\n\n const verticalTextBoxStartIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;\n const verticalTextBoxEndIndex = verticalTextCollisionFeature ? verticalTextCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;\n\n const iconBoxStartIndex = iconCollisionFeature ? iconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;\n const iconBoxEndIndex = iconCollisionFeature ? iconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;\n\n const verticalIconBoxStartIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxStartIndex : bucket.collisionBoxArray.length;\n const verticalIconBoxEndIndex = verticalIconCollisionFeature ? verticalIconCollisionFeature.boxEndIndex : bucket.collisionBoxArray.length;\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 = (feature: ?CollisionFeature, prevHeight: number): number => {\n if (feature && feature.circleDiameter)\n return Math.max(feature.circleDiameter, prevHeight);\n return prevHeight;\n };\n\n collisionCircleDiameter = getCollisionCircleHeight(textCollisionFeature, collisionCircleDiameter);\n collisionCircleDiameter = getCollisionCircleHeight(verticalTextCollisionFeature, collisionCircleDiameter);\n collisionCircleDiameter = getCollisionCircleHeight(iconCollisionFeature, collisionCircleDiameter);\n collisionCircleDiameter = getCollisionCircleHeight(verticalIconCollisionFeature, collisionCircleDiameter);\n const useRuntimeCollisionCircles = (collisionCircleDiameter > -1) ? 1 : 0;\n\n // Convert circle collision height into pixels\n if (useRuntimeCollisionCircles)\n collisionCircleDiameter *= layoutTextSize / ONE_EM;\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 bucket.symbolInstances.emplaceBack(\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 || -1,\n placedIconSymbolIndex,\n verticalPlacedIconSymbolIndex,\n key,\n textBoxStartIndex,\n textBoxEndIndex,\n verticalTextBoxStartIndex,\n verticalTextBoxEndIndex,\n iconBoxStartIndex,\n iconBoxEndIndex,\n verticalIconBoxStartIndex,\n verticalIconBoxEndIndex,\n featureIndex,\n numHorizontalGlyphVertices,\n numVerticalGlyphVertices,\n numIconVertices,\n numVerticalIconVertices,\n useRuntimeCollisionCircles,\n 0,\n textBoxScale,\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>, x1: number, y1: number, x2: number, y2: number): Array> {\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\n\nimport {symbolLayoutAttributes,\n collisionVertexAttributes,\n collisionBoxLayout,\n dynamicLayoutAttributes\n} from './symbol_attributes';\n\nimport {SymbolLayoutArray,\n SymbolDynamicLayoutArray,\n SymbolOpacityArray,\n CollisionBoxLayoutArray,\n CollisionVertexArray,\n PlacedSymbolArray,\n SymbolInstanceArray,\n GlyphOffsetArray,\n SymbolLineVertexArray\n} from '../array_types';\n\nimport Point from '@mapbox/point-geometry';\nimport SegmentVector from '../segment';\nimport {ProgramConfigurationSet} from '../program_configuration';\nimport {TriangleIndexArray, LineIndexArray} from '../index_array_type';\nimport transformText from '../../symbol/transform_text';\nimport mergeLines from '../../symbol/mergelines';\nimport {allowsVerticalWritingMode, stringContainsRTLText} from '../../util/script_detection';\nimport {WritingMode} from '../../symbol/shaping';\nimport loadGeometry from '../load_geometry';\nimport toEvaluationFeature from '../evaluation_feature';\nimport mvt from '@mapbox/vector-tile';\nconst vectorTileFeatureTypes = mvt.VectorTileFeature.types;\nimport {verticalizedCharacterMap} from '../../util/verticalize_punctuation';\nimport Anchor from '../../symbol/anchor';\nimport {getSizeData} from '../../symbol/symbol_size';\nimport {MAX_PACKED_SIZE} from '../../symbol/symbol_layout';\nimport {register} from '../../util/web_worker_transfer';\nimport EvaluationParameters from '../../style/evaluation_parameters';\nimport Formatted from '../../style-spec/expression/types/formatted';\nimport ResolvedImage from '../../style-spec/expression/types/resolved_image';\nimport {plugin as globalRTLTextPlugin, getRTLTextPluginStatus} from '../../source/rtl_text_plugin';\nimport {mat4} from 'gl-matrix';\n\nimport type {CanonicalTileID} from '../../source/tile_id';\nimport type {\n Bucket,\n BucketParameters,\n IndexedFeature,\n PopulateParameters\n} from '../bucket';\nimport type {CollisionBoxArray, CollisionBox, SymbolInstance} from '../array_types';\nimport type {StructArray, StructArrayMember} from '../../util/struct_array';\nimport SymbolStyleLayer from '../../style/style_layer/symbol_style_layer';\nimport type Context from '../../gl/context';\nimport type IndexBuffer from '../../gl/index_buffer';\nimport type VertexBuffer from '../../gl/vertex_buffer';\nimport type {SymbolQuad} from '../../symbol/quads';\nimport type {SizeData} from '../../symbol/symbol_size';\nimport type {FeatureStates} from '../../source/source_state';\nimport type {ImagePosition} from '../../render/image_atlas';\n\nexport type SingleCollisionBox = {\n x1: number;\n y1: number;\n x2: number;\n y2: number;\n anchorPointX: number;\n anchorPointY: number;\n};\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>,\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\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, anchorX, anchorY, ox, oy, tx, ty, sizeVertex, isSDF: boolean, pixelOffsetX, pixelOffsetY, minFontScaleX, minFontScaleY) {\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 array.emplaceBack(\n // a_pos_offset\n anchorX,\n anchorY,\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 addDynamicAttributes(dynamicLayoutVertexArray: StructArray, p: Point, angle: number) {\n dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);\n dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);\n dynamicLayoutVertexArray.emplaceBack(p.x, p.y, angle);\n dynamicLayoutVertexArray.emplaceBack(p.x, p.y, 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;\n segments: SegmentVector;\n\n dynamicLayoutVertexArray: SymbolDynamicLayoutArray;\n dynamicLayoutVertexBuffer: VertexBuffer;\n\n opacityVertexArray: SymbolOpacityArray;\n opacityVertexBuffer: VertexBuffer;\n\n collisionVertexArray: CollisionVertexArray;\n collisionVertexBuffer: VertexBuffer;\n\n placedSymbolArray: PlacedSymbolArray;\n\n constructor(programConfigurations: ProgramConfigurationSet) {\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 }\n\n isEmpty() {\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 // 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 }\n}\n\nregister('SymbolBuffers', SymbolBuffers);\n\nclass CollisionBuffers {\n layoutVertexArray: StructArray;\n layoutAttributes: Array;\n layoutVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray | LineIndexArray;\n indexBuffer: IndexBuffer;\n\n segments: SegmentVector;\n\n collisionVertexArray: CollisionVertexArray;\n collisionVertexBuffer: VertexBuffer;\n\n constructor(LayoutArray: Class,\n layoutAttributes: Array,\n IndexArray: Class) {\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 }\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 }\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 }\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 * `this.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. performSymbolPlacement(bucket, collisionIndex) 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;\n layerIds: Array;\n stateDependentLayers: Array;\n stateDependentLayerIds: Array;\n\n index: number;\n sdfIcons: boolean;\n iconsInText: boolean;\n iconsNeedLinear: boolean;\n bucketInstanceId: number;\n justReloaded: boolean;\n hasPattern: boolean;\n\n textSizeData: SizeData;\n iconSizeData: SizeData;\n\n glyphOffsetArray: GlyphOffsetArray;\n lineVertexArray: SymbolLineVertexArray;\n features: Array;\n symbolInstances: SymbolInstanceArray;\n collisionArrays: Array;\n sortKeyRanges: Array;\n pixelRatio: number;\n tilePixelRatio: number;\n compareText: {[_: string]: Array};\n fadeStartTime: number;\n sortFeaturesByKey: boolean;\n sortFeaturesByY: boolean;\n canOverlap: boolean;\n sortedAngle: number;\n featureSortOrder: Array;\n\n collisionCircleArray: Array;\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;\n writingModes: Array;\n allowVerticalPlacement: boolean;\n hasRTLText: boolean;\n\n constructor(options: BucketParameters) {\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.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 if (layout.get('symbol-placement') === 'point') {\n this.writingModes = layout.get('text-writing-mode').map(wm => WritingMode[wm]);\n }\n\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n\n this.sourceID = options.sourceID;\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 ((textAlongLine || 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, options: PopulateParameters, canonical: CanonicalTileID) {\n const layer = this.layers[0];\n const layout = layer.layout;\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 if (!layer._featureFilter.filter(globalProperties, evaluationFeature, canonical)) {\n continue;\n }\n\n if (!needGeometry) evaluationFeature.geometry = loadGeometry(feature);\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: VectorTileLayer, imagePositions: {[_: string]: ImagePosition}) {\n if (!this.stateDependentLayers.length) return;\n this.text.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions);\n this.icon.programConfigurations.updatePaintArrays(states, vtLayer, this.layers, imagePositions);\n }\n\n isEmpty() {\n // When the bucket encounters only rtl-text but the plugin isnt 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() {\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 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: any) {\n const lineStartIndex = this.lineVertexArray.length;\n if (anchor.segment !== undefined) {\n let sumForwardLength = anchor.dist(line[anchor.segment + 1]);\n let sumBackwardLength = anchor.dist(line[anchor.segment]);\n const vertices = {};\n for (let i = anchor.segment + 1; i < line.length; i++) {\n vertices[i] = {x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumForwardLength};\n if (i < line.length - 1) {\n sumForwardLength += line[i + 1].dist(line[i]);\n }\n }\n for (let i = anchor.segment || 0; i >= 0; i--) {\n vertices[i] = {x: line[i].x, y: line[i].y, tileUnitDistanceFromAnchor: sumBackwardLength};\n if (i > 0) {\n sumBackwardLength += line[i - 1].dist(line[i]);\n }\n }\n for (let i = 0; i < line.length; i++) {\n const vertex = vertices[i];\n this.lineVertexArray.emplaceBack(vertex.x, vertex.y, vertex.tileUnitDistanceFromAnchor);\n }\n }\n return {\n lineStartIndex,\n lineLength: this.lineVertexArray.length - lineStartIndex\n };\n }\n\n addSymbols(arrays: SymbolBuffers,\n quads: Array,\n sizeVertex: any,\n lineOffset: [number, number],\n alongLine: boolean,\n feature: SymbolFeature,\n writingMode: any,\n labelAnchor: Anchor,\n lineStartIndex: number,\n lineLength: number,\n associatedIconIndex: number,\n canonical: CanonicalTileID) {\n const indexArray = arrays.indexArray;\n const layoutVertexArray = arrays.layoutVertexArray;\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, labelAnchor.x, labelAnchor.y, tl.x, y + tl.y, tex.x, tex.y, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY);\n addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, tr.x, y + tr.y, tex.x + tex.w, tex.y, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetTL.y, minFontScaleX, minFontScaleY);\n addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, bl.x, y + bl.y, tex.x, tex.y + tex.h, sizeVertex, isSDF, pixelOffsetTL.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY);\n addVertex(layoutVertexArray, labelAnchor.x, labelAnchor.y, br.x, y + br.y, tex.x + tex.w, tex.y + tex.h, sizeVertex, isSDF, pixelOffsetBR.x, pixelOffsetBR.y, minFontScaleX, minFontScaleY);\n\n addDynamicAttributes(arrays.dynamicLayoutVertexArray, labelAnchor, angle);\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, {}, canonical, sections && sections[sectionIndex]);\n }\n }\n\n arrays.placedSymbolArray.emplaceBack(labelAnchor.x, labelAnchor.y,\n glyphOffsetArrayStart, this.glyphOffsetArray.length - glyphOffsetArrayStart, vertexStartIndex,\n lineStartIndex, lineLength, (labelAnchor.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 );\n }\n\n _addCollisionDebugVertex(layoutVertexArray: StructArray, collisionVertexArray: StructArray, point: Point, anchorX: number, anchorY: number, extrude: Point) {\n collisionVertexArray.emplaceBack(0, 0);\n return layoutVertexArray.emplaceBack(\n // pos\n point.x,\n point.y,\n // a_anchor_pos\n anchorX,\n anchorY,\n // extrude\n Math.round(extrude.x),\n Math.round(extrude.y));\n }\n\n addCollisionDebugVertices(x1: number, y1: number, x2: number, y2: number, arrays: CollisionBuffers, boxAnchorPoint: Point, symbolInstance: SymbolInstance) {\n const segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray);\n const index = segment.vertexLength;\n\n const layoutVertexArray = arrays.layoutVertexArray;\n const collisionVertexArray = arrays.collisionVertexArray;\n\n const anchorX = symbolInstance.anchorX;\n const anchorY = symbolInstance.anchorY;\n\n this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x1, y1));\n this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x2, y1));\n this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x2, y2));\n this._addCollisionDebugVertex(layoutVertexArray, collisionVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(x1, 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 addDebugCollisionBoxes(startIndex: number, endIndex: number, symbolInstance: SymbolInstance, isText: boolean) {\n for (let b = startIndex; b < endIndex; b++) {\n const box: CollisionBox = (this.collisionBoxArray.get(b): any);\n const x1 = box.x1;\n const y1 = box.y1;\n const x2 = box.x2;\n const y2 = box.y2;\n\n this.addCollisionDebugVertices(x1, y1, x2, y2,\n isText ? this.textCollisionBox : this.iconCollisionBox,\n box.anchorPoint, symbolInstance);\n }\n }\n\n generateCollisionDebugBuffers() {\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 for (let i = 0; i < this.symbolInstances.length; i++) {\n const symbolInstance = this.symbolInstances.get(i);\n this.addDebugCollisionBoxes(symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance, true);\n this.addDebugCollisionBoxes(symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance, true);\n this.addDebugCollisionBoxes(symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance, false);\n this.addDebugCollisionBoxes(symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance, false);\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 const collisionArrays = {};\n for (let k = textStartIndex; k < textEndIndex; k++) {\n const box: CollisionBox = (collisionBoxArray.get(k): any);\n collisionArrays.textBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};\n collisionArrays.textFeatureIndex = box.featureIndex;\n break; // Only one box allowed per instance\n }\n for (let k = verticalTextStartIndex; k < verticalTextEndIndex; k++) {\n const box: CollisionBox = (collisionBoxArray.get(k): any);\n collisionArrays.verticalTextBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};\n collisionArrays.verticalTextFeatureIndex = box.featureIndex;\n break; // Only one box allowed per instance\n }\n for (let k = iconStartIndex; k < iconEndIndex; k++) {\n // An icon can only have one box now, so this indexing is a bit vestigial...\n const box: CollisionBox = (collisionBoxArray.get(k): any);\n collisionArrays.iconBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};\n collisionArrays.iconFeatureIndex = box.featureIndex;\n break; // Only one box allowed per instance\n }\n for (let k = verticalIconStartIndex; k < verticalIconEndIndex; k++) {\n // An icon can only have one box now, so this indexing is a bit vestigial...\n const box: CollisionBox = (collisionBoxArray.get(k): any);\n collisionArrays.verticalIconBox = {x1: box.x1, y1: box.y1, x2: box.x2, y2: box.y2, anchorPointX: box.anchorPointX, anchorPointY: box.anchorPointY};\n collisionArrays.verticalIconFeatureIndex = box.featureIndex;\n break; // Only one box allowed per instance\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() {\n return this.text.segments.get().length > 0;\n }\n\n hasIconData() {\n return this.icon.segments.get().length > 0;\n }\n\n hasDebugData() {\n return this.textCollisionBox && this.iconCollisionBox;\n }\n\n hasTextCollisionBoxData() {\n return this.hasDebugData() && this.textCollisionBox.segments.get().length > 0;\n }\n\n hasIconCollisionBoxData() {\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) {\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.anchorX + cos * symbolInstance.anchorY) | 0);\n featureIndexes.push(symbolInstance.featureIndex);\n }\n\n result.sort((aIndex, bIndex) => {\n return (rotatedYs[aIndex] - rotatedYs[bIndex]) ||\n (featureIndexes[bIndex] - featureIndexes[aIndex]);\n });\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 symbolInstance = this.symbolInstances.get(i);\n this.featureSortOrder.push(symbolInstance.featureIndex);\n\n [\n symbolInstance.rightJustifiedTextSymbolIndex,\n symbolInstance.centerJustifiedTextSymbolIndex,\n symbolInstance.leftJustifiedTextSymbolIndex\n ].forEach((index, i, array) => {\n // Only add a given index the first time it shows up,\n // to avoid duplicate opacity entries when multiple justifications\n // share the same glyphs.\n if (index >= 0 && array.indexOf(index) === i) {\n this.addIndicesForPlacedSymbol(this.text, index);\n }\n });\n\n if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) {\n this.addIndicesForPlacedSymbol(this.text, symbolInstance.verticalPlacedTextSymbolIndex);\n }\n\n if (symbolInstance.placedIconSymbolIndex >= 0) {\n this.addIndicesForPlacedSymbol(this.icon, symbolInstance.placedIconSymbolIndex);\n }\n\n if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) {\n this.addIndicesForPlacedSymbol(this.icon, symbolInstance.verticalPlacedIconSymbolIndex);\n }\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};\n","// @flow\n\nimport type {SymbolFeature} from '../data/bucket/symbol_bucket';\n\nexport default function (features: Array): Array {\n const leftIndex: {[_: string]: number} = {};\n const rightIndex: {[_: string]: number} = {};\n const mergedFeatures = [];\n let mergedIndex = 0;\n\n function add(k) {\n mergedFeatures.push(features[k]);\n mergedIndex++;\n }\n\n function mergeFromRight(leftKey: string, rightKey: string, geom) {\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) {\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, geom, onRight) {\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';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image';\n\nimport {\n ColorType\n} from '../../style-spec/expression/types';\n\nexport type LayoutProps = {|\n \"symbol-placement\": DataConstantProperty<\"point\" | \"line\" | \"line-center\">,\n \"symbol-spacing\": DataConstantProperty,\n \"symbol-avoid-edges\": DataConstantProperty,\n \"symbol-sort-key\": DataDrivenProperty,\n \"symbol-z-order\": DataConstantProperty<\"auto\" | \"viewport-y\" | \"source\">,\n \"icon-allow-overlap\": DataConstantProperty,\n \"icon-ignore-placement\": DataConstantProperty,\n \"icon-optional\": DataConstantProperty,\n \"icon-rotation-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"auto\">,\n \"icon-size\": DataDrivenProperty,\n \"icon-text-fit\": DataConstantProperty<\"none\" | \"width\" | \"height\" | \"both\">,\n \"icon-text-fit-padding\": DataConstantProperty<[number, number, number, number]>,\n \"icon-image\": DataDrivenProperty,\n \"icon-rotate\": DataDrivenProperty,\n \"icon-padding\": DataConstantProperty,\n \"icon-keep-upright\": DataConstantProperty,\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,\n \"text-font\": DataDrivenProperty>,\n \"text-size\": DataDrivenProperty,\n \"text-max-width\": DataDrivenProperty,\n \"text-line-height\": DataConstantProperty,\n \"text-letter-spacing\": DataDrivenProperty,\n \"text-justify\": DataDrivenProperty<\"auto\" | \"left\" | \"center\" | \"right\">,\n \"text-radial-offset\": DataDrivenProperty,\n \"text-variable-anchor\": DataConstantProperty>,\n \"text-anchor\": DataDrivenProperty<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n \"text-max-angle\": DataConstantProperty,\n \"text-writing-mode\": DataConstantProperty>,\n \"text-rotate\": DataDrivenProperty,\n \"text-padding\": DataConstantProperty,\n \"text-keep-upright\": DataConstantProperty,\n \"text-transform\": DataDrivenProperty<\"none\" | \"uppercase\" | \"lowercase\">,\n \"text-offset\": DataDrivenProperty<[number, number]>,\n \"text-allow-overlap\": DataConstantProperty,\n \"text-ignore-placement\": DataConstantProperty,\n \"text-optional\": DataConstantProperty,\n|};\n\nconst layout: Properties = 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 DataConstantProperty(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,\n \"icon-color\": DataDrivenProperty,\n \"icon-halo-color\": DataDrivenProperty,\n \"icon-halo-width\": DataDrivenProperty,\n \"icon-halo-blur\": DataDrivenProperty,\n \"icon-translate\": DataConstantProperty<[number, number]>,\n \"icon-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"text-opacity\": DataDrivenProperty,\n \"text-color\": DataDrivenProperty,\n \"text-halo-color\": DataDrivenProperty,\n \"text-halo-width\": DataDrivenProperty,\n \"text-halo-blur\": DataDrivenProperty,\n \"text-translate\": DataConstantProperty<[number, number]>,\n \"text-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n|};\n\nconst paint: Properties = 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, layout: Properties\n}>);\n","// @flow\n\nimport assert from 'assert';\nimport type {Expression} from '../style-spec/expression/expression';\nimport type EvaluationContext from '../style-spec/expression/evaluation_context';\nimport type {Type} from '../style-spec/expression/types';\nimport type {ZoomConstantExpression} from '../style-spec/expression';\nimport {NullType} from '../style-spec/expression/types';\nimport {PossiblyEvaluatedPropertyValue} from './properties';\nimport {register} from '../util/web_worker_transfer';\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 implements Expression {\n type: Type;\n defaultValue: PossiblyEvaluatedPropertyValue;\n\n constructor(defaultValue: PossiblyEvaluatedPropertyValue) {\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) {\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 return this.defaultValue.property.specification.default;\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() {\n return false;\n }\n\n serialize() {\n return null;\n }\n}\n\nregister('FormatSectionOverride', FormatSectionOverride, {omit: ['defaultValue']});\n","// @flow\n\nimport StyleLayer from '../style_layer';\n\nimport assert from 'assert';\nimport SymbolBucket from '../../data/bucket/symbol_bucket';\nimport resolveTokens from '../../util/resolve_tokens';\nimport properties from './symbol_style_layer_properties';\n\nimport {\n Transitionable,\n Transitioning,\n Layout,\n PossiblyEvaluated,\n PossiblyEvaluatedPropertyValue,\n PropertyValue\n} from '../properties';\n\nimport {\n isExpression,\n StyleExpression,\n ZoomConstantExpression,\n ZoomDependentExpression\n} from '../../style-spec/expression';\n\nimport type {BucketParameters} from '../../data/bucket';\nimport type {LayoutProps, PaintProps} from './symbol_style_layer_properties';\nimport type EvaluationParameters from '../evaluation_parameters';\nimport type {LayerSpecification} from '../../style-spec/types';\nimport type {Feature, SourceExpression, CompositeExpression} from '../../style-spec/expression';\nimport type {Expression} from '../../style-spec/expression/expression';\nimport type {CanonicalTileID} from '../../source/tile_id';\nimport {FormattedType} from '../../style-spec/expression/types';\nimport {typeOf} from '../../style-spec/expression/values';\nimport Formatted from '../../style-spec/expression/types/formatted';\nimport FormatSectionOverride from '../format_section_override';\nimport FormatExpression from '../../style-spec/expression/definitions/format';\nimport Literal from '../../style-spec/expression/definitions/literal';\n\nclass SymbolStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout;\n layout: PossiblyEvaluated;\n\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n recalculate(parameters: EvaluationParameters, availableImages: Array) {\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 if (this.layout.get('symbol-placement') === 'point') {\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 {\n this.layout._values['text-writing-mode'] = ['horizontal'];\n }\n }\n\n this._setPaintOverrides();\n }\n\n getValueAndResolveTokens(name: *, feature: Feature, canonical: CanonicalTileID, availableImages: Array) {\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<*>) {\n return new SymbolBucket(parameters);\n }\n\n queryRadius(): number {\n return 0;\n }\n\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 expression = (new ZoomConstantExpression('source', styleExpression): SourceExpression);\n } else {\n expression = (new ZoomDependentExpression('composite',\n styleExpression,\n overriden.value.zoomStops,\n overriden.value._interpolationType): CompositeExpression);\n }\n this.paint._values[overridable] = new PossiblyEvaluatedPropertyValue(overriden.property,\n expression,\n overriden.parameters);\n }\n }\n\n _handleOverridablePaintPropertyUpdate(name: string, oldValue: PropertyValue, newValue: PropertyValue): 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, 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) => {\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\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';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image';\n\n\nexport type PaintProps = {|\n \"background-color\": DataConstantProperty,\n \"background-pattern\": CrossFadedProperty,\n \"background-opacity\": DataConstantProperty,\n|};\n\nconst paint: Properties = new Properties({\n \"background-color\": new DataConstantProperty(styleSpec[\"paint_background\"][\"background-color\"]),\n \"background-pattern\": new CrossFadedProperty(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\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer';\n\nimport properties from './background_style_layer_properties';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties';\n\nimport type {PaintProps} from './background_style_layer_properties';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass BackgroundStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n}\n\nexport default BackgroundStyleLayer;\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';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image';\n\n\nexport type PaintProps = {|\n \"raster-opacity\": DataConstantProperty,\n \"raster-hue-rotate\": DataConstantProperty,\n \"raster-brightness-min\": DataConstantProperty,\n \"raster-brightness-max\": DataConstantProperty,\n \"raster-saturation\": DataConstantProperty,\n \"raster-contrast\": DataConstantProperty,\n \"raster-resampling\": DataConstantProperty<\"linear\" | \"nearest\">,\n \"raster-fade-duration\": DataConstantProperty,\n|};\n\nconst paint: Properties = 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\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer';\n\nimport properties from './raster_style_layer_properties';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties';\n\nimport type {PaintProps} from './raster_style_layer_properties';\nimport type {LayerSpecification} from '../../style-spec/types';\n\nclass RasterStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable;\n _transitioningPaint: Transitioning;\n paint: PossiblyEvaluated;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n}\n\nexport default RasterStyleLayer;\n","// @flow\n\nimport StyleLayer from '../style_layer';\nimport type Map from '../../ui/map';\nimport assert from 'assert';\n\ntype CustomRenderMethod = (gl: WebGLRenderingContext, matrix: Array) => 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', function() {\n * map.addLayer(new NullIslandLayer());\n * });\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} 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} 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 onAdd: ?(map: Map, gl: WebGLRenderingContext) => void,\n onRemove: ?(map: Map, gl: WebGLRenderingContext) => void\n}\n\nexport function validateCustomStyleLayer(layerObject: CustomLayerInterface) {\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() {\n return this.implementation.renderingMode === '3d';\n }\n\n hasOffscreenPass() {\n return this.implementation.prerender !== undefined;\n }\n\n recalculate() {}\n updateTransitions() {}\n hasTransition() {}\n\n serialize() {\n assert(false, \"Custom layers cannot be serialized\");\n }\n\n onAdd(map: Map) {\n if (this.implementation.onAdd) {\n this.implementation.onAdd(map, map.painter.context.gl);\n }\n }\n\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","// @flow\n\nimport circle from './style_layer/circle_style_layer';\nimport heatmap from './style_layer/heatmap_style_layer';\nimport hillshade from './style_layer/hillshade_style_layer';\nimport fill from './style_layer/fill_style_layer';\nimport fillExtrusion from './style_layer/fill_extrusion_style_layer';\nimport line from './style_layer/line_style_layer';\nimport symbol from './style_layer/symbol_style_layer';\nimport background from './style_layer/background_style_layer';\nimport raster from './style_layer/raster_style_layer';\nimport CustomStyleLayer from './style_layer/custom_style_layer';\nimport type {CustomLayerInterface} from './style_layer/custom_style_layer';\n\nimport type {LayerSpecification} from '../style-spec/types';\n\nconst subclasses = {\n circle,\n heatmap,\n hillshade,\n fill,\n 'fill-extrusion': fillExtrusion,\n line,\n symbol,\n background,\n raster\n};\n\nexport default function createStyleLayer(layer: LayerSpecification | CustomLayerInterface) {\n if (layer.type === 'custom') {\n return new CustomStyleLayer(layer);\n } else {\n return new subclasses[layer.type](layer);\n }\n}\n\n","\nexport default ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout'];\n","\nimport refProperties from './util/ref_properties';\n\nfunction stringify(obj) {\n const type = typeof obj;\n if (type === 'number' || type === 'boolean' || type === '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 const keys = Object.keys(obj).sort();\n\n let str = '{';\n for (let i = 0; i < keys.length; i++) {\n str += `${JSON.stringify(keys[i])}:${stringify(obj[keys[i]])},`;\n }\n return `${str}}`;\n}\n\nfunction getKey(layer) {\n let key = '';\n for (const k of refProperties) {\n key += `/${stringify(layer[k])}`;\n }\n return key;\n}\n\nexport default groupByLayout;\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} layers\n * @param {Object} [cachedKeys] - an object to keep already calculated keys.\n * @returns {Array>}\n */\nfunction groupByLayout(layers, cachedKeys) {\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 StyleLayer from './style_layer';\nimport createStyleLayer from './create_style_layer';\n\nimport {values} from '../util/util';\nimport featureFilter from '../style-spec/feature_filter';\nimport groupByLayout from '../style-spec/group_by_layout';\n\nimport type {TypedStyleLayer} from './style_layer/typed_style_layer';\nimport type {LayerSpecification} from '../style-spec/types';\n\nexport type LayerConfigs = {[_: string]: LayerSpecification };\nexport type Family = Array;\n\nclass StyleLayerIndex {\n familiesBySource: { [source: string]: { [sourceLayer: string]: Array> } };\n keyCache: { [source: string]: string };\n\n _layerConfigs: LayerConfigs;\n _layers: {[_: string]: StyleLayer };\n\n constructor(layerConfigs: ?Array) {\n this.keyCache = {};\n if (layerConfigs) {\n this.replace(layerConfigs);\n }\n }\n\n replace(layerConfigs: Array) {\n this._layerConfigs = {};\n this._layers = {};\n this.update(layerConfigs, []);\n }\n\n update(layerConfigs: Array, removedIds: Array) {\n for (const layerConfig of layerConfigs) {\n this._layerConfigs[layerConfig.id] = layerConfig;\n\n const layer = this._layers[layerConfig.id] = createStyleLayer(layerConfig);\n layer._featureFilter = featureFilter(layer.filter);\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;\n\n constructor(strings: Array) {\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) {\n assert(string in this._stringToNumber);\n return this._stringToNumber[string];\n }\n\n decode(n: number) {\n assert(n < this._numberToString.length);\n return this._numberToString[n];\n }\n}\n\nexport default DictionaryCoder;\n","// @flow\nimport type {GeoJSONGeometry} from '@mapbox/geojson-types';\n\nclass Feature {\n type: 'Feature';\n _geometry: ?GeoJSONGeometry;\n properties: {};\n id: number | string | void;\n\n _vectorTileFeature: VectorTileFeature;\n\n constructor(vectorTileFeature: VectorTileFeature, z: number, x: number, y: number, id: string | number | void) {\n this.type = 'Feature';\n\n this._vectorTileFeature = vectorTileFeature;\n (vectorTileFeature: any)._z = z;\n (vectorTileFeature: any)._x = x;\n (vectorTileFeature: any)._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(\n (this._vectorTileFeature: any)._x,\n (this._vectorTileFeature: any)._y,\n (this._vectorTileFeature: any)._z).geometry;\n }\n return this._geometry;\n }\n\n set geometry(g: ?GeoJSONGeometry) {\n this._geometry = g;\n }\n\n toJSON() {\n const json = {\n geometry: this.geometry\n };\n for (const i in this) {\n if (i === '_geometry' || i === '_vectorTileFeature') continue;\n json[i] = (this: any)[i];\n }\n return json;\n }\n}\n\nexport default Feature;\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 LngLat from './lng_lat';\n\nimport type {LngLatLike} from './lng_lat';\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 * var sw = new mapboxgl.LngLat(-73.9876, 40.7661);\n * var ne = new mapboxgl.LngLat(-73.9397, 40.8002);\n * var 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} `this`\n */\n setNorthEast(ne: LngLatLike) {\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} `this`\n */\n setSouthWest(sw: LngLatLike) {\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} `this`\n */\n extend(obj: LngLatLike | LngLatBoundsLike) {\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 {\n if (Array.isArray(obj)) {\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 }\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 * var 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 */\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 */\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 */\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 */\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 */\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 */\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 */\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 */\n getNorth(): number { return this._ne.lat; }\n\n /**\n * Returns the bounding box represented as an array.\n *\n * @returns {Array>} 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 * var 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() {\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 * var 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() {\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 */\n isEmpty() {\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 * var llb = new mapboxgl.LngLatBounds(\n * new mapboxgl.LngLat(-73.9876, 40.7661),\n * new mapboxgl.LngLat(-73.9397, 40.8002)\n * );\n *\n * var ll = new mapboxgl.LngLat(-73.9567, 40.7789);\n *\n * console.log(llb.contains(ll)); // = true\n */\n contains(lnglat: LngLatLike) {\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 * var arr = [[-73.9876, 40.7661], [-73.9397, 40.8002]];\n * var llb = mapboxgl.LngLatBounds.convert(arr);\n * 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 * var v1 = new mapboxgl.LngLatBounds(\n * new mapboxgl.LngLat(-73.9876, 40.7661),\n * new mapboxgl.LngLat(-73.9397, 40.8002)\n * );\n * var v2 = new mapboxgl.LngLatBounds([-73.9876, 40.7661], [-73.9397, 40.8002])\n * var 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","// @flow\n\nimport {wrap} from '../util/util';\nimport LngLatBounds from './lng_lat_bounds';\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 * A `LngLat` object represents a given longitude and latitude coordinate, measured in degrees.\n * These coordinates are based on the [WGS84 (EPSG:4326) standard](https://en.wikipedia.org/wiki/World_Geodetic_System#WGS84).\n *\n * Mapbox GL uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match the\n * [GeoJSON specification](https://tools.ietf.org/html/rfc7946).\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 * var ll = new mapboxgl.LngLat(-123.9749, 40.7736);\n * ll.lng; // = -123.9749\n * @see [Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/)\n * @see [Display a popup](https://www.mapbox.com/mapbox-gl-js/example/popup/)\n * @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)\n * @see [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 * var ll = new mapboxgl.LngLat(286.0251, 40.7736);\n * var wrapped = ll.wrap();\n * wrapped.lng; // = -73.9749\n */\n wrap() {\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} The coordinates represeted as an array of longitude and latitude.\n * @example\n * var ll = new mapboxgl.LngLat(-73.9749, 40.7736);\n * ll.toArray(); // = [-73.9749, 40.7736]\n */\n toArray() {\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 * var ll = new mapboxgl.LngLat(-73.9749, 40.7736);\n * ll.toString(); // = \"LngLat(-73.9749, 40.7736)\"\n */\n toString() {\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 * var new_york = new mapboxgl.LngLat(-74.0060, 40.7128);\n * var los_angeles = new mapboxgl.LngLat(-118.2437, 34.0522);\n * new_york.distanceTo(los_angeles); // = 3935751.690893987, \"true distance\" using a non-spherical approximation is ~3966km\n */\n distanceTo(lngLat: LngLat) {\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 * var 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) {\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 /**\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 * var arr = [-73.9749, 40.7736];\n * var ll = mapboxgl.LngLat.convert(arr);\n * 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: , lat: }, an object {lon: , lat: }, or an array of [, ]\");\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 * var v1 = new mapboxgl.LngLat(-122.420679, 37.772537);\n * var v2 = [-122.420679, 37.772537];\n * var 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, {earthRadius} from '../geo/lng_lat';\nimport type {LngLatLike} from '../geo/lng_lat';\n\n/*\n * The average circumference of the world in meters.\n */\nconst earthCircumfrence = 2 * Math.PI * earthRadius; // meters\n\n/*\n * The circumference at a line of latitude in meters.\n */\nfunction circumferenceAtLatitude(latitude: number) {\n return earthCircumfrence * Math.cos(latitude * Math.PI / 180);\n}\n\nexport function mercatorXfromLng(lng: number) {\n return (180 + lng) / 360;\n}\n\nexport function mercatorYfromLat(lat: 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) {\n return altitude / circumferenceAtLatitude(lat);\n}\n\nexport function lngFromMercatorX(x: number) {\n return x * 360 - 180;\n}\n\nexport function latFromMercatorY(y: 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) {\n return z * circumferenceAtLatitude(latFromMercatorY(y));\n}\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) {\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 * var nullIsland = new mapboxgl.MercatorCoordinate(0.5, 0.5, 0);\n *\n * @see [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 * var coord = mapboxgl.MercatorCoordinate.fromLngLat({ lng: 0, lat: 0}, 0);\n * coord; // MercatorCoordinate(0.5, 0.5, 0)\n */\n static fromLngLat(lngLatLike: LngLatLike, altitude: number = 0) {\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 * var coord = new mapboxgl.MercatorCoordinate(0.5, 0.5, 0);\n * var lngLat = coord.toLngLat(); // LngLat(0, 0)\n */\n toLngLat() {\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 * var coord = new mapboxgl.MercatorCoordinate(0, 0, 0.02);\n * coord.toAltitude(); // 6914.281956295339\n */\n toAltitude() {\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 */\n meterInMercatorCoordinateUnits() {\n // 1 meter / circumference at equator in meters * Mercator projection scale factor at this latitude\n return 1 / earthCircumfrence * mercatorScale(latFromMercatorY(this.y));\n }\n\n}\n\nexport default MercatorCoordinate;\n","// @flow\n\nimport {getTileBBox} from '@mapbox/whoots-js';\nimport EXTENT from '../data/extent';\nimport Point from '@mapbox/point-geometry';\nimport MercatorCoordinate from '../geo/mercator_coordinate';\n\nimport assert from 'assert';\nimport {register} from '../util/web_worker_transfer';\n\nexport class CanonicalTileID {\n z: number;\n x: number;\n y: number;\n key: string;\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) {\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, scheme: ?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}', String(this.z))\n .replace('{x}', String(this.x))\n .replace('{y}', 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 getTilePoint(coord: MercatorCoordinate) {\n const tilesAtZoom = Math.pow(2, this.z);\n return new Point(\n (coord.x * tilesAtZoom - this.x) * EXTENT,\n (coord.y * tilesAtZoom - this.y) * EXTENT);\n }\n\n toString() {\n return `${this.z}/${this.x}/${this.y}`;\n }\n}\n\nexport class UnwrappedTileID {\n wrap: number;\n canonical: CanonicalTileID;\n key: string;\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: string;\n posMatrix: 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 = calculateKey(wrap, overscaledZ, z, x, y);\n }\n\n equals(id: OverscaledTileID) {\n return this.overscaledZ === id.overscaledZ && this.wrap === id.wrap && this.canonical.equals(id.canonical);\n }\n\n scaledTo(targetZ: number) {\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): string {\n assert(targetZ <= this.overscaledZ);\n const zDifference = this.canonical.z - targetZ;\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 return calculateKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);\n }\n }\n\n isChildOf(parent: OverscaledTileID) {\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) {\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) {\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() {\n return new OverscaledTileID(this.overscaledZ, 0, this.canonical.z, this.canonical.x, this.canonical.y);\n }\n\n unwrapTo(wrap: number) {\n return new OverscaledTileID(this.overscaledZ, wrap, this.canonical.z, this.canonical.x, this.canonical.y);\n }\n\n overscaleFactor() {\n return Math.pow(2, this.overscaledZ - this.canonical.z);\n }\n\n toUnwrapped() {\n return new UnwrappedTileID(this.wrap, this.canonical);\n }\n\n toString() {\n return `${this.overscaledZ}/${this.canonical.x}/${this.canonical.y}`;\n }\n\n getTilePoint(coord: MercatorCoordinate) {\n return this.canonical.getTilePoint(new MercatorCoordinate(coord.x - this.wrap, coord.y));\n }\n}\n\nfunction calculateKey(wrap: number, overscaledZ: number, z: number, x: number, y: number): string {\n wrap *= 2;\n if (wrap < 0) wrap = wrap * -1 - 1;\n const dim = 1 << z;\n return (dim * dim * wrap + dim * y + x).toString(36) + z.toString(36) + overscaledZ.toString(36);\n}\n\nfunction getQuadkey(z, x, y) {\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: ['posMatrix']});\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport loadGeometry from './load_geometry';\nimport toEvaluationFeature from './evaluation_feature';\nimport EXTENT from './extent';\nimport featureFilter from '../style-spec/feature_filter';\nimport Grid from 'grid-index';\nimport DictionaryCoder from '../util/dictionary_coder';\nimport vt from '@mapbox/vector-tile';\nimport Protobuf from 'pbf';\nimport GeoJSONFeature from '../util/vectortile_to_geojson';\nimport {arraysIntersect, mapObject, extend} from '../util/util';\nimport {OverscaledTileID} from '../source/tile_id';\nimport {register} from '../util/web_worker_transfer';\nimport EvaluationParameters from '../style/evaluation_parameters';\nimport SourceFeatureState from '../source/source_state';\nimport {polygonIntersectsBox} from '../util/intersection_tests';\nimport {PossiblyEvaluated} from '../style/properties';\n\nimport type StyleLayer from '../style/style_layer';\nimport type {FeatureFilter} from '../style-spec/feature_filter';\nimport type Transform from '../geo/transform';\nimport type {FilterSpecification, PromoteIdSpecification} from '../style-spec/types';\n\nimport {FeatureIndexArray} from './array_types';\n\ntype QueryParameters = {\n scale: number,\n pixelPosMatrix: Float32Array,\n transform: Transform,\n tileSize: number,\n queryGeometry: Array,\n cameraQueryGeometry: Array,\n queryPadding: number,\n params: {\n filter: FilterSpecification,\n layers: Array,\n availableImages: Array\n }\n}\n\nclass FeatureIndex {\n tileID: OverscaledTileID;\n x: number;\n y: number;\n z: number;\n grid: Grid;\n grid3D: Grid;\n featureIndexArray: FeatureIndexArray;\n promoteId: ?PromoteIdSpecification;\n\n rawTileData: ArrayBuffer;\n bucketLayerIDs: Array>;\n\n vtLayers: {[_: string]: VectorTileLayer};\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.grid3D = new Grid(EXTENT, 16, 0);\n this.featureIndexArray = new FeatureIndexArray();\n this.promoteId = promoteId;\n }\n\n insert(feature: VectorTileFeature, geometry: Array>, featureIndex: number, sourceLayerIndex: number, bucketIndex: number, is3D?: boolean) {\n const key = this.featureIndexArray.length;\n this.featureIndexArray.emplaceBack(featureIndex, sourceLayerIndex, bucketIndex);\n\n const grid = is3D ? this.grid3D : 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]: VectorTileLayer} {\n if (!this.vtLayers) {\n this.vtLayers = new vt.VectorTile(new Protobuf(this.rawTileData)).layers;\n this.sourceLayerCoder = new DictionaryCoder(this.vtLayers ? Object.keys(this.vtLayers).sort() : ['_geojsonTileLayer']);\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): {[_: string]: Array<{ featureIndex: number, feature: GeoJSONFeature }>} {\n this.loadVTLayers();\n\n const params = args.params || {},\n pixelsToTileUnits = EXTENT / args.tileSize / args.scale,\n filter = featureFilter(params.filter);\n\n const queryGeometry = args.queryGeometry;\n const queryPadding = args.queryPadding * pixelsToTileUnits;\n\n const bounds = getBounds(queryGeometry);\n const matching = this.grid.query(bounds.minX - queryPadding, bounds.minY - queryPadding, bounds.maxX + queryPadding, bounds.maxY + queryPadding);\n\n const cameraBounds = getBounds(args.cameraQueryGeometry);\n const matching3D = this.grid3D.query(\n cameraBounds.minX - queryPadding, cameraBounds.minY - queryPadding, cameraBounds.maxX + queryPadding, cameraBounds.maxY + queryPadding,\n (bx1, by1, bx2, by2) => {\n return polygonIntersectsBox(args.cameraQueryGeometry, bx1 - queryPadding, by1 - queryPadding, bx2 + queryPadding, by2 + queryPadding);\n });\n\n for (const key of matching3D) {\n matching.push(key);\n }\n\n matching.sort(topDownFeatureComparator);\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.bucketIndex,\n match.sourceLayerIndex,\n match.featureIndex,\n filter,\n params.layers,\n params.availableImages,\n styleLayers,\n serializedLayers,\n sourceFeatureState,\n (feature: VectorTileFeature, styleLayer: StyleLayer, featureState: Object) => {\n if (!featureGeometry) {\n featureGeometry = loadGeometry(feature);\n }\n\n return styleLayer.queryIntersectsFeature(queryGeometry, feature, featureState, featureGeometry, this.z, args.transform, pixelsToTileUnits, args.pixelPosMatrix);\n }\n );\n }\n\n return result;\n }\n\n loadMatchingFeature(\n result: {[_: string]: Array<{ featureIndex: number, feature: GeoJSONFeature }>},\n bucketIndex: number,\n sourceLayerIndex: number,\n featureIndex: number,\n filter: FeatureFilter,\n filterLayerIDs: Array,\n availableImages: Array,\n styleLayers: {[_: string]: StyleLayer},\n serializedLayers: {[_: string]: Object},\n sourceFeatureState?: SourceFeatureState,\n intersectionTest?: (feature: VectorTileFeature, styleLayer: StyleLayer, featureState: Object, id: string | number | void) => boolean | number) {\n\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 if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) {\n return;\n }\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);\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: any).layer = serializedLayer;\n let layerResult = result[layerID];\n if (layerResult === undefined) {\n layerResult = result[layerID] = [];\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,\n serializedLayers: {[string]: StyleLayer},\n bucketIndex: number,\n sourceLayerIndex: number,\n filterSpec: FilterSpecification,\n filterLayerIDs: Array,\n availableImages: Array,\n styleLayers: {[_: string]: StyleLayer}) {\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 symbolFeatureIndex,\n filter,\n filterLayerIDs,\n availableImages,\n styleLayers,\n serializedLayers\n );\n\n }\n return result;\n }\n\n hasLayer(id: string) {\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: VectorTileFeature, 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 id = feature.properties[propName];\n if (typeof id === 'boolean') id = Number(id);\n }\n return id;\n }\n}\n\nregister(\n 'FeatureIndex',\n FeatureIndex,\n {omit: ['rawTileData', 'sourceLayerCoder']}\n);\n\nexport default FeatureIndex;\n\nfunction evaluateProperties(serializedProperties, styleLayerProperties, feature, featureState, availableImages) {\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 getBounds(geometry: Array) {\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const p of geometry) {\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 return {minX, minY, maxX, maxY};\n}\n\nfunction topDownFeatureComparator(a, b) {\n return b - a;\n}\n","// @flow\n\nimport {AlphaImage} from '../util/image';\nimport {register} from '../util/web_worker_transfer';\nimport potpack from 'potpack';\n\nimport type {GlyphMetrics, StyleGlyph} from '../style/style_glyph';\n\nconst padding = 1;\n\nexport type Rect = {\n x: number,\n y: number,\n w: number,\n h: number\n};\n\nexport type GlyphPosition = {\n rect: Rect,\n metrics: GlyphMetrics\n};\n\nexport type GlyphPositions = {[_: string]: {[_: number]: GlyphPosition } }\n\nexport default class GlyphAtlas {\n image: AlphaImage;\n positions: GlyphPositions;\n\n constructor(stacks: {[_: string]: {[_: number]: ?StyleGlyph } }) {\n const positions = {};\n const bins = [];\n\n for (const stack in stacks) {\n const glyphs = stacks[stack];\n const stackPositions = positions[stack] = {};\n\n for (const id in glyphs) {\n const src = glyphs[+id];\n if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) continue;\n\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 stackPositions[id] = {rect: bin, metrics: src.metrics};\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 glyphs = stacks[stack];\n\n for (const id in glyphs) {\n const src = glyphs[+id];\n if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) continue;\n const bin = positions[stack][id].rect;\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';\n\nimport {performSymbolLayout} from '../symbol/symbol_layout';\nimport {CollisionBoxArray} from '../data/array_types';\nimport DictionaryCoder from '../util/dictionary_coder';\nimport SymbolBucket from '../data/bucket/symbol_bucket';\nimport LineBucket from '../data/bucket/line_bucket';\nimport FillBucket from '../data/bucket/fill_bucket';\nimport FillExtrusionBucket from '../data/bucket/fill_extrusion_bucket';\nimport {warnOnce, mapObject, values} from '../util/util';\nimport assert from 'assert';\nimport ImageAtlas from '../render/image_atlas';\nimport GlyphAtlas from '../render/glyph_atlas';\nimport EvaluationParameters from '../style/evaluation_parameters';\nimport {OverscaledTileID} from './tile_id';\n\nimport type {Bucket} from '../data/bucket';\nimport type Actor from '../util/actor';\nimport type StyleLayer from '../style/style_layer';\nimport type StyleLayerIndex from '../style/style_layer_index';\nimport type {StyleImage} from '../style/style_image';\nimport type {StyleGlyph} from '../style/style_glyph';\nimport type {\n WorkerTileParameters,\n WorkerTileCallback,\n} from '../source/worker_source';\nimport type {PromoteIdSpecification} from '../style-spec/types';\n\nclass WorkerTile {\n tileID: OverscaledTileID;\n uid: string;\n zoom: number;\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\n status: 'parsing' | 'done';\n data: VectorTile;\n collisionBoxArray: CollisionBoxArray;\n\n abort: ?() => void;\n reloadCallback: WorkerTileCallback;\n vectorTile: VectorTile;\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.uid = params.uid;\n this.zoom = params.zoom;\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 }\n\n parse(data: VectorTile, layerIndex: StyleLayerIndex, availableImages: Array, actor: Actor, callback: WorkerTileCallback) {\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 const options = {\n featureIndex,\n iconDependencies: {},\n patternDependencies: {},\n glyphDependencies: {},\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 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\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 layers: family,\n zoom: this.zoom,\n pixelRatio: this.pixelRatio,\n overscaling: this.overscaling,\n collisionBoxArray: this.collisionBoxArray,\n sourceLayerIndex,\n sourceID: this.source\n });\n\n bucket.populate(features, options, this.tileID.canonical);\n featureIndex.bucketLayerIDs.push(family.map((l) => l.id));\n }\n }\n\n let error: ?Error;\n let glyphMap: ?{[_: string]: {[_: number]: ?StyleGlyph}};\n let iconMap: ?{[_: string]: StyleImage};\n let patternMap: ?{[_: string]: StyleImage};\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.call(this);\n }\n });\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.call(this);\n }\n });\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.call(this);\n }\n });\n } else {\n patternMap = {};\n }\n\n maybePrepare.call(this);\n\n function maybePrepare() {\n if (error) {\n return callback(error);\n } else if (glyphMap && iconMap && patternMap) {\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, glyphMap, glyphAtlas.positions, iconMap, imageAtlas.iconPositions, this.showCollisionBoxes, this.tileID.canonical);\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 bucket.addFeatures(options, this.tileID.canonical, imageAtlas.patternPositions);\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 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 }\n }\n }\n}\n\nfunction recalculateLayers(layers: $ReadOnlyArray, zoom: number, availableImages: Array) {\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 window from '../util/window';\nimport type {RequestParameters} from '../util/ajax';\n\nconst performance = window.performance;\n\nexport type PerformanceMetrics = {\n loadTime: number,\n fullLoadTime: number,\n fps: number,\n percentDroppedFrames: number\n}\n\nexport const PerformanceMarkers = {\n create: 'create',\n load: 'load',\n fullLoad: 'fullLoad'\n};\n\nlet lastFrameTime = null;\nlet frameTimes = [];\n\nconst minFramerateTarget = 30;\nconst frameTimeTarget = 1000 / minFramerateTarget;\n\nexport const PerformanceUtils = {\n mark(marker: $Keys) {\n performance.mark(marker);\n },\n frame(timestamp: number) {\n const currTimestamp = timestamp;\n if (lastFrameTime != null) {\n const frameTime = currTimestamp - lastFrameTime;\n frameTimes.push(frameTime);\n }\n lastFrameTime = currTimestamp;\n },\n clearMetrics() {\n lastFrameTime = null;\n frameTimes = [];\n performance.clearMeasures('loadTime');\n performance.clearMeasures('fullLoadTime');\n\n for (const marker in PerformanceMarkers) {\n performance.clearMarks(PerformanceMarkers[marker]);\n }\n },\n getPerformanceMetrics(): PerformanceMetrics {\n const loadTime = performance.measure('loadTime', PerformanceMarkers.create, PerformanceMarkers.load).duration;\n const fullLoadTime = performance.measure('fullLoadTime', PerformanceMarkers.create, PerformanceMarkers.fullLoad).duration;\n const totalFrames = frameTimes.length;\n\n const avgFrameTime = frameTimes.reduce((prev, curr) => prev + curr, 0) / totalFrames / 1000;\n const fps = 1 / avgFrameTime;\n\n // count frames that missed our framerate target\n const droppedFrames = frameTimes\n .filter((frameTime) => frameTime > frameTimeTarget)\n .reduce((acc, curr) => {\n return acc + (curr - frameTimeTarget) / frameTimeTarget;\n }, 0);\n const percentDroppedFrames = (droppedFrames / (totalFrames + droppedFrames)) * 100;\n\n return {\n loadTime,\n fullLoadTime,\n fps,\n percentDroppedFrames\n };\n }\n};\n\n/**\n * Safe wrapper for the performance resource timing API in web workers with graceful degradation\n *\n * @param {RequestParameters} request\n * @private\n */\nexport class RequestPerformance {\n _marks: {start: string, end: string, measure: string};\n\n constructor (request: RequestParameters) {\n this._marks = {\n start: [request.url, 'start'].join('#'),\n end: [request.url, 'end'].join('#'),\n measure: request.url.toString()\n };\n\n performance.mark(this._marks.start);\n }\n\n finish() {\n performance.mark(this._marks.end);\n let resourceTimingData = performance.getEntriesByName(this._marks.measure);\n\n // fallback if web worker implementation of perf.getEntriesByName returns empty\n if (resourceTimingData.length === 0) {\n performance.measure(this._marks.measure, this._marks.start, this._marks.end);\n resourceTimingData = performance.getEntriesByName(this._marks.measure);\n\n // cleanup\n performance.clearMarks(this._marks.start);\n performance.clearMarks(this._marks.end);\n performance.clearMeasures(this._marks.measure);\n }\n\n return resourceTimingData;\n }\n}\n\nexport default performance;\n","// @flow\n\nimport {getArrayBuffer} from '../util/ajax';\n\nimport vt from '@mapbox/vector-tile';\nimport Protobuf from 'pbf';\nimport WorkerTile from './worker_tile';\nimport {extend} from '../util/util';\nimport {RequestPerformance} from '../util/performance';\n\nimport type {\n WorkerSource,\n WorkerTileParameters,\n WorkerTileCallback,\n TileParameters\n} from '../source/worker_source';\n\nimport type Actor from '../util/actor';\nimport type StyleLayerIndex from '../style/style_layer_index';\nimport type {Callback} from '../types/callback';\n\nexport type LoadVectorTileResult = {\n vectorTile: VectorTile;\n rawData: ArrayBuffer;\n expires?: any;\n cacheControl?: any;\n resourceTiming?: Array;\n};\n\n/**\n * @callback LoadVectorDataCallback\n * @param error\n * @param vectorTile\n * @private\n */\nexport type LoadVectorDataCallback = Callback;\n\nexport type AbortVectorData = () => void;\nexport type LoadVectorData = (params: WorkerTileParameters, callback: LoadVectorDataCallback) => ?AbortVectorData;\n\n/**\n * @private\n */\nfunction loadVectorTile(params: WorkerTileParameters, 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: new vt.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/**\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 implements WorkerSource {\n actor: Actor;\n layerIndex: StyleLayerIndex;\n availableImages: Array;\n loadVectorData: LoadVectorData;\n loading: {[_: string]: WorkerTile };\n loaded: {[_: string]: WorkerTile };\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, loadVectorData: ?LoadVectorData) {\n this.actor = actor;\n this.layerIndex = layerIndex;\n this.availableImages = availableImages;\n this.loadVectorData = loadVectorData || loadVectorTile;\n this.loading = {};\n this.loaded = {};\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 if (!this.loading)\n this.loading = {};\n\n const perf = (params && params.request && params.request.collectResourceTiming) ?\n new RequestPerformance(params.request) : false;\n\n const workerTile = this.loading[uid] = new WorkerTile(params);\n workerTile.abort = this.loadVectorData(params, (err, response) => {\n delete this.loading[uid];\n\n if (err || !response) {\n workerTile.status = 'done';\n 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 const resourceTiming = {};\n if (perf) {\n const resourceTimingData = perf.finish();\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 resourceTiming.resourceTiming = JSON.parse(JSON.stringify(resourceTimingData));\n }\n\n workerTile.vectorTile = response.vectorTile;\n workerTile.parse(response.vectorTile, this.layerIndex, this.availableImages, this.actor, (err, result) => {\n if (err || !result) return callback(err);\n\n // Transferring a copy of rawTileData because the worker needs to retain its copy.\n callback(null, extend({rawTileData: rawTileData.slice(0)}, result, cacheControl, resourceTiming));\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\n const done = (err, data) => {\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 loading = this.loading,\n uid = params.uid;\n if (loading && loading[uid] && loading[uid].abort) {\n loading[uid].abort();\n delete 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\nimport {RGBAImage} from '../util/image';\n\nimport {warnOnce} from '../util/util';\nimport {register} from '../util/web_worker_transfer';\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 default class DEMData {\n uid: string;\n data: Uint32Array;\n stride: number;\n dim: number;\n encoding: \"mapbox\" | \"terrarium\";\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: string, data: RGBAImage, encoding: \"mapbox\" | \"terrarium\") {\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 this.data = new Uint32Array(data.data.buffer);\n this.encoding = encoding || 'mapbox';\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 this.data[this._idx(-1, x)] = this.data[this._idx(0, x)];\n // right vertical border\n this.data[this._idx(dim, x)] = this.data[this._idx(dim - 1, x)];\n // left horizontal border\n this.data[this._idx(x, -1)] = this.data[this._idx(x, 0)];\n // right horizontal border\n this.data[this._idx(x, dim)] = this.data[this._idx(x, dim - 1)];\n }\n // corners\n this.data[this._idx(-1, -1)] = this.data[this._idx(0, 0)];\n this.data[this._idx(dim, -1)] = this.data[this._idx(dim - 1, 0)];\n this.data[this._idx(-1, dim)] = this.data[this._idx(0, dim - 1)];\n this.data[this._idx(dim, dim)] = this.data[this._idx(dim - 1, dim - 1)];\n }\n\n get(x: number, y: number) {\n const pixels = new Uint8Array(this.data.buffer);\n const index = this._idx(x, y) * 4;\n const unpack = this.encoding === \"terrarium\" ? this._unpackTerrarium : this._unpackMapbox;\n return unpack(pixels[index], pixels[index + 1], pixels[index + 2]);\n }\n\n getUnpackVector() {\n return this.encoding === \"terrarium\" ? [256.0, 1.0, 1.0 / 256.0, 32768.0] : [6553.6, 25.6, 0.1, 10000.0];\n }\n\n _idx(x: number, y: 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 _unpackMapbox(r: number, g: number, b: 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\n _unpackTerrarium(r: number, g: number, b: 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\n getPixels() {\n return new RGBAImage({width: this.stride, height: this.stride}, new Uint8Array(this.data.buffer));\n }\n\n backfillBorder(borderTile: DEMData, dx: number, dy: number) {\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 this.data[this._idx(x, y)] = borderTile.data[this._idx(x + ox, y + oy)];\n }\n }\n }\n}\n\nregister('DEMData', DEMData);\n","// @flow\n\nimport DEMData from '../data/dem_data';\nimport {RGBAImage} from '../util/image';\nimport window from '../util/window';\n\nimport type Actor from '../util/actor';\nimport type {\n WorkerDEMTileParameters,\n WorkerDEMTileCallback,\n TileParameters\n} from './worker_source';\nconst {ImageBitmap} = window;\n\nclass RasterDEMTileWorkerSource {\n actor: Actor;\n loaded: {[_: string]: DEMData};\n offscreenCanvas: OffscreenCanvas;\n offscreenCanvasContext: CanvasRenderingContext2D;\n\n constructor() {\n this.loaded = {};\n }\n\n loadTile(params: WorkerDEMTileParameters, callback: WorkerDEMTileCallback) {\n const {uid, encoding, rawImageData} = params;\n // Main thread will transfer ImageBitmap if offscreen decode with OffscreenCanvas is supported, else it will transfer an already decoded image.\n const imagePixels = (ImageBitmap && rawImageData instanceof ImageBitmap) ? this.getImageData(rawImageData) : rawImageData;\n const dem = new DEMData(uid, imagePixels, encoding);\n this.loaded = this.loaded || {};\n this.loaded[uid] = dem;\n callback(null, dem);\n }\n\n getImageData(imgBitmap: ImageBitmap): RGBAImage {\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 this.offscreenCanvasContext = this.offscreenCanvas.getContext('2d');\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 an additional 1px padding around the image to allow backfilling for neighboring data.\n const imgData = this.offscreenCanvasContext.getImageData(-1, -1, imgBitmap.width + 2, imgBitmap.height + 2);\n this.offscreenCanvasContext.clearRect(0, 0, this.offscreenCanvas.width, this.offscreenCanvas.height);\n return new RGBAImage({width: imgData.width, height: imgData.height}, imgData.data);\n }\n\n removeTile(params: TileParameters) {\n const loaded = this.loaded,\n uid = params.uid;\n if (loaded && loaded[uid]) {\n delete loaded[uid];\n }\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 mvt from '@mapbox/vector-tile';\nconst toGeoJSON = mvt.VectorTileFeature.prototype.toGeoJSON;\nimport EXTENT from '../data/extent';\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>,\n}\n\nclass FeatureWrapper implements VectorTileFeature {\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() {\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) {\n return toGeoJSON.call(this, x, y, z);\n }\n}\n\nclass GeoJSONWrapper implements VectorTile, VectorTileLayer {\n layers: {[_: string]: VectorTileLayer};\n name: string;\n extent: number;\n length: number;\n _features: Array;\n\n constructor(features: Array) {\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): VectorTileFeature {\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 keyIndex = keycache[key]\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 value = feature.properties[key]\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","\nexport default function sortKD(ids, coords, nodeSize, left, right, depth) {\n if (right - left <= nodeSize) return;\n\n const m = (left + right) >> 1;\n\n select(ids, coords, m, left, right, depth % 2);\n\n sortKD(ids, coords, nodeSize, left, m - 1, depth + 1);\n sortKD(ids, coords, nodeSize, m + 1, right, depth + 1);\n}\n\nfunction select(ids, coords, k, left, right, inc) {\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, inc);\n }\n\n const t = coords[2 * k + inc];\n let i = left;\n let j = right;\n\n swapItem(ids, coords, left, k);\n if (coords[2 * right + inc] > 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 + inc] < t) i++;\n while (coords[2 * j + inc] > t) j--;\n }\n\n if (coords[2 * left + inc] === 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\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\nfunction swap(arr, i, j) {\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n","\nexport default function within(ids, coords, qx, qy, r, nodeSize) {\n const stack = [0, ids.length - 1, 0];\n const result = [];\n const r2 = r * r;\n\n while (stack.length) {\n const axis = stack.pop();\n const right = stack.pop();\n const left = stack.pop();\n\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 const m = Math.floor((left + right) / 2);\n\n const x = coords[2 * m];\n const y = coords[2 * m + 1];\n\n if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]);\n\n const nextAxis = (axis + 1) % 2;\n\n if (axis === 0 ? qx - r <= x : qy - r <= y) {\n stack.push(left);\n stack.push(m - 1);\n stack.push(nextAxis);\n }\n if (axis === 0 ? qx + r >= x : qy + r >= y) {\n stack.push(m + 1);\n stack.push(right);\n stack.push(nextAxis);\n }\n }\n\n return result;\n}\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 sort from './sort';\nimport range from './range';\nimport within from './within';\n\nconst defaultGetX = p => p[0];\nconst defaultGetY = p => p[1];\n\nexport default class KDBush {\n constructor(points, getX = defaultGetX, getY = defaultGetY, nodeSize = 64, ArrayType = Float64Array) {\n this.nodeSize = nodeSize;\n this.points = points;\n\n const IndexArrayType = points.length < 65536 ? Uint16Array : Uint32Array;\n\n const ids = this.ids = new IndexArrayType(points.length);\n const coords = this.coords = new ArrayType(points.length * 2);\n\n for (let i = 0; i < points.length; i++) {\n ids[i] = i;\n coords[2 * i] = getX(points[i]);\n coords[2 * i + 1] = getY(points[i]);\n }\n\n sort(ids, coords, nodeSize, 0, ids.length - 1, 0);\n }\n\n range(minX, minY, maxX, maxY) {\n return range(this.ids, this.coords, minX, minY, maxX, maxY, this.nodeSize);\n }\n\n within(x, y, r) {\n return within(this.ids, this.coords, x, y, r, this.nodeSize);\n }\n}\n","\nexport default function range(ids, coords, minX, minY, maxX, maxY, nodeSize) {\n const stack = [0, ids.length - 1, 0];\n const result = [];\n let x, y;\n\n while (stack.length) {\n const axis = stack.pop();\n const right = stack.pop();\n const left = stack.pop();\n\n if (right - left <= nodeSize) {\n for (let i = left; i <= right; i++) {\n x = coords[2 * i];\n 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 const m = Math.floor((left + right) / 2);\n\n x = coords[2 * m];\n y = coords[2 * m + 1];\n\n if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);\n\n const nextAxis = (axis + 1) % 2;\n\n if (axis === 0 ? minX <= x : minY <= y) {\n stack.push(left);\n stack.push(m - 1);\n stack.push(nextAxis);\n }\n if (axis === 0 ? maxX >= x : maxY >= y) {\n stack.push(m + 1);\n stack.push(right);\n stack.push(nextAxis);\n }\n }\n\n return result;\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\nexport default class Supercluster {\n constructor(options) {\n this.options = extend(Object.create(defaultOptions), options);\n this.trees = new Array(this.options.maxZoom + 1);\n }\n\n load(points) {\n const {log, minZoom, maxZoom, nodeSize} = 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 let clusters = [];\n for (let i = 0; i < points.length; i++) {\n if (!points[i].geometry) continue;\n clusters.push(createPointCluster(points[i], i));\n }\n this.trees[maxZoom + 1] = new KDBush(clusters, getX, getY, nodeSize, Float32Array);\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 clusters = this._cluster(clusters, z);\n this.trees[z] = new KDBush(clusters, getX, getY, nodeSize, Float32Array);\n\n if (log) console.log('z%d: %d clusters in %dms', z, clusters.length, +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 clusters = [];\n for (const id of ids) {\n const c = tree.points[id];\n clusters.push(c.numPoints ? getClusterJSON(c) : this.points[c.index]);\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 index = this.trees[originZoom];\n if (!index) throw new Error(errorMsg);\n\n const origin = index.points[originId];\n if (!origin) throw new Error(errorMsg);\n\n const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1));\n const ids = index.within(origin.x, origin.y, r);\n const children = [];\n for (const id of ids) {\n const c = index.points[id];\n if (c.parentId === clusterId) {\n children.push(c.numPoints ? getClusterJSON(c) : this.points[c.index]);\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.points, x, y, z2, tile);\n\n if (x === 0) {\n this._addTileFeatures(\n tree.range(1 - p / z2, top, 1, bottom),\n tree.points, z2, y, z2, tile);\n }\n if (x === z2 - 1) {\n this._addTileFeatures(\n tree.range(0, top, p / z2, bottom),\n tree.points, -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 _addTileFeatures(ids, points, x, y, z2, tile) {\n for (const i of ids) {\n const c = points[i];\n const isCluster = c.numPoints;\n const f = {\n type: 1,\n geometry: [[\n Math.round(this.options.extent * (c.x * z2 - x)),\n Math.round(this.options.extent * (c.y * z2 - y))\n ]],\n tags: isCluster ? getClusterProperties(c) : this.points[c.index].properties\n };\n\n // assign id\n let id;\n if (isCluster) {\n id = c.id;\n } else if (this.options.generateId) {\n // optionally generate id\n id = c.index;\n } else if (this.points[c.index].id) {\n // keep id if already assigned\n id = this.points[c.index].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(+z, this.options.maxZoom + 1));\n }\n\n _cluster(points, zoom) {\n const clusters = [];\n const {radius, extent, reduce, minPoints} = this.options;\n const r = radius / (extent * Math.pow(2, zoom));\n\n // loop through each point\n for (let i = 0; i < points.length; i++) {\n const p = points[i];\n // if we've already visited the point at this zoom level, skip it\n if (p.zoom <= zoom) continue;\n p.zoom = zoom;\n\n // find all nearby points\n const tree = this.trees[zoom + 1];\n const neighborIds = tree.within(p.x, p.y, r);\n\n const numPointsOrigin = p.numPoints || 1;\n let numPoints = numPointsOrigin;\n\n // count the number of points in a potential cluster\n for (const neighborId of neighborIds) {\n const b = tree.points[neighborId];\n // filter out neighbors that are already processed\n if (b.zoom > zoom) numPoints += b.numPoints || 1;\n }\n\n if (numPoints >= minPoints) { // enough points to form a cluster\n let wx = p.x * numPointsOrigin;\n let wy = p.y * numPointsOrigin;\n\n let clusterProperties = reduce && numPointsOrigin > 1 ? this._map(p, true) : null;\n\n // encode both zoom and point index on which the cluster originated -- offset by total length of features\n const id = (i << 5) + (zoom + 1) + this.points.length;\n\n for (const neighborId of neighborIds) {\n const b = tree.points[neighborId];\n\n if (b.zoom <= zoom) continue;\n b.zoom = zoom; // save the zoom (so it doesn't get processed twice)\n\n const numPoints2 = b.numPoints || 1;\n wx += b.x * numPoints2; // accumulate coordinates for calculating weighted center\n wy += b.y * numPoints2;\n\n b.parentId = id;\n\n if (reduce) {\n if (!clusterProperties) clusterProperties = this._map(p, true);\n reduce(clusterProperties, this._map(b));\n }\n }\n\n p.parentId = id;\n clusters.push(createCluster(wx / numPoints, wy / numPoints, id, numPoints, clusterProperties));\n\n } else { // left points as unclustered\n clusters.push(p);\n\n if (numPoints > 1) {\n for (const neighborId of neighborIds) {\n const b = tree.points[neighborId];\n if (b.zoom <= zoom) continue;\n b.zoom = zoom;\n clusters.push(b);\n }\n }\n }\n }\n\n return clusters;\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(point, clone) {\n if (point.numPoints) {\n return clone ? extend({}, point.properties) : point.properties;\n }\n const original = this.points[point.index].properties;\n const result = this.options.map(original);\n return clone && result === original ? extend({}, result) : result;\n }\n}\n\nfunction createCluster(x, y, id, numPoints, properties) {\n return {\n x, // weighted cluster center\n y,\n zoom: Infinity, // the last zoom the cluster was processed at\n id, // encodes index of the first child of the cluster and its zoom level\n parentId: -1, // parent cluster id\n numPoints,\n properties\n };\n}\n\nfunction createPointCluster(p, id) {\n const [x, y] = p.geometry.coordinates;\n return {\n x: lngX(x), // projected point coordinates\n y: latY(y),\n zoom: Infinity, // the last zoom the point was processed at\n index: id, // index of the source feature in the original input array,\n parentId: -1 // parent cluster id\n };\n}\n\nfunction getClusterJSON(cluster) {\n return {\n type: 'Feature',\n id: cluster.id,\n properties: getClusterProperties(cluster),\n geometry: {\n type: 'Point',\n coordinates: [xLng(cluster.x), yLat(cluster.y)]\n }\n };\n}\n\nfunction getClusterProperties(cluster) {\n const count = cluster.numPoints;\n const abbrev =\n count >= 10000 ? `${Math.round(count / 1000) }k` :\n count >= 1000 ? `${Math.round(count / 100) / 10 }k` : count;\n return extend(extend({}, cluster.properties), {\n cluster: true,\n cluster_id: cluster.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\nfunction extend(dest, src) {\n for (const id in src) dest[id] = src[id];\n return dest;\n}\n\nfunction getX(p) {\n return p.x;\n}\nfunction getY(p) {\n return p.y;\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';\n\nimport {RequestPerformance} from '../util/performance';\nimport rewind from '@mapbox/geojson-rewind';\nimport GeoJSONWrapper from './geojson_wrapper';\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';\nimport {createExpression} from '../style-spec/expression';\n\nimport type {\n WorkerTileParameters,\n WorkerTileCallback,\n} from '../source/worker_source';\n\nimport type Actor from '../util/actor';\nimport type StyleLayerIndex from '../style/style_layer_index';\n\nimport type {LoadVectorDataCallback} from './vector_tile_worker_source';\nimport type {RequestParameters, ResponseCallback} from '../util/ajax';\nimport type {Callback} from '../types/callback';\nimport type {GeoJSONFeature} from '@mapbox/geojson-types';\n\nexport type LoadGeoJSONParameters = {\n request?: RequestParameters,\n data?: string,\n source: string,\n cluster: boolean,\n superclusterOptions?: Object,\n geojsonVtOptions?: Object,\n clusterProperties?: Object,\n filter?: Array\n};\n\nexport type LoadGeoJSON = (params: LoadGeoJSONParameters, callback: ResponseCallback) => 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;\n getLeaves(clusterId: number, limit: number, offset: number): Array;\n}\n\nfunction loadGeoJSONTile(params: WorkerTileParameters, 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\nexport type SourceState =\n | 'Idle' // Source empty or data loaded\n | 'Coalescing' // Data finished loading, but discard 'loadData' messages until receiving 'coalesced'\n | 'NeedsLoadData'; // 'loadData' received while coalescing, trigger one more 'loadData' on receiving 'coalesced'\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 _state: SourceState;\n _pendingCallback: Callback<{\n resourceTiming?: {[_: string]: Array},\n abandoned?: boolean }>;\n _pendingLoadDataParams: LoadGeoJSONParameters;\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, loadGeoJSON: ?LoadGeoJSON) {\n super(actor, layerIndex, availableImages, 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<{\n resourceTiming?: {[_: string]: Array},\n abandoned?: boolean }>) {\n if (this._pendingCallback) {\n // Tell the foreground the previous call has been abandoned\n this._pendingCallback(null, {abandoned: true});\n }\n this._pendingCallback = callback;\n this._pendingLoadDataParams = params;\n\n if (this._state &&\n this._state !== 'Idle') {\n this._state = 'NeedsLoadData';\n } else {\n this._state = 'Coalescing';\n this._loadData();\n }\n }\n\n /**\n * Internal implementation: called directly by `loadData`\n * or by `coalesce` using stored parameters.\n */\n _loadData() {\n if (!this._pendingCallback || !this._pendingLoadDataParams) {\n assert(false);\n return;\n }\n const callback = this._pendingCallback;\n const params = this._pendingLoadDataParams;\n delete this._pendingCallback;\n delete this._pendingLoadDataParams;\n\n const perf = (params && params.request && params.request.collectResourceTiming) ?\n new RequestPerformance(params.request) : false;\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 = perf.finish();\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 * While processing `loadData`, we coalesce all further\n * `loadData` messages into a single call to _loadData\n * that will happen once we've finished processing the\n * first message. {@link GeoJSONSource#_updateWorkerData}\n * is responsible for sending us the `coalesce` message\n * at the time it receives a response from `loadData`\n *\n * State: Idle\n * ↑ |\n * 'coalesce' 'loadData'\n * | (triggers load)\n * | ↓\n * State: Coalescing\n * ↑ |\n * (triggers load) |\n * 'coalesce' 'loadData'\n * | ↓\n * State: NeedsLoadData\n */\n coalesce() {\n if (this._state === 'Coalescing') {\n this._state = 'Idle';\n } else if (this._state === 'NeedsLoadData') {\n this._state = 'Coalescing';\n this._loadData();\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) {\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 loadGeoJSON(params: LoadGeoJSONParameters, callback: ResponseCallback) {\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 removeSource(params: {source: string}, callback: Callback) {\n if (this._pendingCallback) {\n // Don't leak callbacks\n this._pendingCallback(null, {abandoned: true});\n }\n callback();\n }\n\n getClusterExpansionZoom(params: {clusterId: number}, callback: Callback) {\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>) {\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>) {\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}) {\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';\n\nimport StyleLayerIndex from '../style/style_layer_index';\nimport VectorTileWorkerSource from './vector_tile_worker_source';\nimport RasterDEMTileWorkerSource from './raster_dem_tile_worker_source';\nimport GeoJSONWorkerSource from './geojson_worker_source';\nimport assert from 'assert';\nimport {plugin as globalRTLTextPlugin} from './rtl_text_plugin';\nimport {enforceCacheSizeLimit} from '../util/tile_request_cache';\n\nimport type {\n WorkerSource,\n WorkerTileParameters,\n WorkerDEMTileParameters,\n WorkerTileCallback,\n WorkerDEMTileCallback,\n TileParameters\n} from '../source/worker_source';\n\nimport type {WorkerGlobalScopeInterface} from '../util/web_worker';\nimport type {Callback} from '../types/callback';\nimport type {LayerSpecification} from '../style-spec/types';\nimport type {PluginState} from './rtl_text_plugin';\n\n/**\n * @private\n */\nexport default class Worker {\n self: WorkerGlobalScopeInterface;\n actor: Actor;\n layerIndexes: {[_: string]: StyleLayerIndex };\n availableImages: {[_: string]: Array };\n workerSourceTypes: {[_: string]: Class };\n workerSources: {[_: string]: {[_: string]: {[_: string]: WorkerSource } } };\n demWorkerSources: {[_: string]: {[_: string]: RasterDEMTileWorkerSource } };\n referrer: ?string;\n\n constructor(self: WorkerGlobalScopeInterface) {\n this.self = self;\n this.actor = new Actor(self, this);\n\n this.layerIndexes = {};\n this.availableImages = {};\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) => {\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 setReferrer(mapID: string, referrer: string) {\n this.referrer = referrer;\n }\n\n setImages(mapId: string, images: Array, 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 setLayers(mapId: string, layers: Array, callback: WorkerTileCallback) {\n this.getLayerIndex(mapId).replace(layers);\n callback();\n }\n\n updateLayers(mapId: string, params: {layers: Array, removedIds: Array}, 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 this.getWorkerSource(mapId, params.type, params.source).loadTile(params, callback);\n }\n\n loadDEMTile(mapId: string, params: WorkerDEMTileParameters, callback: WorkerDEMTileCallback) {\n this.getDEMWorkerSource(mapId, params.source).loadTile(params, callback);\n }\n\n reloadTile(mapId: string, params: WorkerTileParameters & {type: string}, callback: WorkerTileCallback) {\n assert(params.type);\n this.getWorkerSource(mapId, params.type, params.source).reloadTile(params, 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 removeDEMTile(mapId: string, params: TileParameters) {\n this.getDEMWorkerSource(mapId, params.source).removeTile(params);\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) {\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) {\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) {\n let availableImages = this.availableImages[mapId];\n\n if (!availableImages) {\n availableImages = [];\n }\n\n return availableImages;\n }\n\n getLayerIndex(mapId: string) {\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) {\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, data, callback) => {\n this.actor.send(type, data, callback, mapId);\n }\n };\n this.workerSources[mapId][type][source] = new (this.workerSourceTypes[type]: any)((actor: any), this.getLayerIndex(mapId), this.getAvailableImages(mapId));\n }\n\n return this.workerSources[mapId][type][source];\n }\n\n getDEMWorkerSource(mapId: string, source: string) {\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\n/* global self, WorkerGlobalScope */\nif (typeof WorkerGlobalScope !== 'undefined' &&\n typeof self !== 'undefined' &&\n self instanceof WorkerGlobalScope) {\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","t0","t1","t2","x2","i","Math","abs","d2","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","MAX_SAFE_INTEGER","pow","clamp","n","min","max","values","obj","const","result","push","extend","dest","sources","src","uuid","random","toString","replace","validateUuid","str","test","endsWith","string","suffix","indexOf","length","mapObject","input","iterator","context","output","key","call","map","warnOnceHistory","warnOnce","message","console","warn","isCounterClockwise","c","calculateSignedArea","ring","let","sum","len","j","p1","p2","isWorker","WorkerGlobalScope","self","parseCacheControl","cacheControl","header","$0","$1","$2","$3","value","toLowerCase","maxAge","parseInt","isNaN","_isSafari","isSafari","scope","userAgent","navigator","safari","match","storageAvailable","type","storage","window","setItem","removeItem","e","GridIndex","extent","padding","cells","ArrayBuffer","arrayBuffer","array","Int32Array","d","start","end","subarray","bboxesOffset","keys","bboxes","insert","_insertReadonly","scale","uid","x1","y1","y2","_forEachCell","_insertCell","cellIndex","query","intersectionTest","slice","_queryCell","seenUids","cell","u","undefined","offset","fn","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","r","g","inputs","parse","rgba","parseCSSColor","toArray","ParsingError","super","Error","Scope","parent","bindings","concat","get","name","has","NullType","kind","NumberType","StringType","BooleanType","ColorType","ObjectType","ValueType","CollatorType","FormattedType","ResolvedImageType","itemType","N","valueMemberTypes","checkSubtype","expected","isValidType","provided","allowedTypes","some","isValidNativeType","Collator","caseSensitive","diacriticSensitive","locale","sensitivity","collator","Intl","usage","compare","lhs","rhs","resolvedLocale","resolvedOptions","FormattedSection","text","image","fontStack","textColor","Formatted","sections","fromString","unformatted","isEmpty","section","factory","join","serialize","serialized","options","ResolvedImage","available","validateRGBA","isValue","mixed","typeOf","String","JSON","stringify","Literal","args","error","expectedType","evaluate","eachChild","outputDefined","RuntimeError","toJSON","types","number","boolean","object","Assertion","parsed","ctx","forEach","every","arg","FormatExpression","firstArg","nextTokenMayBeObject","font","lastExpression","content","evaluatedContent","ImageExpression","evaluatedImageName","availableImages","to-boolean","to-color","to-number","to-string","Coercion","Boolean","parseColor","num","Number","valueToString","child","geometryTypes","EvaluationContext","globals","feature","featureState","formattedSection","_parseColorCache","canonical","id","geometryType","geometry","canonicalID","properties","cached","CompoundExpression","_evaluate","definition","definitions","availableOverloads","overloads","filter","signature","signatureContext","ParsingContext","registry","path","parsedArgs","argParseFailed","errors","signatures","actualTypes","register","CollatorExpression","updateBBox","bbox","coord","boxWithinBox","bbox1","bbox2","getTileCoordinates","PI","log","tilesAtZoom","z","rayIntersect","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","getTileLines","lineBBox","tileLines","tileLine","Infinity","Within","geojson","geometries","isFeatureConstant","isStateConstant","isGlobalPropertyConstant","features","polygonGeometry","tilePolygon","tilePolygons","pointsWithinPolygons","linesWithinPolygons","Var","boundExpression","part","findStopLessThanOrEqualTo","stops","currentValue","lastIndex","lowerIndex","upperIndex","currentIndex","expr","index","_parse","annotate","typeAnnotation","Expr","actual","isConstant","expression","isTypeAnnotation","childrenConstant","ec","Step","labels","outputs","outputType","label","labelKey","valueKey","stopCount","out","from","to","deg2rad","rad2deg","xyz2lab","lab2xyz","xyz2rgb","rgb2xyz","rgbToLab","rgbColor","labToRgb","labColor","interpolateHue","lab","forward","reverse","interpolate","interpolateNumber","hcl","hclColor","Interpolate","operator","interpolation","exponentialInterpolation","base","lowerValue","upperValue","difference","progress","interpolationFactor","lower","upper","controlPoints","rest","outputLower","outputUpper","Coalesce","needsAnnotation","requestedImageName","argCount","Let","At","In","needle","haystack","IndexOf","fromIndex","Match","inputType","cases","otherwise","labelContext","groupedByOutput","outputLookup","Object","sort","outputIndex","coerceLabel","Case","branches","Slice","beginIndex","endIndex","isComparableType","eqCollate","makeComparison","compareBasic","compareWithCollator","isOrderComparison","hasUntypedArgument","Comparison","lt","rt","Equals","NotEquals","LessThan","GreaterThan","LessThanOrEqual","GreaterThanOrEqual","NumberFormat","currency","minFractionDigits","maxFractionDigits","style","minimumFractionDigits","maximumFractionDigits","format","Length","expressions","==","!=",">","<",">=","<=","at","case","coalesce","in","index-of","interpolate-hcl","interpolate-lab","literal","number-format","step","var","within","v","varargs","success","supportsPropertyExpression","spec","supportsZoomExpression","parameters","supportsInterpolation","interpolated","getType","val","isFunction","identityFunction","evaluateCategoricalFunction","propertySpec","hashedStops","keyType","default","evaluateIntervalFunction","stop","evaluateExponentialFunction","interp","colorSpace","colorspace","colorSpaces","evaluatedLower","apply","evaluatedUpper","evaluateIdentityFunction","typeof","typeToString","to-rgba","rgb","feature-state","geometry-type","zoom","heatmap-density","heatmapDensity","line-progress","lineProgress","accumulated","+","*","-","/","%","ln2","LN2","pi","E","^","log10","LN10","ln","log2","asin","acos","atan","ceil","filter-==","filter-id-==","filter-type-==","filter-<","filter-id-<","filter->","filter-id->","filter-<=","filter-id-<=","filter->=","filter-id->=","filter-has","filter-has-id","filter-type-in","filter-id-in","filter-in-small","filter-in-large","binarySearch","all","any","!","is-supported-script","isSupportedScript","upcase","toUpperCase","downcase","resolved-locale","StyleExpression","_warningHistory","_evaluator","_defaultValue","getDefaultValue","_enumValues","isExpression","createExpression","parser","color","enum","formatted","resolvedImage","getExpectedType","evaluateWithoutErrorHandling","ZoomConstantExpression","_styleExpression","isStateDependent","ZoomDependentExpression","zoomStops","interpolationType","createPropertyExpression","isZoomConstant","zoomCurve","findZoomCurve","childResult","StylePropertyFunction","specification","_parameters","_specification","createFunction","innerFun","categoricalKeyType","isColor","zoomAndFeatureDependent","zoomDependent","property","create","featureFunctions","featureFunctionStops","bind","_","deserialize","klass","defineProperty","writeable","omit","shallow","Grid","grid","transferables","_classRegistryKey","isArrayBuffer","constructor","isImageBitmap","ImageBitmap","Date","RegExp","isView","view","ImageData","data","hasOwnProperty","$name","ThrottledInvoker","callback","_callback","_triggered","MessageChannel","_channel","port2","onmessage","trigger","port1","postMessage","setTimeout","remove","Actor","target","mapId","callbacks","tasks","taskQueue","cancelCallbacks","invoker","process","addEventListener","receive","globalScope","send","targetMapId","mustQueue","substring","buffers","hasCallback","sourceMapId","cancel","processTask","task","completed","done","err","getWorkerSource","source","removeEventListener","ValidationError","identifier","__line__","validateConstants","constants","unbundle","valueOf","deepUnbundle","unbundledValue","validateObject","elementSpecs","valueSpec","elementValidators","objectElementValidators","styleSpec","objectKey","elementSpecKey","elementSpec","validateElement","validateSpec","required","validateArray","arraySpec","validateArrayElement","arrayElementValidator","validate","arrayElementSpec","$version","function","arrayIndex","validateNumber","minimum","maximum","validateFunction","stopKeyType","previousStopDomainValue","previousStopDomainZoom","functionValueSpec","functionType","stopDomainValues","isZoomFunction","isPropertyFunction","isZoomAndPropertyFunction","validateFunctionStop","validateStopDomainValue","reportValue","isFinite","validateExpression","expressionContext","expressionObj","propertyKey","propertyType","validateEnum","isExpressionFilter","filterSpec","transition","property-type","createFilter","needGeometry","convertFilter","compiled","globalProperties","geometryNeeded","filters","convertComparisonOp","convertNegation","convertInOp","convertHasOp","validateFilter","validateNonExpressionFilter","filter_operator","geometry_type","validateProperty","layerSpec","layerType","transitionMatch","tokenMatch","tokens","exec","glyphs","validatePaintProperty","validateLayoutProperty","validateLayer","layer","ref","layerId","otherLayer","layers","sourceType","paint","lineMetrics","layout","validateString","promoteId","prop","validateSource","source_geojson","cluster","clusterProperties","reduceExpr","source_video","source_image","validateLight","light","lightSpec","rootType","VALIDATORS","validateStyleMin","latestStyleSpec","$root","validateGlyphsURL","sortErrors","wrapCleanErrors","inner","_addEventListener","listener","listenerList","_removeEventListener","splice","paintProperty","layoutProperty","Event","ErrorEvent","Evented","on","_listeners","off","_oneTimeListeners","once","fire","event","listens","_eventedParent","_eventedParentData","setEventedParent","validateStyle","ZoomHistory","first","update","now","floorZ","lastIntegerZoom","lastIntegerZoomTime","lastZoom","lastFloorZoom","unicodeBlockLookup","char","allowsVerticalWritingMode","chars","charHasUprightVerticalOrientation","charCodeAt","isChar","charHasRotatedVerticalOrientation","charHasNeutralVerticalOrientation","charInRTLScript","charInSupportedScript","canRenderRTL","stringContainsRTLText","glForTesting","webpImgTest","config","API_URL","EVENTS_URL","FEEDBACK_URL","REQUIRE_ACCESS_TOKEN","ACCESS_TOKEN","MAX_PARALLEL_IMAGE_REQUESTS","exported","performance","supported","gl","webpCheckComplete","webpImgTestOnloadComplete","testWebpTextureUpload","texture","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","isContextLost","deleteTexture","isMapboxURL","url","document","createElement","onload","onerror","mapboxHTTPURLRe","isMapboxHTTPURL","urlRe","parseAccessToken","accessToken","parts","decodeURIComponent","atob","TelemetryEvent","anonId","eventData","queue","pendingRequest","getStorageKey","domain","tokenData","btoa","encodeURIComponent","fromCharCode","telemEventKey","fetchEventData","isLocalStorageAvailable","storageKey","uuidKey","localStorage","getItem","saveEventData","processRequests","postEvent","timestamp","additionalPayload","customAccessToken","eventsUrlObject","protocol","authority","parseUrl","payload","created","toISOString","sdkIdentifier","skuId","userId","finalPayload","request","headers","Content-Type","body","postData","queueRequest","sharedCache","responseConstructorSupportsReadableStream","MapLoadEvent","skuToken","postMapLoadEvent","tileUrls","accessTokenIsSet","usesMapboxTiles","turnstileEvent_","_customAccessToken","postTurnstileEvent","lastSuccess","tokenU","dueForEvent","nextUpdate","lastUpdate","nextDate","daysElapsed","getDate","enabled.telemetry","mapLoadEvent_","cacheOpen","caches","open","stripQueryParameters","freeze","Unknown","Style","Source","Tile","Glyphs","SpriteImage","SpriteJSON","Image","AJAXError","status","getReferrer","worker","referrer","location","href","makeRequest","requestParameters","fetch","Request","AbortController","controller","method","credentials","signal","complete","aborted","cacheIgnoringSearch","validateOrFetch","cachedResponse","responseIsFresh","finishRequest","requestTime","then","response","ok","cacheableResponse","statusText","catch","code","json","Headers","toUTCString","getTime","Response","ReadableStream","blob","prepareBody","clonedResponse","cache","put","cachePut","strippedURL","fresh","expires","isFresh","delete","cacheGet","abort","makeFetchRequest","actor","xhr","XMLHttpRequest","responseType","setRequestHeader","withCredentials","getResponseHeader","makeXMLHttpRequest","pluginStatus","pluginURL","plugin","applyArabicShaping","processBidirectionalText","processStyledBidirectionalText","isLoaded","isLoading","setState","state","isParsed","getPluginURL","EvaluationParameters","fadeDuration","zoomHistory","isStringInSupportedScript","rtlTextPlugin","crossFadingFactor","getCrossfadeParameters","fraction","fromScale","toScale","PropertyValue","constant","normalizePropertyExpression","isDataDriven","possiblyEvaluate","TransitionablePropertyValue","transitioned","prior","TransitioningPropertyValue","untransitioned","Transitionable","_properties","_values","defaultTransitionablePropertyValues","getValue","setValue","getTransition","setTransition","Transitioning","begin","delay","duration","finalValue","t3","easeCubicInOut","defaultTransitioningPropertyValues","PossiblyEvaluated","hasTransition","Layout","defaultPropertyValues","PossiblyEvaluatedPropertyValue","constantOr","defaultPossiblyEvaluatedValues","DataConstantProperty","DataDrivenProperty","overrides","CrossFadedDataDrivenProperty","evaluatedValue","constantValue","_calculate","cameraVal","mid","CrossFadedProperty","ColorRampProperty","Properties","overridableProperties","overridable","defaultPropertyValue","defaultTransitionablePropertyValue","StyleLayer","_featureFilter","metadata","minzoom","maxzoom","sourceLayer","_unevaluatedLayout","_transitionablePaint","setPaintProperty","setLayoutProperty","_transitioningPaint","_crossfadeParameters","getLayoutProperty","visibility","_validate","getPaintProperty","transitionable","isCrossFadedProperty","wasDataDriven","oldValue","_handleSpecialPaintPropertyUpdate","newValue","_handleOverridablePaintPropertyUpdate","isHidden","updateTransitions","recalculate","source-layer","filterObject","emitter","hasErrors","emitValidationErrors","sprite","is3D","isTileClipped","hasOffscreenPass","resize","viewTypes","Int8","Int8Array","Uint8","Uint8Array","Int16","Int16Array","Uint16","Uint16Array","Int32","Uint32","Uint32Array","Float32","Float32Array","Struct","structArray","_structArray","_pos1","size","_pos2","_pos4","_pos8","StructArray","isTransferred","capacity","createLayout","members","alignment","maxSize","member","typeSize","BYTES_PER_ELEMENT","memberOffset","align","components","_trim","byteLength","bytesPerElement","_refreshViews","clear","reserve","oldUint8Array","uint8","StructArrayLayout2i4","int16","emplaceBack","v0","emplace","o2","StructArrayLayout4i8","v3","StructArrayLayout2i4i12","v4","v5","StructArrayLayout2i4ub8","o1","StructArrayLayout2f8","float32","o4","StructArrayLayout10ui20","uint16","v6","v7","v8","v9","StructArrayLayout4i4ui4i24","v10","v11","StructArrayLayout3f12","StructArrayLayout1ul4","uint32","StructArrayLayout6i1ul2ui20","StructArrayLayout2i2i2i12","StructArrayLayout2f1f2i16","StructArrayLayout2ub2f12","StructArrayLayout3ui6","StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48","v12","v13","v14","v15","v16","StructArrayLayout8i15ui1ul4f68","v17","v18","v19","v20","v21","v22","v23","v24","v25","v26","v27","StructArrayLayout1f4","StructArrayLayout3i6","StructArrayLayout1ul2ui8","StructArrayLayout2ui4","StructArrayLayout1ui2","StructArrayLayout4f16","CollisionBoxStruct","prototypeAccessors","anchorPointX","anchorPointY","featureIndex","sourceLayerIndex","bucketIndex","anchorPoint","CollisionBoxArray","PlacedSymbolStruct","prototypeAccessors$1","anchorX","anchorY","glyphStartIndex","numGlyphs","vertexStartIndex","lineStartIndex","lineLength","segment","lowerSize","upperSize","lineOffsetX","lineOffsetY","writingMode","placedOrientation","hidden","crossTileID","associatedIconIndex","PlacedSymbolArray","SymbolInstanceStruct","prototypeAccessors$2","rightJustifiedTextSymbolIndex","centerJustifiedTextSymbolIndex","leftJustifiedTextSymbolIndex","verticalPlacedTextSymbolIndex","placedIconSymbolIndex","verticalPlacedIconSymbolIndex","textBoxStartIndex","textBoxEndIndex","verticalTextBoxStartIndex","verticalTextBoxEndIndex","iconBoxStartIndex","iconBoxEndIndex","verticalIconBoxStartIndex","verticalIconBoxEndIndex","numHorizontalGlyphVertices","numVerticalGlyphVertices","numIconVertices","numVerticalIconVertices","useRuntimeCollisionCircles","textBoxScale","textOffset0","textOffset1","collisionCircleDiameter","SymbolInstanceArray","GlyphOffsetArray","getoffsetX","SymbolLineVertexArray","getx","gety","gettileUnitDistanceFromAnchor","FeatureIndexStruct","prototypeAccessors$3","FeatureIndexArray","SegmentVector","segments","packUint8ToFloat","prepareSegment","numVertices","layoutVertexArray","indexArray","sortKey","MAX_VERTEX_ARRAY_LENGTH","vertexLength","vertexOffset","primitiveOffset","primitiveLength","destroy","vaos","simpleSegment","patternAttributes","seed","remainder","bytes","h1","h1b","c1","c2","k1","murmur3","murmur2","FeaturePositionMap","ids","positions","indexed","getNumericId","getPositions","intId","Float64Array","left","right","pivot","swap","numValue","arr","tmp","Uniform","Uniform1f","current","uniform1i","uniform1f","Uniform4f","uniform2f","uniform3f","uniform4f","UniformColor","emptyMat4","packColor","uniformMatrix4fv","ConstantBinder","names","uniformNames","setUniform","uniform","getBinding","CrossFadedConstantBinder","patternFrom","patternTo","pixelRatioFrom","pixelRatioTo","setConstantPatternPositions","posTo","posFrom","pixelRatio","tlbr","uniformName","pos","SourceExpressionBinder","PaintVertexArray","maxValue","paintVertexAttributes","paintVertexArray","populatePaintArray","newLength","imagePositions","_setPaintValue","updatePaintArray","upload","paintVertexBuffer","updateData","createVertexBuffer","CompositeExpressionBinder","useIntegerZoom","minColor","maxColor","currentZoom","factor","CrossFadedCompositeBinder","zoomInPaintVertexArray","zoomOutPaintVertexArray","_setPaintValues","patterns","imageMin","imageMid","imageMax","tl","br","zoomInPaintVertexBuffer","zoomOutPaintVertexBuffer","ProgramConfiguration","filterProperties","binders","_buffers","paintAttributeNames","propType","isCrossFaded","StructArrayLayout","layoutType","cacheKey","getMaxValue","binder","populatePaintArrays","updatePaintArrays","featureStates","featureMap","vtLayer","dirty","defines","getBinderAttributes","getBinderUniforms","uniforms","getPaintVertexBuffers","getUniforms","locations","binding","setUniforms","binderUniforms","updatePaintBuffers","crossfade","patternVertexBuffer","ProgramConfigurationSet","programConfigurations","needsUpload","_featureMap","_bufferOffset","text-opacity","icon-opacity","text-color","icon-color","text-halo-color","icon-halo-color","text-halo-blur","icon-halo-blur","text-halo-width","icon-halo-width","line-gap-width","line-pattern","fill-pattern","fill-extrusion-pattern","binderType","defaultLayouts","composite","layoutException","PatternLayoutArray","getLayoutException","MAX","BITS","MIN","loadGeometry","toEvaluationFeature","addCircleVertex","extrudeX","extrudeY","CircleBucket","overscaling","layerIds","hasPattern","CircleLayoutArray","TriangleIndexArray","stateDependentLayerIds","polygonIntersectsPolygon","polygonA","polygonB","polygonContainsPoint","lineIntersectsLine","polygonIntersectsBufferedPoint","radius","pointIntersectsBufferedLine","polygonIntersectsMultiPolygon","multiPolygon","multiPolygonContainsPoint","lineIntersectsBufferedLine","lineA","lineB","a0","a1","lineSegmentIntersectsLineSegment","b0","b1","radiusSquared","distToSegmentSquared","w","l2","edgeIntersectsBox","e1","e2","corners","dir","getMaximumPaintValue","bucket","translateDistance","translate","queryGeometry","translateAnchor","bearing","pixelsToTileUnits","pt","translated","populate","styleLayer","bucketFeatures","circleSortKey","evaluationFeature","bucketFeature","addFeature","states","stateDependentLayers","uploadPending","uploaded","layoutVertexBuffer","layoutAttributes","indexBuffer","createIndexBuffer","circle-sort-key","circle-radius","circle-color","circle-blur","circle-opacity","circle-translate","circle-translate-anchor","circle-pitch-scale","circle-pitch-alignment","circle-stroke-width","circle-stroke-color","circle-stroke-opacity","ARRAY_TYPE","identity","transformMat4","hypot","arguments","glMatrix","CircleStyleLayer","createBucket","queryRadius","circleBucket","queryIntersectsFeature","transform","pixelPosMatrix","translatedPolygon","alignWithMap","transformedPolygon","projectPoint","projectQueryGeometry","transformedSize","transformedPoint","adjustedSize","projectedCenter","vec4","cameraToCenterDistance","HeatmapBucket","createImage","channels","Uint8ClampedArray","width","height","RangeError","resizeImage","newImage","copyImage","srcImg","dstImg","srcPt","dstPt","srcData","dstData","srcOffset","dstOffset","AlphaImage","copy","RGBAImage","heatmap-radius","heatmap-weight","heatmap-intensity","heatmap-color","heatmap-opacity","HeatmapStyleLayer","_updateColorRamp","colorRamp","evaluationGlobals","resolution","clips","renderPixel","stride","evaluationKey","pxColor","clip","renderColorRamp","colorRampTexture","heatmapFbo","hillshade-illumination-direction","hillshade-illumination-anchor","hillshade-exaggeration","hillshade-shadow-color","hillshade-highlight-color","hillshade-accent-color","HillshadeStyleLayer","earcut","holeIndices","dim","minX","minY","maxX","maxY","invSize","hasHoles","outerLen","outerNode","linkedList","triangles","next","prev","list","steiner","getLeftmost","compareX","eliminateHole","filterPoints","eliminateHoles","earcutLinked","clockwise","last","signedArea","insertNode","removeNode","again","area","ear","pass","zOrder","prevZ","nextZ","q","tail","numMerges","pSize","qSize","inSize","sortLinked","indexCurve","isEarHashed","isEar","cureLocalIntersections","splitEarcut","pointInTriangle","maxTX","maxTY","minZ","maxZ","intersects","locallyInside","isValidDiagonal","splitPolygon","hole","hx","hy","qx","mx","my","tanMin","sectorContainsSector","findHoleBridge","leftmost","px","py","intersectsPolygon","middleInside","sign","o3","onSegment","a2","Node","b2","an","bp","quickselect","quickselectStep","exp","sd","defaultCompare","classifyRings","maxRings","ccw","compareAreas","patternDependencies","patternProperty","constantPattern","addPatternDependencies","patternFeature","patternPropertyValue","deviation","polygonArea","trianglesArea","flatten","vertices","holes","dimensions","holeIndex","FillBucket","patternFeatures","FillLayoutArray","indexArray2","LineIndexArray","segments2","fillSortKey","addFeatures","indexBuffer2","triangleSegment","triangleIndex","flattened","lineSegment","lineIndex","indices","fill-sort-key","fill-antialias","fill-opacity","fill-color","fill-outline-color","fill-translate","fill-translate-anchor","FillStyleLayer","outlineColor","VectorTileFeature","pbf","_pbf","_geometry","_keys","readFields","readFeature","tag","readVarint","readTag","cmd","lines","cmdLen","readSVarint","toGeoJSON","x0","y0","coords","project","points","VectorTileLayer","version","_features","readLayer","readString","readFloat","readDouble","readVarint64","readBoolean","readValueMessage","readTile","require","vectorTileFeatureTypes","mvt","FACTOR","addVertex","vertexArray","nx","ny","nz","FillExtrusionBucket","FillExtrusionLayoutArray","isBoundaryEdge","edgeDistance","bottomRight","fill-extrusion-opacity","fill-extrusion-color","fill-extrusion-translate","fill-extrusion-translate-anchor","fill-extrusion-height","fill-extrusion-base","fill-extrusion-vertical-gradient","FillExtrusionStyleLayer","projectedQueryGeometry","projected","zBase","zTop","projectedBase","projectedTop","baseXZ","baseYZ","baseZZ","baseWZ","topXZ","topYZ","topZZ","topWZ","ringBase","ringTop","sX","sY","sZ","sW","baseZ","baseW","topX","topY","topZ","topW","projectExtrusion","closestDistance","getIntersectionDistance","topA","face","checkIntersection","dot","projectedFace","ab","ac","ap","dotABAB","dotABAC","dotACAC","dotAPAB","dotAPAC","denom","distance","COS_HALF_SHARP_CORNER","MAX_LINE_DISTANCE","LINE_DISTANCE_BUFFER_BITS","LineBucket","lineClipsArray","gradients","LineLayoutArray","layoutVertexArray2","LineExtLayoutArray","maxLineLength","lineSortKey","patternBucketFeature","layoutVertexBuffer2","layoutAttributesExt","lineFeatureClips","cap","miterLimit","roundLimit","lineClips","addLine","scaledDistance","totalDistance","updateScaledDistance","isPolygon","currentVertex","sharpCornerOffset","SHARP_CORNER_OFFSET","prevVertex","nextVertex","prevNormal","nextNormal","joinNormal","cosAngle","cosHalfAngle","miterLength","approxAngle","isSharpCorner","lineTurnsLeft","prevSegmentLength","newPrevVertex","updateDistance","addCurrentVertex","middleVertex","currentJoin","bevelLength","offsetA","offsetB","extrude","addHalfVertex","nextSegmentLength","newCurrentVertex","normal","endLeft","endRight","rightX","rightY","up","linesofarScaled","line-cap","line-join","line-miter-limit","line-round-limit","line-sort-key","line-opacity","line-color","line-translate","line-translate-anchor","line-width","line-offset","line-blur","line-dasharray","line-gradient","lineFloorwidthProperty","LineStyleLayer","gradientVersion","stepInterpolant","gradientExpression","lineBucket","getLineWidth","halfWidth","lineOffset","newRings","zero","newRing","aToB","bToC","offsetLine","multiLine","polygonIntersectsBufferedMultiLine","lineWidth","lineGapWidth","symbolLayoutAttributes","dynamicLayoutAttributes","collisionVertexAttributes","collisionBoxLayout","toLocaleUpperCase","toLocaleLowerCase","transformText","verticalizedCharacterMap","#","$","&","(",")",",",".",":",";","=","?","@","[","\\","]","`","{","|","}","~","¢","£","¥","¦","¬","¯","–","—","‘","’","“","”","…","‧","₩","、","。","〈","〉","《","》","「","」","『","』","【","】","〔","〕","〖","〗","!","(",")",",","-",".",":",";","<",">","?","[","]","_","{","|","}","⦅","⦆","。","「","」","isLE","mLen","nBytes","eLen","eMax","eBias","nBits","NaN","Pbf","buf","Varint","Fixed64","Bytes","Fixed32","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","potpack","boxes","maxWidth","box","spaces","space","fill","readField","skip","readMessage","readFixed32","readSFixed32","readFixed64","readSFixed64","ieee754","readVarintRemainder","decode","readUtf8TextDecoder","b3","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","ImagePosition","paddedRect","stretchX","stretchY","displaySize","IMAGE_PADDING","ImageAtlas","icons","iconPositions","patternPositions","haveRenderCallbacks","bins","addImages","bin","images","hasRenderCallback","patchUpdatedImages","imageManager","dispatchRenderCallbacks","updatedImages","patchUpdatedImage","getImage","position","WritingMode","horizontal","vertical","horizontalOnly","SectionOptions","imageName","forText","textOptions","forImage","imageOptions","TaggedString","sectionIndex","imageSectionID","shapeText","glyphMap","glyphPositions","defaultFontStack","lineHeight","textAnchor","textJustify","spacing","allowVerticalPlacement","symbolPlacement","layoutTextSize","layoutTextSizeThisZoom","logicalInput","fromFeature","verticalizePunctuation","determineLineBreaks","taggedLine","lineBreakPoints","lineBreak","breakLines","positionedLines","shaping","top","bottom","iconsInText","verticalizable","maxLineHeight","justify","trim","lineMaxScale","getMaxScale","maxLineOffset","positionedLine","positionedGlyphs","getSection","getSectionIndex","codePoint","getCharCode","baselineOffset","metrics","rect","verticalAdvance","whitespace","imagePosition","advance","glyphPosition","glyph","justifyLine","currentLineHeight","getAnchorAlignment","horizontalAlign","verticalAlign","blockHeight","lineCount","shiftY","shiftX","positionedGlyph","shapeLines","addImageSection","addTextSection","nextCharCode","prevCharCode","beginningWhitespace","trailingWhitespace","reduce","nextImageSectionCharCode","getNextImageSectionCharCode","breakable","getGlyphAdvance","calculateBadness","targetWidth","penalty","isLastBreak","raggedness","calculatePenalty","nextCodePoint","penalizableIdeographicBreak","evaluateBreak","breakIndex","breakX","potentialBreaks","bestPriorBreak","bestBreakBadness","potentialBreak","breakBadness","badness","priorBreak","potentialLineBreaks","totalWidth","determineAverageLineWidth","hasServerSuggestedBreakpoints","currentX","ideographicBreak","leastBadBreaks","lastLineBreak","anchor","lastPositionedGlyph","lineIndent","fitIconToText","shapedIcon","shapedText","textFit","iconOffset","fontScale","collisionPadding","textLeft","textRight","textTop","textBottom","Anchor","getSizeData","tileZoom","minZoom","maxZoom","checkMaxAngle","labelLength","windowSize","maxAngle","anchorDistance","recentCorners","recentAngleDelta","angleDelta","getLineLength","getAngleWindowSize","glyphSize","boxScale","getShapedLabelLength","getCenterAnchor","angleWindowSize","prevDistance","centerDistance","segmentDistance","getAnchors","tileExtent","shapedLabelLength","isLineContinued","resample","placeAtMiddle","halfLabelLength","markedDistance","anchors","segmentDist","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","tr","bl","pixelOffsetTL","pixelOffsetBR","matrix","tex","glyphOffset","isSDF","xCuts","stretchZonesToCuts","yCuts","xi","yi","ranges","stretchZones","fixedSize","stretchSize","cuts","stretchOffset","iconSize","fixedOffset","CollisionFeature","collisionBoxArray","shaped","alignLine","boxStartIndex","circleDiameter","rotateRadians","boxEndIndex","TinyQueue","_down","polygonRings","precision","debug","outerRing","cellSize","cellQueue","Queue","compareMax","Cell","bestCell","getCentroidCell","numProbes","minDistSq","pointToPolygonDist","SQRT2","item","_up","peek","halfLength","best","INVALID_TEXT_OFFSET","POSITIVE_INFINITY","performSymbolLayout","imageMap","showCollisionBoxes","createArrays","tilePixelRatio","compareText","iconsNeedLinear","unevaluatedLayoutValues","sizes","textSizeData","compositeTextSizes","iconSizeData","compositeIconSizes","layoutIconSize","textMaxSize","textAlongLine","keepUpright","textSize","fontstack","shapedTextOrientations","textOffset","unformattedText","spacingIfAllowed","allowsLetterSpacing","variableTextAnchor","radialOffset","offsetX","offsetY","fromTextOffset","hypotenuse","fromRadialOffset","addVerticalShapingForPointLabelIfNeeded","justifications","getAnchorJustification","singleLine","justification","icon","iconAnchor","shapeIcon","sdf","sdfIcons","getDefaultHorizontalShaping","verticallyShapedIcon","defaultHorizontalShaping","textMaxBoxScale","iconBoxScale","symbolMinDistance","textPadding","iconPadding","textMaxAngle","iconAlongLine","textRepeatDistance","iconTextFit","addSymbolAtAnchor","textCollisionFeature","iconCollisionFeature","verticalTextCollisionFeature","verticalIconCollisionFeature","lineArray","addToLineVertexArray","placedTextSymbolIndices","verticalTextRotation","iconQuads","verticalIconQuads","sizeData","MAX_GLYPH_ICON_SIZE","addSymbols","placedSymbolArray","textRotate","addTextVertices","getCollisionCircleHeight","prevHeight","glyphOffsetArray","SymbolBucket","MAX_GLYPHS","addToSortKeyRanges","symbolInstances","center","addSymbol","clippedLines","clippedLine","p0","clipLine","anchorIsTooClose","poi","findPoleOfInaccessibility","generateCollisionDebugBuffers","placementTypes","placedIconIndex","glyphQuads","alongLine","textureRect","rectBuffer","GLYPH_PBF_BORDER","rotateVerticalGlyph","halfAdvance","builtInOffset","verticalizedLabelOffset","verticalRotation","xHalfWidthOffsetCorrection","ONE_EM","halfWidthOffsetCorrection","verticalOffsetCorrection","getGlyphQuads","horizontalShaping","repeatDistance","otherAnchors","shaderOpacityAttributes","ox","oy","tx","ty","sizeVertex","pixelOffsetX","pixelOffsetY","minFontScaleX","minFontScaleY","aSizeX","aSizeY","addDynamicAttributes","dynamicLayoutVertexArray","containsRTLText","formattedText","SymbolBuffers","SymbolLayoutArray","SymbolDynamicLayoutArray","opacityVertexArray","SymbolOpacityArray","dynamicIndexBuffer","dynamicLayoutVertexBuffer","opacityVertexBuffer","itemSize","CollisionBuffers","LayoutArray","IndexArray","collisionVertexArray","CollisionVertexArray","collisionVertexBuffer","hasRTLText","sortKeyRanges","collisionCircleArray","placementInvProjMatrix","mat4","placementViewportMatrix","canOverlap","sortFeaturesByKey","sortFeaturesByY","writingModes","wm","sourceID","lineVertexArray","calculateGlyphDependencies","stack","doesAllowVerticalWritingMode","verticalChar","charAt","textFont","textField","iconImage","hasText","hasIcon","symbolSortKey","iconDependencies","stacks","glyphDependencies","resolvedTokens","getValueAndResolveTokens","globalRTLTextPlugin","sectionFont","sectionStack","leftIndex","rightIndex","mergedFeatures","mergedIndex","mergeFromRight","leftKey","rightKey","geom","mergeFromLeft","getKey","onRight","mergeLines","hasDebugData","textCollisionBox","iconCollisionBox","destroyDebugData","sumForwardLength","sumBackwardLength","tileUnitDistanceFromAnchor","vertex","arrays","labelAnchor","glyphOffsetArrayStart","_addCollisionDebugVertex","addCollisionDebugVertices","boxAnchorPoint","symbolInstance","addDebugCollisionBoxes","startIndex","isText","CollisionBoxLayoutArray","_deserializeCollisionBoxesForSymbol","textStartIndex","textEndIndex","verticalTextStartIndex","verticalTextEndIndex","iconStartIndex","iconEndIndex","verticalIconStartIndex","verticalIconEndIndex","collisionArrays","textBox","textFeatureIndex","verticalTextBox","verticalTextFeatureIndex","iconBox","iconFeatureIndex","verticalIconBox","verticalIconFeatureIndex","deserializeCollisionBoxes","hasTextData","hasIconData","hasTextCollisionBoxData","hasIconCollisionBoxData","addIndicesForPlacedSymbol","iconOrText","placedSymbolIndex","placedSymbol","vertexIndex","getSortedSymbolIndexes","sortedAngle","symbolInstanceIndexes","rotatedYs","featureIndexes","aIndex","bIndex","symbolInstanceIndex","symbolInstanceEnd","symbolInstanceStart","sortFeatures","featureSortOrder","symbol-placement","symbol-spacing","symbol-avoid-edges","symbol-sort-key","symbol-z-order","icon-allow-overlap","icon-ignore-placement","icon-optional","icon-rotation-alignment","icon-size","icon-text-fit","icon-text-fit-padding","icon-image","icon-rotate","icon-padding","icon-keep-upright","icon-offset","icon-anchor","icon-pitch-alignment","text-pitch-alignment","text-rotation-alignment","text-field","text-font","text-size","text-max-width","text-line-height","text-letter-spacing","text-justify","text-radial-offset","text-variable-anchor","text-anchor","text-max-angle","text-writing-mode","text-rotate","text-padding","text-keep-upright","text-transform","text-offset","text-allow-overlap","text-ignore-placement","text-optional","icon-translate","icon-translate-anchor","runtimeType","getOverride","o","hasOverride","text-translate","text-translate-anchor","FormatSectionOverride","defaultValue","SymbolStyleLayer","deduped","_setPaintOverrides","unevaluated","resolveTokens","hasPaintOverride","overriden","override","styleExpression","_interpolationType","propertyName","hasOverrides","checkSections","checkExpression","background-color","background-pattern","background-opacity","BackgroundStyleLayer","raster-opacity","raster-hue-rotate","raster-brightness-min","raster-brightness-max","raster-saturation","raster-contrast","raster-resampling","raster-fade-duration","RasterStyleLayer","CustomStyleLayer","implementation","renderingMode","prerender","onAdd","painter","onRemove","subclasses","circle","heatmap","hillshade","fill-extrusion","fillExtrusion","symbol","background","raster","createStyleLayer","refProperties","StyleLayerIndex","layerConfigs","keyCache","_layerConfigs","_layers","removedIds","layerConfig","featureFilter","familiesBySource","cachedKeys","groups","group","groupByLayout","sourceId","sourceGroup","sourceLayerId","sourceLayerFamilies","DictionaryCoder","strings","_stringToNumber","_numberToString","encode","Feature","vectorTileFeature","_vectorTileFeature","_z","_x","_y","getMercCoords","LngLatBounds","sw","ne","setSouthWest","setNorthEast","_ne","LngLat","lng","lat","_sw","sw2","ne2","getCenter","getSouthWest","getNorthEast","getNorthWest","getWest","getNorth","getSouthEast","getEast","getSouth","contains","lnglat","containsLongitude","wrap","distanceTo","lngLat","rad","lat1","lat2","toBounds","latAccuracy","lngAccuracy","lon","earthCircumfrence","circumferenceAtLatitude","latitude","latFromMercatorY","MercatorCoordinate","fromLngLat","lngLatLike","altitude","mercatorZfromAltitude","toLngLat","toAltitude","meterInMercatorCoordinateUnits","CanonicalTileID","calculateKey","urls","scheme","quadkey","mask","getQuadkey","getTilePoint","UnwrappedTileID","OverscaledTileID","overscaledZ","scaledTo","targetZ","zDifference","calculateScaledKey","withWrap","isChildOf","children","sourceMaxZoom","isLessThan","wrapped","unwrapTo","overscaleFactor","toUnwrapped","FeatureIndex","tileID","grid3D","featureIndexArray","evaluateProperties","serializedProperties","styleLayerProperties","getBounds","topDownFeatureComparator","loadVTLayers","vtLayers","vt","VectorTile","Protobuf","rawTileData","sourceLayerCoder","styleLayers","serializedLayers","sourceFeatureState","tileSize","queryPadding","bounds","matching","cameraBounds","cameraQueryGeometry","matching3D","bx1","by1","bx2","by2","boxX1","boxY1","boxX2","boxY2","polygonIntersectsBox","previousIndex","featureGeometry","loadMatchingFeature","filterLayerIDs","layerIDs","bucketLayerIDs","arraysIntersect","sourceLayerName","getId","layerID","getState","serializedLayer","intersectionZ","geojsonFeature","GeoJSONFeature","layerResult","lookupSymbolFeatures","symbolFeatureIndexes","hasLayer","GlyphAtlas","stackPositions","bitmap","WorkerTile","collectResourceTiming","returnDependencies","recalculateLayers","layerIndex","iconMap","patternMap","buckets","layerFamilies","family","maybePrepare","glyphAtlas","imageAtlas","glyphAtlasImage","RequestPerformance","_marks","measure","mark","loadVectorTile","getArrayBuffer","vectorTile","rawData","resourceTimingData","getEntriesByName","clearMarks","clearMeasures","VectorTileWorkerSource","loadVectorData","loading","loaded","loadTile","perf","workerTile","resourceTiming","reloadTile","vtSource","reloadCallback","abortTile","removeTile","DEMData","encoding","_idx","pixels","_unpackTerrarium","_unpackMapbox","getUnpackVector","getPixels","backfillBorder","borderTile","xMin","xMax","yMin","yMax","RasterDEMTileWorkerSource","rewindRings","outer","rewindRing","imagePixels","rawImageData","getImageData","dem","imgBitmap","offscreenCanvas","offscreenCanvasContext","OffscreenCanvas","getContext","drawImage","imgData","clearRect","FeatureWrapper","_feature","tags","GeoJSONWrapper","_geojsonTileLayer","rawGeometry","fromVectorTileJs","tile","writeLayer","writeTile","keycache","valuecache","writeFeature","writeValue","writeProperties","writeGeometry","keyIndex","valueIndex","command","zigzag","count","swapItem","sqDist","defaultGetX","defaultGetY","KDBush","getX","getY","nodeSize","ArrayType","IndexArrayType","sortKD","depth","select","inc","axis","nextAxis","qy","r2","defaultOptions","minPoints","generateId","props","Supercluster","trees","createCluster","numPoints","parentId","createPointCluster","lngX","latY","getClusterJSON","getClusterProperties","abbrev","cluster_id","point_count","point_count_abbreviated","getSqSegDist","createFeature","calcLineBBox","calcBBox","convertFeature","tolerance","convertPoint","convertLine","convertLines","projectX","projectY","simplify","sqTolerance","maxSqDist","minPosToMid","posToMid","k2","minAll","maxAll","clipped","newGeometry","clipPoints","clipLines","newGeom","trackMetrics","segLen","newSlice","intersect","intersectX","intersectY","az","exited","addPoint","shiftFeatureCoords","newFeatures","shiftCoords","newPolygon","newPoints","transformTile","transformed","z2","transformPoint","createTile","numSimplified","numFeatures","simplified","tileFeature","isOuter","rewind","GeoJSONVT","time","tiles","tileCoords","timeEnd","indexMaxZoom","indexMaxPoints","stats","total","merged","splitTile","toID","loadGeoJSONTile","_geoJSONIndex","geoJSONTile","getTile","geojsonWrapper","vtpbf","byteOffset","load","timerId","clusters","_cluster","getClusters","minLng","minLat","maxLng","maxLat","easternHem","westernHem","tree","_limitZoom","getChildren","clusterId","originId","_getOriginId","originZoom","_getOriginZoom","errorMsg","origin","getLeaves","limit","leaves","_appendLeaves","_addTileFeatures","getClusterExpansionZoom","expansionZoom","skipped","isCluster","neighborIds","numPointsOrigin","wx","wy","_map","numPoints2","original","cz","k3","k4","z0","GeoJSONWorkerSource","loadGeoJSON","loadData","_pendingCallback","abandoned","_pendingLoadDataParams","_state","_loadData","gj","superclusterOptions","mapExpressions","reduceExpressions","propertyNames","mapExpressionParsed","reduceExpressionParsed","pointProperties","getSuperclusterOptions","geojsonvt","geojsonVtOptions","getJSON","removeSource","getClusterChildren","getClusterLeaves","Worker","layerIndexes","workerSourceTypes","vector","workerSources","demWorkerSources","registerWorkerSource","WorkerSource","registerRTLTextPlugin","setReferrer","mapID","setImages","workerSource","ws","setLayers","getLayerIndex","updateLayers","loadDEMTile","getDEMWorkerSource","removeDEMTile","loadWorkerSource","importScripts","syncRTLPluginState","getAvailableImages","enforceCacheSizeLimit"],"mappings":"qCA4BAA,MAAiBC,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,IAAME,EACXC,KAAKF,IAAMA,EACXE,KAAKD,IAAMA,EAGfJ,EAAWY,UAAUC,aAAe,SAASC,GAEzC,aAAcN,GAAKM,EAAIT,KAAKE,IAAMO,EAAIT,KAAKC,IAAMQ,GAGrDd,EAAWY,UAAUG,aAAe,SAASD,GACzC,aAAcH,GAAKG,EAAIT,KAAKK,IAAMI,EAAIT,KAAKI,IAAMK,GAGrDd,EAAWY,UAAUI,uBAAyB,SAASF,GACnD,SAAcT,KAAKG,GAAKM,EAAI,EAAMT,KAAKE,IAAMO,EAAIT,KAAKC,IAG1DN,EAAWY,UAAUK,YAAc,SAASC,EAAGC,GAG3C,IAAIC,EAAIC,EAAIC,EAAIC,EAAIC,EAGpB,SALuB,IAAZL,IAAyBA,EAAU,MAKzCG,EAAKJ,EAAGM,EAAI,EAAGA,EAAI,EAAGA,IAAK,CAG5B,GADAD,EAAKlB,KAAKQ,aAAaS,GAAMJ,EACzBO,KAAKC,IAAIH,GAAMJ,EAAS,OAAOG,EAEnC,IAAIK,EAAKtB,KAAKW,uBA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