{"version":3,"file":"mapbox-gl-csp.js","sources":["../node_modules/@mapbox/mapbox-gl-supported/index.js","../node_modules/@mapbox/unitbezier/index.js","../node_modules/@mapbox/point-geometry/index.js","../src/util/browser/window.js","../src/style-spec/util/deep_equal.js","../src/util/util.js","../src/util/browser.js","../src/util/dom.js","../src/util/config.js","../src/util/webp_supported.js","../src/util/sku_token.js","../src/util/mapbox.js","../src/util/tile_request_cache.js","../src/util/offscreen_canvas_supported.js","../src/util/ajax.js","../src/util/evented.js","../src/style-spec/error/validation_error.js","../src/style-spec/validate/validate_constants.js","../src/style-spec/util/extend.js","../src/style-spec/util/unbundle_jsonlint.js","../src/style-spec/expression/parsing_error.js","../src/style-spec/expression/scope.js","../src/style-spec/expression/types.js","../node_modules/csscolorparser/csscolorparser.js","../src/style-spec/util/color.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/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/style/validate_style.js","../node_modules/grid-index/grid-index.js","../src/util/web_worker_transfer.js","../src/style/zoom_history.js","../src/util/is_char_in_unicode_block.js","../src/util/script_detection.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/vec3.js","../node_modules/gl-matrix/esm/vec4.js","../node_modules/gl-matrix/esm/vec2.js","../src/style/style_layer/circle_style_layer.js","../src/data/bucket/heatmap_bucket.js","../src/util/image.js","../src/style/style_layer/heatmap_style_layer_properties.js","../src/util/color_ramp.js","../src/style/style_layer/heatmap_style_layer.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","../src/style/parse_glyph_pbf.js","../node_modules/potpack/index.mjs","../src/render/image_atlas.js","../src/symbol/shaping.js","../src/symbol/symbol_size.js","../src/symbol/anchor.js","../src/symbol/symbol_layout.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/render/texture.js","../src/style/style_image.js","../src/render/image_manager.js","../node_modules/@mapbox/tiny-sdf/index.js","../src/render/glyph_manager.js","../src/style/load_glyph_range.js","../src/style/light.js","../src/render/line_atlas.js","../src/util/throttled_invoker.js","../src/util/actor.js","../src/util/dispatcher.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/source/load_tilejson.js","../src/source/tile_bounds.js","../src/source/vector_tile_source.js","../src/source/raster_tile_source.js","../src/data/dem_data.js","../src/source/raster_dem_tile_source.js","../src/source/geojson_source.js","../src/source/image_source.js","../src/source/video_source.js","../src/source/canvas_source.js","../src/source/source.js","../src/source/query_features.js","../src/util/dictionary_coder.js","../src/util/vectortile_to_geojson.js","../src/source/source_state.js","../src/data/feature_index.js","../src/source/tile.js","../src/data/bucket.js","../src/source/tile_cache.js","../src/gl/index_buffer.js","../src/gl/vertex_buffer.js","../src/gl/value.js","../src/gl/framebuffer.js","../src/gl/depth_mode.js","../src/gl/stencil_mode.js","../src/gl/color_mode.js","../src/gl/cull_face_mode.js","../src/gl/context.js","../src/source/source_cache.js","../src/util/browser/web_worker.js","../src/util/worker_pool.js","../src/util/global_worker_pool.js","../src/style-spec/util/ref_properties.js","../src/style-spec/deref.js","../src/style-spec/diff.js","../src/symbol/path_interpolator.js","../src/symbol/grid_index.js","../src/symbol/projection.js","../src/symbol/collision_index.js","../src/source/pixels_to_tile_units.js","../src/symbol/clip_line.js","../src/symbol/placement.js","../src/style/pauseable_placement.js","../src/symbol/cross_tile_symbol_index.js","../src/style/style.js","../src/style-spec/empty.js","../src/style/load_sprite.js","../src/data/pos_attributes.js","../src/shaders/shaders.js","../src/render/vertex_array_object.js","../src/render/program.js","../src/render/program/pattern.js","../src/render/program/fill_extrusion_program.js","../node_modules/gl-matrix/esm/mat3.js","../src/render/program/fill_program.js","../src/render/program/circle_program.js","../src/render/program/collision_program.js","../src/render/program/debug_program.js","../src/render/program/clipping_mask_program.js","../src/render/program/heatmap_program.js","../src/render/program/line_program.js","../src/render/program/raster_program.js","../src/render/program/symbol_program.js","../src/render/draw_collision_debug.js","../src/render/program/background_program.js","../src/render/program/program_uniforms.js","../src/render/program/hillshade_program.js","../src/render/draw_symbol.js","../src/render/draw_fill.js","../src/render/draw_fill_extrusion.js","../src/render/draw_hillshade.js","../src/render/draw_raster.js","../src/render/draw_debug.js","../src/render/painter.js","../src/render/draw_circle.js","../src/render/draw_heatmap.js","../src/render/draw_line.js","../src/render/draw_background.js","../src/render/draw_custom.js","../src/util/primitives.js","../src/geo/edge_insets.js","../src/geo/transform.js","../node_modules/gl-matrix/esm/mat2.js","../src/ui/hash.js","../src/util/throttle.js","../src/ui/handler_inertia.js","../src/ui/events.js","../src/ui/handler/map_event.js","../src/ui/handler/box_zoom.js","../src/ui/handler/handler_util.js","../src/ui/handler/tap_recognizer.js","../src/ui/handler/tap_zoom.js","../src/ui/handler/mouse.js","../src/ui/handler/touch_pan.js","../src/ui/handler/touch_zoom_rotate.js","../src/ui/handler/keyboard.js","../src/ui/handler/scroll_zoom.js","../src/ui/handler/shim/dblclick_zoom.js","../src/ui/handler/click_zoom.js","../src/ui/handler/tap_drag_zoom.js","../src/ui/handler/shim/drag_pan.js","../src/ui/handler/shim/drag_rotate.js","../src/ui/handler/shim/touch_zoom_rotate.js","../src/ui/handler_manager.js","../src/ui/camera.js","../src/ui/control/attribution_control.js","../src/ui/control/logo_control.js","../src/util/task_queue.js","../src/ui/default_locale.js","../src/ui/map.js","../src/ui/control/navigation_control.js","../src/util/smart_wrap.js","../src/ui/anchor.js","../src/ui/marker.js","../src/ui/control/geolocate_control.js","../src/ui/control/scale_control.js","../src/ui/control/fullscreen_control.js","../src/ui/popup.js","../src/index.js"],"sourcesContent":["'use strict';\n\nif (typeof module !== 'undefined' && module.exports) {\n module.exports = isSupported;\n} else if (window) {\n window.mapboxgl = window.mapboxgl || {};\n window.mapboxgl.supported = isSupported;\n window.mapboxgl.notSupportedReason = notSupportedReason;\n}\n\n/**\n * Test whether the current browser supports Mapbox GL JS\n * @param {Object} options\n * @param {boolean} [options.failIfMajorPerformanceCaveat=false] Return `false`\n * if the performance of Mapbox GL JS would be dramatically worse than\n * expected (i.e. a software renderer is would be used)\n * @return {boolean}\n */\nfunction isSupported(options) {\n return !notSupportedReason(options);\n}\n\nfunction notSupportedReason(options) {\n if (!isBrowser()) return 'not a browser';\n if (!isArraySupported()) return 'insufficent Array support';\n if (!isFunctionSupported()) return 'insufficient Function support';\n if (!isObjectSupported()) return 'insufficient Object support';\n if (!isJSONSupported()) return 'insufficient JSON support';\n if (!isWorkerSupported()) return 'insufficient worker support';\n if (!isUint8ClampedArraySupported()) return 'insufficient Uint8ClampedArray support';\n if (!isArrayBufferSupported()) return 'insufficient ArrayBuffer support';\n if (!isCanvasGetImageDataSupported()) return 'insufficient Canvas/getImageData support';\n if (!isWebGLSupportedCached(options && options.failIfMajorPerformanceCaveat)) return 'insufficient WebGL support';\n}\n\nfunction isBrowser() {\n return typeof window !== 'undefined' && typeof document !== 'undefined';\n}\n\nfunction isArraySupported() {\n return (\n Array.prototype &&\n Array.prototype.every &&\n Array.prototype.filter &&\n Array.prototype.forEach &&\n Array.prototype.indexOf &&\n Array.prototype.lastIndexOf &&\n Array.prototype.map &&\n Array.prototype.some &&\n Array.prototype.reduce &&\n Array.prototype.reduceRight &&\n Array.isArray\n );\n}\n\nfunction isFunctionSupported() {\n return Function.prototype && Function.prototype.bind;\n}\n\nfunction isObjectSupported() {\n return (\n Object.keys &&\n Object.create &&\n Object.getPrototypeOf &&\n Object.getOwnPropertyNames &&\n Object.isSealed &&\n Object.isFrozen &&\n Object.isExtensible &&\n Object.getOwnPropertyDescriptor &&\n Object.defineProperty &&\n Object.defineProperties &&\n Object.seal &&\n Object.freeze &&\n Object.preventExtensions\n );\n}\n\nfunction isJSONSupported() {\n return 'JSON' in window && 'parse' in JSON && 'stringify' in JSON;\n}\n\nfunction isWorkerSupported() {\n if (!('Worker' in window && 'Blob' in window && 'URL' in window)) {\n return false;\n }\n\n var blob = new Blob([''], { type: 'text/javascript' });\n var workerURL = URL.createObjectURL(blob);\n var supported;\n var worker;\n\n try {\n worker = new Worker(workerURL);\n supported = true;\n } catch (e) {\n supported = false;\n }\n\n if (worker) {\n worker.terminate();\n }\n URL.revokeObjectURL(workerURL);\n\n return supported;\n}\n\n// IE11 only supports `Uint8ClampedArray` as of version\n// [KB2929437](https://support.microsoft.com/en-us/kb/2929437)\nfunction isUint8ClampedArraySupported() {\n return 'Uint8ClampedArray' in window;\n}\n\n// https://github.com/mapbox/mapbox-gl-supported/issues/19\nfunction isArrayBufferSupported() {\n return ArrayBuffer.isView;\n}\n\n// Some browsers or browser extensions block access to canvas data to prevent fingerprinting.\n// Mapbox GL uses this API to load sprites and images in general.\nfunction isCanvasGetImageDataSupported() {\n const canvas = document.createElement('canvas');\n canvas.width = canvas.height = 1;\n const context = canvas.getContext('2d');\n if (!context) {\n return false;\n }\n const imageData = context.getImageData(0, 0, 1, 1);\n return imageData && imageData.width === canvas.width;\n}\n\nvar isWebGLSupportedCache = {};\nfunction isWebGLSupportedCached(failIfMajorPerformanceCaveat) {\n\n if (isWebGLSupportedCache[failIfMajorPerformanceCaveat] === undefined) {\n isWebGLSupportedCache[failIfMajorPerformanceCaveat] = isWebGLSupported(failIfMajorPerformanceCaveat);\n }\n\n return isWebGLSupportedCache[failIfMajorPerformanceCaveat];\n}\n\nisSupported.webGLContextAttributes = {\n antialias: false,\n alpha: true,\n stencil: true,\n depth: true\n};\n\nfunction getWebGLContext(failIfMajorPerformanceCaveat) {\n var canvas = document.createElement('canvas');\n\n var attributes = Object.create(isSupported.webGLContextAttributes);\n attributes.failIfMajorPerformanceCaveat = failIfMajorPerformanceCaveat;\n\n if (canvas.probablySupportsContext) {\n return (\n canvas.probablySupportsContext('webgl', attributes) ||\n canvas.probablySupportsContext('experimental-webgl', attributes)\n );\n\n } else if (canvas.supportsContext) {\n return (\n canvas.supportsContext('webgl', attributes) ||\n canvas.supportsContext('experimental-webgl', attributes)\n );\n\n } else {\n return (\n canvas.getContext('webgl', attributes) ||\n canvas.getContext('experimental-webgl', attributes)\n );\n }\n}\n\nfunction isWebGLSupported(failIfMajorPerformanceCaveat) {\n const gl = getWebGLContext(failIfMajorPerformanceCaveat);\n if (!gl) {\n return false;\n }\n\n // Try compiling a shader and get its compile status. Some browsers like Brave block this API\n // to prevent fingerprinting. Unfortunately, this also means that Mapbox GL won't work.\n const shader = gl.createShader(gl.VERTEX_SHADER);\n if (!shader || gl.isContextLost()) {\n return false;\n }\n gl.shaderSource(shader, 'void main() {}');\n gl.compileShader(shader);\n return gl.getShaderParameter(shader, gl.COMPILE_STATUS) === true;\n}\n","/*\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\n/**\n * Deeply compares two object literals.\n *\n * @private\n */\nfunction deepEqual(a: ?mixed, b: ?mixed): boolean {\n if (Array.isArray(a)) {\n if (!Array.isArray(b) || a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!deepEqual(a[i], b[i])) return false;\n }\n return true;\n }\n if (typeof a === 'object' && a !== null && b !== null) {\n if (!(typeof b === 'object')) return false;\n const keys = Object.keys(a);\n if (keys.length !== Object.keys(b).length) return false;\n for (const key in a) {\n if (!deepEqual(a[key], b[key])) return false;\n }\n return true;\n }\n return a === b;\n}\n\nexport default deepEqual;\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","// @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 strict\n\nimport Point from '@mapbox/point-geometry';\n\nimport window from './window';\nimport assert from 'assert';\n\nconst DOM = {};\nexport default DOM;\n\nDOM.create = function (tagName: string, className: ?string, container?: HTMLElement) {\n const el = window.document.createElement(tagName);\n if (className !== undefined) el.className = className;\n if (container) container.appendChild(el);\n return el;\n};\n\nDOM.createNS = function (namespaceURI: string, tagName: string) {\n const el = window.document.createElementNS(namespaceURI, tagName);\n return el;\n};\n\nconst docStyle = window.document && window.document.documentElement.style;\n\nfunction testProp(props) {\n if (!docStyle) return props[0];\n for (let i = 0; i < props.length; i++) {\n if (props[i] in docStyle) {\n return props[i];\n }\n }\n return props[0];\n}\n\nconst selectProp = testProp(['userSelect', 'MozUserSelect', 'WebkitUserSelect', 'msUserSelect']);\nlet userSelect;\n\nDOM.disableDrag = function () {\n if (docStyle && selectProp) {\n userSelect = docStyle[selectProp];\n docStyle[selectProp] = 'none';\n }\n};\n\nDOM.enableDrag = function () {\n if (docStyle && selectProp) {\n docStyle[selectProp] = userSelect;\n }\n};\n\nconst transformProp = testProp(['transform', 'WebkitTransform']);\n\nDOM.setTransform = function(el: HTMLElement, value: string) {\n // https://github.com/facebook/flow/issues/7754\n // $FlowFixMe\n el.style[transformProp] = value;\n};\n\n// Feature detection for {passive: false} support in add/removeEventListener.\nlet passiveSupported = false;\n\ntry {\n // https://github.com/facebook/flow/issues/285\n // $FlowFixMe\n const options = Object.defineProperty({}, \"passive\", {\n get() { // eslint-disable-line\n passiveSupported = true;\n }\n });\n window.addEventListener(\"test\", options, options);\n window.removeEventListener(\"test\", options, options);\n} catch (err) {\n passiveSupported = false;\n}\n\nDOM.addEventListener = function(target: *, type: *, callback: *, options: {passive?: boolean, capture?: boolean} = {}) {\n if ('passive' in options && passiveSupported) {\n target.addEventListener(type, callback, options);\n } else {\n target.addEventListener(type, callback, options.capture);\n }\n};\n\nDOM.removeEventListener = function(target: *, type: *, callback: *, options: {passive?: boolean, capture?: boolean} = {}) {\n if ('passive' in options && passiveSupported) {\n target.removeEventListener(type, callback, options);\n } else {\n target.removeEventListener(type, callback, options.capture);\n }\n};\n\n// Suppress the next click, but only if it's immediate.\nconst suppressClick: MouseEventListener = function (e) {\n e.preventDefault();\n e.stopPropagation();\n window.removeEventListener('click', suppressClick, true);\n};\n\nDOM.suppressClick = function() {\n window.addEventListener('click', suppressClick, true);\n window.setTimeout(() => {\n window.removeEventListener('click', suppressClick, true);\n }, 0);\n};\n\nDOM.mousePos = function (el: HTMLElement, e: MouseEvent | window.TouchEvent | Touch) {\n const rect = el.getBoundingClientRect();\n return new Point(\n e.clientX - rect.left - el.clientLeft,\n e.clientY - rect.top - el.clientTop\n );\n};\n\nDOM.touchPos = function (el: HTMLElement, touches: TouchList) {\n const rect = el.getBoundingClientRect(),\n points = [];\n for (let i = 0; i < touches.length; i++) {\n points.push(new Point(\n touches[i].clientX - rect.left - el.clientLeft,\n touches[i].clientY - rect.top - el.clientTop\n ));\n }\n return points;\n};\n\nDOM.mouseButton = function (e: MouseEvent) {\n assert(e.type === 'mousedown' || e.type === 'mouseup');\n if (typeof window.InstallTrigger !== 'undefined' && e.button === 2 && e.ctrlKey &&\n window.navigator.platform.toUpperCase().indexOf('MAC') >= 0) {\n // Fix for https://github.com/mapbox/mapbox-gl-js/issues/3131:\n // Firefox (detected by InstallTrigger) on Mac determines e.button = 2 when\n // using Control + left click\n return 0;\n }\n return e.button;\n};\n\nDOM.remove = function(node: HTMLElement) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\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\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\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\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\nimport window from './window';\n\nlet supportsOffscreenCanvas: ?boolean;\n\nexport default function offscreenCanvasSupported(): boolean {\n if (supportsOffscreenCanvas == null) {\n supportsOffscreenCanvas = window.OffscreenCanvas &&\n new window.OffscreenCanvas(1, 1).getContext('2d') &&\n typeof window.createImageBitmap === 'function';\n }\n\n return supportsOffscreenCanvas;\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 {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\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\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\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","// @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","// (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\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","\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\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","'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","// @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\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\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 * 3 Dimensional Vector\r\n * @module vec3\r\n */\n\n/**\r\n * Creates a new, empty vec3\r\n *\r\n * @returns {vec3} a new 3D vector\r\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(3);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n }\n\n return out;\n}\n/**\r\n * Creates a new vec3 initialized with values from an existing vector\r\n *\r\n * @param {vec3} a vector to clone\r\n * @returns {vec3} a new 3D vector\r\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n return out;\n}\n/**\r\n * Calculates the length of a vec3\r\n *\r\n * @param {vec3} 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 return Math.hypot(x, y, z);\n}\n/**\r\n * Creates a new vec3 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 * @returns {vec3} a new 3D vector\r\n */\n\nexport function fromValues(x, y, z) {\n var out = new glMatrix.ARRAY_TYPE(3);\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n/**\r\n * Copy the values from one vec3 to another\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the source vector\r\n * @returns {vec3} 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 return out;\n}\n/**\r\n * Set the components of a vec3 to the given values\r\n *\r\n * @param {vec3} 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 * @returns {vec3} out\r\n */\n\nexport function set(out, x, y, z) {\n out[0] = x;\n out[1] = y;\n out[2] = z;\n return out;\n}\n/**\r\n * Adds two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {vec3} 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 return out;\n}\n/**\r\n * Subtracts vector b from vector a\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {vec3} 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 return out;\n}\n/**\r\n * Multiplies two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {vec3} 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 return out;\n}\n/**\r\n * Divides two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {vec3} 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 return out;\n}\n/**\r\n * Math.ceil the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a vector to ceil\r\n * @returns {vec3} 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 return out;\n}\n/**\r\n * Math.floor the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a vector to floor\r\n * @returns {vec3} 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 return out;\n}\n/**\r\n * Returns the minimum of two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {vec3} 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 return out;\n}\n/**\r\n * Returns the maximum of two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {vec3} 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 return out;\n}\n/**\r\n * Math.round the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a vector to round\r\n * @returns {vec3} 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 return out;\n}\n/**\r\n * Scales a vec3 by a scalar number\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the vector to scale\r\n * @param {Number} b amount to scale the vector by\r\n * @returns {vec3} 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 return out;\n}\n/**\r\n * Adds two vec3's after scaling the second operand by a scalar value\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @param {Number} scale the amount to scale b by before adding\r\n * @returns {vec3} 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 return out;\n}\n/**\r\n * Calculates the euclidian distance between two vec3's\r\n *\r\n * @param {vec3} a the first operand\r\n * @param {vec3} 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 return Math.hypot(x, y, z);\n}\n/**\r\n * Calculates the squared euclidian distance between two vec3's\r\n *\r\n * @param {vec3} a the first operand\r\n * @param {vec3} 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 return x * x + y * y + z * z;\n}\n/**\r\n * Calculates the squared length of a vec3\r\n *\r\n * @param {vec3} 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 return x * x + y * y + z * z;\n}\n/**\r\n * Negates the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a vector to negate\r\n * @returns {vec3} 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 return out;\n}\n/**\r\n * Returns the inverse of the components of a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a vector to invert\r\n * @returns {vec3} 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 return out;\n}\n/**\r\n * Normalize a vec3\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a vector to normalize\r\n * @returns {vec3} 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 len = x * x + y * y + z * z;\n\n if (len > 0) {\n //TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n out[2] = a[2] * len;\n return out;\n}\n/**\r\n * Calculates the dot product of two vec3's\r\n *\r\n * @param {vec3} a the first operand\r\n * @param {vec3} 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];\n}\n/**\r\n * Computes the cross product of two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @returns {vec3} out\r\n */\n\nexport function cross(out, a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2];\n var bx = b[0],\n by = b[1],\n bz = b[2];\n out[0] = ay * bz - az * by;\n out[1] = az * bx - ax * bz;\n out[2] = ax * by - ay * bx;\n return out;\n}\n/**\r\n * Performs a linear interpolation between two vec3's\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec3} 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 out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n out[2] = az + t * (b[2] - az);\n return out;\n}\n/**\r\n * Performs a hermite interpolation with two control points\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @param {vec3} c the third operand\r\n * @param {vec3} d the fourth operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec3} out\r\n */\n\nexport function hermite(out, a, b, c, d, t) {\n var factorTimes2 = t * t;\n var factor1 = factorTimes2 * (2 * t - 3) + 1;\n var factor2 = factorTimes2 * (t - 2) + t;\n var factor3 = factorTimes2 * (t - 1);\n var factor4 = factorTimes2 * (3 - 2 * t);\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n/**\r\n * Performs a bezier interpolation with two control points\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the first operand\r\n * @param {vec3} b the second operand\r\n * @param {vec3} c the third operand\r\n * @param {vec3} d the fourth operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec3} out\r\n */\n\nexport function bezier(out, a, b, c, d, t) {\n var inverseFactor = 1 - t;\n var inverseFactorTimesTwo = inverseFactor * inverseFactor;\n var factorTimes2 = t * t;\n var factor1 = inverseFactorTimesTwo * inverseFactor;\n var factor2 = 3 * t * inverseFactorTimesTwo;\n var factor3 = 3 * factorTimes2 * inverseFactor;\n var factor4 = factorTimes2 * t;\n out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4;\n out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4;\n out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4;\n return out;\n}\n/**\r\n * Generates a random vector with the given scale\r\n *\r\n * @param {vec3} 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 {vec3} out\r\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0;\n var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n var z = glMatrix.RANDOM() * 2.0 - 1.0;\n var zScale = Math.sqrt(1.0 - z * z) * scale;\n out[0] = Math.cos(r) * zScale;\n out[1] = Math.sin(r) * zScale;\n out[2] = z * scale;\n return out;\n}\n/**\r\n * Transforms the vec3 with a mat4.\r\n * 4th vector component is implicitly '1'\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the vector to transform\r\n * @param {mat4} m matrix to transform with\r\n * @returns {vec3} out\r\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n var w = m[3] * x + m[7] * y + m[11] * z + m[15];\n w = w || 1.0;\n out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w;\n out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w;\n out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w;\n return out;\n}\n/**\r\n * Transforms the vec3 with a mat3.\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the vector to transform\r\n * @param {mat3} m the 3x3 matrix to transform with\r\n * @returns {vec3} out\r\n */\n\nexport function transformMat3(out, a, m) {\n var x = a[0],\n y = a[1],\n z = a[2];\n out[0] = x * m[0] + y * m[3] + z * m[6];\n out[1] = x * m[1] + y * m[4] + z * m[7];\n out[2] = x * m[2] + y * m[5] + z * m[8];\n return out;\n}\n/**\r\n * Transforms the vec3 with a quat\r\n * Can also be used for dual quaternions. (Multiply it with the real part)\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec3} a the vector to transform\r\n * @param {quat} q quaternion to transform with\r\n * @returns {vec3} out\r\n */\n\nexport function transformQuat(out, a, q) {\n // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed\n var qx = q[0],\n qy = q[1],\n qz = q[2],\n qw = q[3];\n var x = a[0],\n y = a[1],\n z = a[2]; // var qvec = [qx, qy, qz];\n // var uv = vec3.cross([], qvec, a);\n\n var uvx = qy * z - qz * y,\n uvy = qz * x - qx * z,\n uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv);\n\n var uuvx = qy * uvz - qz * uvy,\n uuvy = qz * uvx - qx * uvz,\n uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w);\n\n var w2 = qw * 2;\n uvx *= w2;\n uvy *= w2;\n uvz *= w2; // vec3.scale(uuv, uuv, 2);\n\n uuvx *= 2;\n uuvy *= 2;\n uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv));\n\n out[0] = x + uvx + uuvx;\n out[1] = y + uvy + uuvy;\n out[2] = z + uvz + uuvz;\n return out;\n}\n/**\r\n * Rotate a 3D vector around the x-axis\r\n * @param {vec3} out The receiving vec3\r\n * @param {vec3} a The vec3 point to rotate\r\n * @param {vec3} b The origin of the rotation\r\n * @param {Number} rad The angle of rotation in radians\r\n * @returns {vec3} out\r\n */\n\nexport function rotateX(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[0];\n r[1] = p[1] * Math.cos(rad) - p[2] * Math.sin(rad);\n r[2] = p[1] * Math.sin(rad) + p[2] * Math.cos(rad); //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\r\n * Rotate a 3D vector around the y-axis\r\n * @param {vec3} out The receiving vec3\r\n * @param {vec3} a The vec3 point to rotate\r\n * @param {vec3} b The origin of the rotation\r\n * @param {Number} rad The angle of rotation in radians\r\n * @returns {vec3} out\r\n */\n\nexport function rotateY(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[2] * Math.sin(rad) + p[0] * Math.cos(rad);\n r[1] = p[1];\n r[2] = p[2] * Math.cos(rad) - p[0] * Math.sin(rad); //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\r\n * Rotate a 3D vector around the z-axis\r\n * @param {vec3} out The receiving vec3\r\n * @param {vec3} a The vec3 point to rotate\r\n * @param {vec3} b The origin of the rotation\r\n * @param {Number} rad The angle of rotation in radians\r\n * @returns {vec3} out\r\n */\n\nexport function rotateZ(out, a, b, rad) {\n var p = [],\n r = []; //Translate point to the origin\n\n p[0] = a[0] - b[0];\n p[1] = a[1] - b[1];\n p[2] = a[2] - b[2]; //perform rotation\n\n r[0] = p[0] * Math.cos(rad) - p[1] * Math.sin(rad);\n r[1] = p[0] * Math.sin(rad) + p[1] * Math.cos(rad);\n r[2] = p[2]; //translate to correct position\n\n out[0] = r[0] + b[0];\n out[1] = r[1] + b[1];\n out[2] = r[2] + b[2];\n return out;\n}\n/**\r\n * Get the angle between two 3D vectors\r\n * @param {vec3} a The first operand\r\n * @param {vec3} b The second operand\r\n * @returns {Number} The angle in radians\r\n */\n\nexport function angle(a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2],\n bx = b[0],\n by = b[1],\n bz = b[2],\n mag1 = Math.sqrt(ax * ax + ay * ay + az * az),\n mag2 = Math.sqrt(bx * bx + by * by + bz * bz),\n mag = mag1 * mag2,\n cosine = mag && dot(a, b) / mag;\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n/**\r\n * Set the components of a vec3 to zero\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @returns {vec3} out\r\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n out[2] = 0.0;\n return out;\n}\n/**\r\n * Returns a string representation of a vector\r\n *\r\n * @param {vec3} 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 \"vec3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \")\";\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 {vec3} a The first vector.\r\n * @param {vec3} 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];\n}\n/**\r\n * Returns whether or not the vectors have approximately the same elements in the same position.\r\n *\r\n * @param {vec3} a The first vector.\r\n * @param {vec3} 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 var b0 = b[0],\n b1 = b[1],\n b2 = b[2];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2));\n}\n/**\r\n * Alias for {@link vec3.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;\n/**\r\n * Alias for {@link vec3.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link vec3.divide}\r\n * @function\r\n */\n\nexport var div = divide;\n/**\r\n * Alias for {@link vec3.distance}\r\n * @function\r\n */\n\nexport var dist = distance;\n/**\r\n * Alias for {@link vec3.squaredDistance}\r\n * @function\r\n */\n\nexport var sqrDist = squaredDistance;\n/**\r\n * Alias for {@link vec3.length}\r\n * @function\r\n */\n\nexport var len = length;\n/**\r\n * Alias for {@link vec3.squaredLength}\r\n * @function\r\n */\n\nexport var sqrLen = squaredLength;\n/**\r\n * Perform some operation over an array of vec3s.\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 vec3. 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 vec3s 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 = 3;\n }\n\n if (!offset) {\n offset = 0;\n }\n\n if (count) {\n l = Math.min(count * stride + offset, a.length);\n } else {\n l = a.length;\n }\n\n for (i = offset; i < l; i += stride) {\n vec[0] = a[i];\n vec[1] = a[i + 1];\n vec[2] = a[i + 2];\n fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\n a[i + 2] = vec[2];\n }\n\n return a;\n };\n}();","import * as glMatrix from \"./common.js\";\n/**\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}();","import * as glMatrix from \"./common.js\";\n/**\r\n * 2 Dimensional Vector\r\n * @module vec2\r\n */\n\n/**\r\n * Creates a new, empty vec2\r\n *\r\n * @returns {vec2} a new 2D vector\r\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(2);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[0] = 0;\n out[1] = 0;\n }\n\n return out;\n}\n/**\r\n * Creates a new vec2 initialized with values from an existing vector\r\n *\r\n * @param {vec2} a vector to clone\r\n * @returns {vec2} a new 2D vector\r\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(2);\n out[0] = a[0];\n out[1] = a[1];\n return out;\n}\n/**\r\n * Creates a new vec2 initialized with the given values\r\n *\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @returns {vec2} a new 2D vector\r\n */\n\nexport function fromValues(x, y) {\n var out = new glMatrix.ARRAY_TYPE(2);\n out[0] = x;\n out[1] = y;\n return out;\n}\n/**\r\n * Copy the values from one vec2 to another\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the source vector\r\n * @returns {vec2} out\r\n */\n\nexport function copy(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n return out;\n}\n/**\r\n * Set the components of a vec2 to the given values\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {Number} x X component\r\n * @param {Number} y Y component\r\n * @returns {vec2} out\r\n */\n\nexport function set(out, x, y) {\n out[0] = x;\n out[1] = y;\n return out;\n}\n/**\r\n * Adds two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {vec2} 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 return out;\n}\n/**\r\n * Subtracts vector b from vector a\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {vec2} 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 return out;\n}\n/**\r\n * Multiplies two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {vec2} 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 return out;\n}\n/**\r\n * Divides two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {vec2} 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 return out;\n}\n/**\r\n * Math.ceil the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a vector to ceil\r\n * @returns {vec2} out\r\n */\n\nexport function ceil(out, a) {\n out[0] = Math.ceil(a[0]);\n out[1] = Math.ceil(a[1]);\n return out;\n}\n/**\r\n * Math.floor the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a vector to floor\r\n * @returns {vec2} out\r\n */\n\nexport function floor(out, a) {\n out[0] = Math.floor(a[0]);\n out[1] = Math.floor(a[1]);\n return out;\n}\n/**\r\n * Returns the minimum of two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {vec2} 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 return out;\n}\n/**\r\n * Returns the maximum of two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {vec2} 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 return out;\n}\n/**\r\n * Math.round the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a vector to round\r\n * @returns {vec2} out\r\n */\n\nexport function round(out, a) {\n out[0] = Math.round(a[0]);\n out[1] = Math.round(a[1]);\n return out;\n}\n/**\r\n * Scales a vec2 by a scalar number\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the vector to scale\r\n * @param {Number} b amount to scale the vector by\r\n * @returns {vec2} out\r\n */\n\nexport function scale(out, a, b) {\n out[0] = a[0] * b;\n out[1] = a[1] * b;\n return out;\n}\n/**\r\n * Adds two vec2's after scaling the second operand by a scalar value\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @param {Number} scale the amount to scale b by before adding\r\n * @returns {vec2} 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 return out;\n}\n/**\r\n * Calculates the euclidian distance between two vec2's\r\n *\r\n * @param {vec2} a the first operand\r\n * @param {vec2} 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 y = b[1] - a[1];\n return Math.hypot(x, y);\n}\n/**\r\n * Calculates the squared euclidian distance between two vec2's\r\n *\r\n * @param {vec2} a the first operand\r\n * @param {vec2} 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 y = b[1] - a[1];\n return x * x + y * y;\n}\n/**\r\n * Calculates the length of a vec2\r\n *\r\n * @param {vec2} 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 y = a[1];\n return Math.hypot(x, y);\n}\n/**\r\n * Calculates the squared length of a vec2\r\n *\r\n * @param {vec2} 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 y = a[1];\n return x * x + y * y;\n}\n/**\r\n * Negates the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a vector to negate\r\n * @returns {vec2} out\r\n */\n\nexport function negate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n return out;\n}\n/**\r\n * Returns the inverse of the components of a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a vector to invert\r\n * @returns {vec2} out\r\n */\n\nexport function inverse(out, a) {\n out[0] = 1.0 / a[0];\n out[1] = 1.0 / a[1];\n return out;\n}\n/**\r\n * Normalize a vec2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a vector to normalize\r\n * @returns {vec2} out\r\n */\n\nexport function normalize(out, a) {\n var x = a[0],\n y = a[1];\n var len = x * x + y * y;\n\n if (len > 0) {\n //TODO: evaluate use of glm_invsqrt here?\n len = 1 / Math.sqrt(len);\n }\n\n out[0] = a[0] * len;\n out[1] = a[1] * len;\n return out;\n}\n/**\r\n * Calculates the dot product of two vec2's\r\n *\r\n * @param {vec2} a the first operand\r\n * @param {vec2} 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];\n}\n/**\r\n * Computes the cross product of two vec2's\r\n * Note that the cross product must by definition produce a 3D vector\r\n *\r\n * @param {vec3} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @returns {vec3} out\r\n */\n\nexport function cross(out, a, b) {\n var z = a[0] * b[1] - a[1] * b[0];\n out[0] = out[1] = 0;\n out[2] = z;\n return out;\n}\n/**\r\n * Performs a linear interpolation between two vec2's\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the first operand\r\n * @param {vec2} b the second operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {vec2} out\r\n */\n\nexport function lerp(out, a, b, t) {\n var ax = a[0],\n ay = a[1];\n out[0] = ax + t * (b[0] - ax);\n out[1] = ay + t * (b[1] - ay);\n return out;\n}\n/**\r\n * Generates a random vector with the given scale\r\n *\r\n * @param {vec2} 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 {vec2} out\r\n */\n\nexport function random(out, scale) {\n scale = scale || 1.0;\n var r = glMatrix.RANDOM() * 2.0 * Math.PI;\n out[0] = Math.cos(r) * scale;\n out[1] = Math.sin(r) * scale;\n return out;\n}\n/**\r\n * Transforms the vec2 with a mat2\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the vector to transform\r\n * @param {mat2} m matrix to transform with\r\n * @returns {vec2} out\r\n */\n\nexport function transformMat2(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[2] * y;\n out[1] = m[1] * x + m[3] * y;\n return out;\n}\n/**\r\n * Transforms the vec2 with a mat2d\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the vector to transform\r\n * @param {mat2d} m matrix to transform with\r\n * @returns {vec2} out\r\n */\n\nexport function transformMat2d(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[2] * y + m[4];\n out[1] = m[1] * x + m[3] * y + m[5];\n return out;\n}\n/**\r\n * Transforms the vec2 with a mat3\r\n * 3rd vector component is implicitly '1'\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the vector to transform\r\n * @param {mat3} m matrix to transform with\r\n * @returns {vec2} out\r\n */\n\nexport function transformMat3(out, a, m) {\n var x = a[0],\n y = a[1];\n out[0] = m[0] * x + m[3] * y + m[6];\n out[1] = m[1] * x + m[4] * y + m[7];\n return out;\n}\n/**\r\n * Transforms the vec2 with a mat4\r\n * 3rd vector component is implicitly '0'\r\n * 4th vector component is implicitly '1'\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @param {vec2} a the vector to transform\r\n * @param {mat4} m matrix to transform with\r\n * @returns {vec2} out\r\n */\n\nexport function transformMat4(out, a, m) {\n var x = a[0];\n var y = a[1];\n out[0] = m[0] * x + m[4] * y + m[12];\n out[1] = m[1] * x + m[5] * y + m[13];\n return out;\n}\n/**\r\n * Rotate a 2D vector\r\n * @param {vec2} out The receiving vec2\r\n * @param {vec2} a The vec2 point to rotate\r\n * @param {vec2} b The origin of the rotation\r\n * @param {Number} rad The angle of rotation in radians\r\n * @returns {vec2} out\r\n */\n\nexport function rotate(out, a, b, rad) {\n //Translate point to the origin\n var p0 = a[0] - b[0],\n p1 = a[1] - b[1],\n sinC = Math.sin(rad),\n cosC = Math.cos(rad); //perform rotation and translate to correct position\n\n out[0] = p0 * cosC - p1 * sinC + b[0];\n out[1] = p0 * sinC + p1 * cosC + b[1];\n return out;\n}\n/**\r\n * Get the angle between two 2D vectors\r\n * @param {vec2} a The first operand\r\n * @param {vec2} b The second operand\r\n * @returns {Number} The angle in radians\r\n */\n\nexport function angle(a, b) {\n var x1 = a[0],\n y1 = a[1],\n x2 = b[0],\n y2 = b[1],\n // mag is the product of the magnitudes of a and b\n mag = Math.sqrt(x1 * x1 + y1 * y1) * Math.sqrt(x2 * x2 + y2 * y2),\n // mag &&.. short circuits if mag == 0\n cosine = mag && (x1 * x2 + y1 * y2) / mag; // Math.min(Math.max(cosine, -1), 1) clamps the cosine between -1 and 1\n\n return Math.acos(Math.min(Math.max(cosine, -1), 1));\n}\n/**\r\n * Set the components of a vec2 to zero\r\n *\r\n * @param {vec2} out the receiving vector\r\n * @returns {vec2} out\r\n */\n\nexport function zero(out) {\n out[0] = 0.0;\n out[1] = 0.0;\n return out;\n}\n/**\r\n * Returns a string representation of a vector\r\n *\r\n * @param {vec2} 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 \"vec2(\" + a[0] + \", \" + a[1] + \")\";\n}\n/**\r\n * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===)\r\n *\r\n * @param {vec2} a The first vector.\r\n * @param {vec2} 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];\n}\n/**\r\n * Returns whether or not the vectors have approximately the same elements in the same position.\r\n *\r\n * @param {vec2} a The first vector.\r\n * @param {vec2} 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 var b0 = b[0],\n b1 = b[1];\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));\n}\n/**\r\n * Alias for {@link vec2.length}\r\n * @function\r\n */\n\nexport var len = length;\n/**\r\n * Alias for {@link vec2.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;\n/**\r\n * Alias for {@link vec2.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link vec2.divide}\r\n * @function\r\n */\n\nexport var div = divide;\n/**\r\n * Alias for {@link vec2.distance}\r\n * @function\r\n */\n\nexport var dist = distance;\n/**\r\n * Alias for {@link vec2.squaredDistance}\r\n * @function\r\n */\n\nexport var sqrDist = squaredDistance;\n/**\r\n * Alias for {@link vec2.squaredLength}\r\n * @function\r\n */\n\nexport var sqrLen = squaredLength;\n/**\r\n * Perform some operation over an array of vec2s.\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 vec2. 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 vec2s 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 = 2;\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 fn(vec, vec, arg);\n a[i] = vec[0];\n a[i + 1] = vec[1];\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 {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","// @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","// 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","// @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","\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 {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\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 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 {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","// @flow\n\nimport window from '../util/window';\nconst {HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData, ImageBitmap} = window;\n\nimport type Context from '../gl/context';\nimport type {RGBAImage, AlphaImage} from '../util/image';\n\nexport type TextureFormat =\n | $PropertyType\n | $PropertyType;\nexport type TextureFilter =\n | $PropertyType\n | $PropertyType\n | $PropertyType;\nexport type TextureWrap =\n | $PropertyType\n | $PropertyType\n | $PropertyType;\n\ntype EmptyImage = {\n width: number,\n height: number,\n data: null\n}\n\nexport type TextureImage =\n | RGBAImage\n | AlphaImage\n | HTMLImageElement\n | HTMLCanvasElement\n | HTMLVideoElement\n | ImageData\n | EmptyImage\n | ImageBitmap;\n\nclass Texture {\n context: Context;\n size: [number, number];\n texture: WebGLTexture;\n format: TextureFormat;\n filter: ?TextureFilter;\n wrap: ?TextureWrap;\n useMipmap: boolean;\n\n constructor(context: Context, image: TextureImage, format: TextureFormat, options: ?{ premultiply?: boolean, useMipmap?: boolean }) {\n this.context = context;\n this.format = format;\n this.texture = context.gl.createTexture();\n this.update(image, options);\n }\n\n update(image: TextureImage, options: ?{premultiply?: boolean, useMipmap?: boolean}, position?: { x: number, y: number }) {\n const {width, height} = image;\n const resize = (!this.size || this.size[0] !== width || this.size[1] !== height) && !position;\n const {context} = this;\n const {gl} = context;\n\n this.useMipmap = Boolean(options && options.useMipmap);\n gl.bindTexture(gl.TEXTURE_2D, this.texture);\n\n context.pixelStoreUnpackFlipY.set(false);\n context.pixelStoreUnpack.set(1);\n context.pixelStoreUnpackPremultiplyAlpha.set(this.format === gl.RGBA && (!options || options.premultiply !== false));\n\n if (resize) {\n this.size = [width, height];\n\n if (image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || (ImageBitmap && image instanceof ImageBitmap)) {\n gl.texImage2D(gl.TEXTURE_2D, 0, this.format, this.format, gl.UNSIGNED_BYTE, image);\n } else {\n gl.texImage2D(gl.TEXTURE_2D, 0, this.format, width, height, 0, this.format, gl.UNSIGNED_BYTE, image.data);\n }\n\n } else {\n const {x, y} = position || {x: 0, y: 0};\n if (image instanceof HTMLImageElement || image instanceof HTMLCanvasElement || image instanceof HTMLVideoElement || image instanceof ImageData || (ImageBitmap && image instanceof ImageBitmap)) {\n gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, gl.RGBA, gl.UNSIGNED_BYTE, image);\n } else {\n gl.texSubImage2D(gl.TEXTURE_2D, 0, x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, image.data);\n }\n }\n\n if (this.useMipmap && this.isSizePowerOfTwo()) {\n gl.generateMipmap(gl.TEXTURE_2D);\n }\n }\n\n bind(filter: TextureFilter, wrap: TextureWrap, minFilter: ?TextureFilter) {\n const {context} = this;\n const {gl} = context;\n gl.bindTexture(gl.TEXTURE_2D, this.texture);\n\n if (minFilter === gl.LINEAR_MIPMAP_NEAREST && !this.isSizePowerOfTwo()) {\n minFilter = gl.LINEAR;\n }\n\n if (filter !== this.filter) {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter || filter);\n this.filter = filter;\n }\n\n if (wrap !== this.wrap) {\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);\n this.wrap = wrap;\n }\n }\n\n isSizePowerOfTwo() {\n return this.size[0] === this.size[1] && (Math.log(this.size[0]) / Math.LN2) % 1 === 0;\n }\n\n destroy() {\n const {gl} = this.context;\n gl.deleteTexture(this.texture);\n this.texture = (null: any);\n }\n}\n\nexport default Texture;\n","// @flow\n\nimport {RGBAImage} from '../util/image';\n\nimport type Map from '../ui/map';\n\nexport type StyleImageData = {\n data: RGBAImage,\n version: number,\n hasRenderCallback?: boolean,\n userImage?: StyleImageInterface\n};\n\nexport type StyleImageMetadata = {\n pixelRatio: number,\n sdf: boolean,\n stretchX?: Array<[number, number]>,\n stretchY?: Array<[number, number]>,\n content?: [number, number, number, number]\n};\n\nexport type StyleImage = StyleImageData & StyleImageMetadata;\n\nexport type StyleImageInterface = {\n width: number,\n height: number,\n data: Uint8Array | Uint8ClampedArray,\n render?: () => boolean,\n onAdd?: (map: Map, id: string) => void,\n onRemove?: () => void\n};\n\nexport function renderStyleImage(image: StyleImage) {\n const {userImage} = image;\n if (userImage && userImage.render) {\n const updated = userImage.render();\n if (updated) {\n image.data.replace(new Uint8Array(userImage.data.buffer));\n return true;\n }\n }\n return false;\n}\n\n/**\n * Interface for dynamically generated style images. This is a specification for\n * implementers to model: it is not an exported method or class.\n *\n * Images implementing this interface can be redrawn for every frame. They can be used to animate\n * icons and patterns or make them respond to user input. Style images can implement a\n * {@link StyleImageInterface#render} method. The method is called every frame and\n * can be used to update the image.\n *\n * @interface StyleImageInterface\n * @property {number} width\n * @property {number} height\n * @property {Uint8Array | Uint8ClampedArray} data\n *\n * @see [Add an animated icon to the map.](https://docs.mapbox.com/mapbox-gl-js/example/add-image-animated/)\n *\n * @example\n * var flashingSquare = {\n * width: 64,\n * height: 64,\n * data: new Uint8Array(64 * 64 * 4),\n *\n * onAdd: function(map) {\n * this.map = map;\n * },\n *\n * render: function() {\n * // keep repainting while the icon is on the map\n * this.map.triggerRepaint();\n *\n * // alternate between black and white based on the time\n * var value = Math.round(Date.now() / 1000) % 2 === 0 ? 255 : 0;\n *\n * // check if image needs to be changed\n * if (value !== this.previousValue) {\n * this.previousValue = value;\n *\n * var bytesPerPixel = 4;\n * for (var x = 0; x < this.width; x++) {\n * for (var y = 0; y < this.height; y++) {\n * var offset = (y * this.width + x) * bytesPerPixel;\n * this.data[offset + 0] = value;\n * this.data[offset + 1] = value;\n * this.data[offset + 2] = value;\n * this.data[offset + 3] = 255;\n * }\n * }\n *\n * // return true to indicate that the image changed\n * return true;\n * }\n * }\n * }\n *\n * map.addImage('flashing_square', flashingSquare);\n */\n\n/**\n * This method is called once before every frame where the icon will be used.\n * The method can optionally update the image's `data` member with a new image.\n *\n * If the method updates the image it must return `true` to commit the change.\n * If the method returns `false` or nothing the image is assumed to not have changed.\n *\n * If updates are infrequent it maybe easier to use {@link Map#updateImage} to update\n * the image instead of implementing this method.\n *\n * @function\n * @memberof StyleImageInterface\n * @instance\n * @name render\n * @return {boolean} `true` if this method updated the image. `false` if the image was not changed.\n */\n\n/**\n * Optional method called when the layer has been added to the Map with {@link Map#addImage}.\n *\n * @function\n * @memberof StyleImageInterface\n * @instance\n * @name onAdd\n * @param {Map} map The Map this custom layer was just added to.\n */\n\n/**\n * Optional method called when the icon is removed from the map with {@link Map#removeImage}.\n * This gives the image a chance to clean up resources and event listeners.\n *\n * @function\n * @memberof StyleImageInterface\n * @instance\n * @name onRemove\n */\n","// @flow\n\nimport potpack from 'potpack';\n\nimport {Event, ErrorEvent, Evented} from '../util/evented';\nimport {RGBAImage} from '../util/image';\nimport {ImagePosition} from './image_atlas';\nimport Texture from './texture';\nimport assert from 'assert';\nimport {renderStyleImage} from '../style/style_image';\nimport {warnOnce} from '../util/util';\n\nimport type {StyleImage} from '../style/style_image';\nimport type Context from '../gl/context';\nimport type {Bin} from 'potpack';\nimport type {Callback} from '../types/callback';\n\ntype Pattern = {\n bin: Bin,\n position: ImagePosition\n};\n\n// When copied into the atlas texture, image data is padded by one pixel on each side. Icon\n// images are padded with fully transparent pixels, while pattern images are padded with a\n// copy of the image data wrapped from the opposite side. In both cases, this ensures the\n// correct behavior of GL_LINEAR texture sampling mode.\nconst padding = 1;\n\n/*\n ImageManager does three things:\n\n 1. Tracks requests for icon images from tile workers and sends responses when the requests are fulfilled.\n 2. Builds a texture atlas for pattern images.\n 3. Rerenders renderable images once per frame\n\n These are disparate responsibilities and should eventually be handled by different classes. When we implement\n data-driven support for `*-pattern`, we'll likely use per-bucket pattern atlases, and that would be a good time\n to refactor this.\n*/\nclass ImageManager extends Evented {\n images: {[_: string]: StyleImage};\n updatedImages: {[_: string]: boolean};\n callbackDispatchedThisFrame: {[_: string]: boolean};\n loaded: boolean;\n requestors: Array<{ids: Array, callback: Callback<{[_: string]: StyleImage}>}>;\n\n patterns: {[_: string]: Pattern};\n atlasImage: RGBAImage;\n atlasTexture: ?Texture;\n dirty: boolean;\n\n constructor() {\n super();\n this.images = {};\n this.updatedImages = {};\n this.callbackDispatchedThisFrame = {};\n this.loaded = false;\n this.requestors = [];\n\n this.patterns = {};\n this.atlasImage = new RGBAImage({width: 1, height: 1});\n this.dirty = true;\n }\n\n isLoaded() {\n return this.loaded;\n }\n\n setLoaded(loaded: boolean) {\n if (this.loaded === loaded) {\n return;\n }\n\n this.loaded = loaded;\n\n if (loaded) {\n for (const {ids, callback} of this.requestors) {\n this._notify(ids, callback);\n }\n this.requestors = [];\n }\n }\n\n getImage(id: string): ?StyleImage {\n return this.images[id];\n }\n\n addImage(id: string, image: StyleImage) {\n assert(!this.images[id]);\n if (this._validate(id, image)) {\n this.images[id] = image;\n }\n }\n\n _validate(id: string, image: StyleImage) {\n let valid = true;\n if (!this._validateStretch(image.stretchX, image.data && image.data.width)) {\n this.fire(new ErrorEvent(new Error(`Image \"${id}\" has invalid \"stretchX\" value`)));\n valid = false;\n }\n if (!this._validateStretch(image.stretchY, image.data && image.data.height)) {\n this.fire(new ErrorEvent(new Error(`Image \"${id}\" has invalid \"stretchY\" value`)));\n valid = false;\n }\n if (!this._validateContent(image.content, image)) {\n this.fire(new ErrorEvent(new Error(`Image \"${id}\" has invalid \"content\" value`)));\n valid = false;\n }\n return valid;\n }\n\n _validateStretch(stretch: ?Array<[number, number]> | void, size: number) {\n if (!stretch) return true;\n let last = 0;\n for (const part of stretch) {\n if (part[0] < last || part[1] < part[0] || size < part[1]) return false;\n last = part[1];\n }\n return true;\n }\n\n _validateContent(content: ?[number, number, number, number] | void, image: StyleImage) {\n if (!content) return true;\n if (content.length !== 4) return false;\n if (content[0] < 0 || image.data.width < content[0]) return false;\n if (content[1] < 0 || image.data.height < content[1]) return false;\n if (content[2] < 0 || image.data.width < content[2]) return false;\n if (content[3] < 0 || image.data.height < content[3]) return false;\n if (content[2] < content[0]) return false;\n if (content[3] < content[1]) return false;\n return true;\n }\n\n updateImage(id: string, image: StyleImage) {\n const oldImage = this.images[id];\n assert(oldImage);\n assert(oldImage.data.width === image.data.width);\n assert(oldImage.data.height === image.data.height);\n image.version = oldImage.version + 1;\n this.images[id] = image;\n this.updatedImages[id] = true;\n }\n\n removeImage(id: string) {\n assert(this.images[id]);\n const image = this.images[id];\n delete this.images[id];\n delete this.patterns[id];\n\n if (image.userImage && image.userImage.onRemove) {\n image.userImage.onRemove();\n }\n }\n\n listImages(): Array {\n return Object.keys(this.images);\n }\n\n getImages(ids: Array, callback: Callback<{[_: string]: StyleImage}>) {\n // If the sprite has been loaded, or if all the icon dependencies are already present\n // (i.e. if they've been added via runtime styling), then notify the requestor immediately.\n // Otherwise, delay notification until the sprite is loaded. At that point, if any of the\n // dependencies are still unavailable, we'll just assume they are permanently missing.\n let hasAllDependencies = true;\n if (!this.isLoaded()) {\n for (const id of ids) {\n if (!this.images[id]) {\n hasAllDependencies = false;\n }\n }\n }\n if (this.isLoaded() || hasAllDependencies) {\n this._notify(ids, callback);\n } else {\n this.requestors.push({ids, callback});\n }\n }\n\n _notify(ids: Array, callback: Callback<{[_: string]: StyleImage}>) {\n const response = {};\n\n for (const id of ids) {\n if (!this.images[id]) {\n this.fire(new Event('styleimagemissing', {id}));\n }\n const image = this.images[id];\n if (image) {\n // Clone the image so that our own copy of its ArrayBuffer doesn't get transferred.\n response[id] = {\n data: image.data.clone(),\n pixelRatio: image.pixelRatio,\n sdf: image.sdf,\n version: image.version,\n stretchX: image.stretchX,\n stretchY: image.stretchY,\n content: image.content,\n hasRenderCallback: Boolean(image.userImage && image.userImage.render)\n };\n } else {\n warnOnce(`Image \"${id}\" could not be loaded. Please make sure you have added the image with map.addImage() or a \"sprite\" property in your style. You can provide missing images by listening for the \"styleimagemissing\" map event.`);\n }\n }\n\n callback(null, response);\n }\n\n // Pattern stuff\n\n getPixelSize() {\n const {width, height} = this.atlasImage;\n return {width, height};\n }\n\n getPattern(id: string): ?ImagePosition {\n const pattern = this.patterns[id];\n\n const image = this.getImage(id);\n if (!image) {\n return null;\n }\n\n if (pattern && pattern.position.version === image.version) {\n return pattern.position;\n }\n\n if (!pattern) {\n const w = image.data.width + padding * 2;\n const h = image.data.height + padding * 2;\n const bin = {w, h, x: 0, y: 0};\n const position = new ImagePosition(bin, image);\n this.patterns[id] = {bin, position};\n } else {\n pattern.position.version = image.version;\n }\n\n this._updatePatternAtlas();\n\n return this.patterns[id].position;\n }\n\n bind(context: Context) {\n const gl = context.gl;\n if (!this.atlasTexture) {\n this.atlasTexture = new Texture(context, this.atlasImage, gl.RGBA);\n } else if (this.dirty) {\n this.atlasTexture.update(this.atlasImage);\n this.dirty = false;\n }\n\n this.atlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n }\n\n _updatePatternAtlas() {\n const bins = [];\n for (const id in this.patterns) {\n bins.push(this.patterns[id].bin);\n }\n\n const {w, h} = potpack(bins);\n\n const dst = this.atlasImage;\n dst.resize({width: w || 1, height: h || 1});\n\n for (const id in this.patterns) {\n const {bin} = this.patterns[id];\n const x = bin.x + padding;\n const y = bin.y + padding;\n const src = this.images[id].data;\n const w = src.width;\n const h = src.height;\n\n RGBAImage.copy(src, dst, {x: 0, y: 0}, {x, y}, {width: w, height: h});\n\n // Add 1 pixel wrapped padding on each side of the image.\n RGBAImage.copy(src, dst, {x: 0, y: h - 1}, {x, y: y - 1}, {width: w, height: 1}); // T\n RGBAImage.copy(src, dst, {x: 0, y: 0}, {x, y: y + h}, {width: w, height: 1}); // B\n RGBAImage.copy(src, dst, {x: w - 1, y: 0}, {x: x - 1, y}, {width: 1, height: h}); // L\n RGBAImage.copy(src, dst, {x: 0, y: 0}, {x: x + w, y}, {width: 1, height: h}); // R\n }\n\n this.dirty = true;\n }\n\n beginFrame() {\n this.callbackDispatchedThisFrame = {};\n }\n\n dispatchRenderCallbacks(ids: Array) {\n for (const id of ids) {\n\n // the callback for the image was already dispatched for a different frame\n if (this.callbackDispatchedThisFrame[id]) continue;\n this.callbackDispatchedThisFrame[id] = true;\n\n const image = this.images[id];\n assert(image);\n\n const updated = renderStyleImage(image);\n if (updated) {\n this.updateImage(id, image);\n }\n }\n }\n}\n\nexport default ImageManager;\n","'use strict';\n\nmodule.exports = TinySDF;\nmodule.exports.default = TinySDF;\n\nvar INF = 1e20;\n\nfunction TinySDF(fontSize, buffer, radius, cutoff, fontFamily, fontWeight) {\n this.fontSize = fontSize || 24;\n this.buffer = buffer === undefined ? 3 : buffer;\n this.cutoff = cutoff || 0.25;\n this.fontFamily = fontFamily || 'sans-serif';\n this.fontWeight = fontWeight || 'normal';\n this.radius = radius || 8;\n var size = this.size = this.fontSize + this.buffer * 2;\n\n this.canvas = document.createElement('canvas');\n this.canvas.width = this.canvas.height = size;\n\n this.ctx = this.canvas.getContext('2d');\n this.ctx.font = this.fontWeight + ' ' + this.fontSize + 'px ' + this.fontFamily;\n this.ctx.textBaseline = 'middle';\n this.ctx.fillStyle = 'black';\n\n // temporary arrays for the distance transform\n this.gridOuter = new Float64Array(size * size);\n this.gridInner = new Float64Array(size * size);\n this.f = new Float64Array(size);\n this.d = new Float64Array(size);\n this.z = new Float64Array(size + 1);\n this.v = new Int16Array(size);\n\n // hack around https://bugzilla.mozilla.org/show_bug.cgi?id=737852\n this.middle = Math.round((size / 2) * (navigator.userAgent.indexOf('Gecko/') >= 0 ? 1.2 : 1));\n}\n\nTinySDF.prototype.draw = function (char) {\n this.ctx.clearRect(0, 0, this.size, this.size);\n this.ctx.fillText(char, this.buffer, this.middle);\n\n var imgData = this.ctx.getImageData(0, 0, this.size, this.size);\n var alphaChannel = new Uint8ClampedArray(this.size * this.size);\n\n for (var i = 0; i < this.size * this.size; i++) {\n var a = imgData.data[i * 4 + 3] / 255; // alpha value\n this.gridOuter[i] = a === 1 ? 0 : a === 0 ? INF : Math.pow(Math.max(0, 0.5 - a), 2);\n this.gridInner[i] = a === 1 ? INF : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2);\n }\n\n edt(this.gridOuter, this.size, this.size, this.f, this.d, this.v, this.z);\n edt(this.gridInner, this.size, this.size, this.f, this.d, this.v, this.z);\n\n for (i = 0; i < this.size * this.size; i++) {\n var d = this.gridOuter[i] - this.gridInner[i];\n alphaChannel[i] = Math.max(0, Math.min(255, Math.round(255 - 255 * (d / this.radius + this.cutoff))));\n }\n\n return alphaChannel;\n};\n\n// 2D Euclidean distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf\nfunction edt(data, width, height, f, d, v, z) {\n for (var x = 0; x < width; x++) {\n for (var y = 0; y < height; y++) {\n f[y] = data[y * width + x];\n }\n edt1d(f, d, v, z, height);\n for (y = 0; y < height; y++) {\n data[y * width + x] = d[y];\n }\n }\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n f[x] = data[y * width + x];\n }\n edt1d(f, d, v, z, width);\n for (x = 0; x < width; x++) {\n data[y * width + x] = Math.sqrt(d[x]);\n }\n }\n}\n\n// 1D squared distance transform\nfunction edt1d(f, d, v, z, n) {\n v[0] = 0;\n z[0] = -INF;\n z[1] = +INF;\n\n for (var q = 1, k = 0; q < n; q++) {\n var s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);\n while (s <= z[k]) {\n k--;\n s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);\n }\n k++;\n v[k] = q;\n z[k] = s;\n z[k + 1] = +INF;\n }\n\n for (q = 0, k = 0; q < n; q++) {\n while (z[k + 1] < q) k++;\n d[q] = (q - v[k]) * (q - v[k]) + f[v[k]];\n }\n}\n","// @flow\n\nimport loadGlyphRange from '../style/load_glyph_range';\n\nimport TinySDF from '@mapbox/tiny-sdf';\nimport isChar from '../util/is_char_in_unicode_block';\nimport {asyncAll} from '../util/util';\nimport {AlphaImage} from '../util/image';\n\nimport type {StyleGlyph} from '../style/style_glyph';\nimport type {RequestManager} from '../util/mapbox';\nimport type {Callback} from '../types/callback';\n\ntype Entry = {\n // null means we've requested the range, but the glyph wasn't included in the result.\n glyphs: {[id: number]: StyleGlyph | null},\n requests: {[range: number]: Array>},\n ranges: {[range: number]: boolean | null},\n tinySDF?: TinySDF\n};\n\nclass GlyphManager {\n requestManager: RequestManager;\n localIdeographFontFamily: ?string;\n entries: {[_: string]: Entry};\n url: ?string;\n\n // exposed as statics to enable stubbing in unit tests\n static loadGlyphRange: typeof loadGlyphRange;\n static TinySDF: Class;\n\n constructor(requestManager: RequestManager, localIdeographFontFamily: ?string) {\n this.requestManager = requestManager;\n this.localIdeographFontFamily = localIdeographFontFamily;\n this.entries = {};\n }\n\n setURL(url: ?string) {\n this.url = url;\n }\n\n getGlyphs(glyphs: {[stack: string]: Array}, callback: Callback<{[stack: string]: {[id: number]: ?StyleGlyph}}>) {\n const all = [];\n\n for (const stack in glyphs) {\n for (const id of glyphs[stack]) {\n all.push({stack, id});\n }\n }\n\n asyncAll(all, ({stack, id}, callback: Callback<{stack: string, id: number, glyph: ?StyleGlyph}>) => {\n let entry = this.entries[stack];\n if (!entry) {\n entry = this.entries[stack] = {\n glyphs: {},\n requests: {},\n ranges: {}\n };\n }\n\n let glyph = entry.glyphs[id];\n if (glyph !== undefined) {\n callback(null, {stack, id, glyph});\n return;\n }\n\n glyph = this._tinySDF(entry, stack, id);\n if (glyph) {\n entry.glyphs[id] = glyph;\n callback(null, {stack, id, glyph});\n return;\n }\n\n const range = Math.floor(id / 256);\n if (range * 256 > 65535) {\n callback(new Error('glyphs > 65535 not supported'));\n return;\n }\n\n if (entry.ranges[range]) {\n callback(null, {stack, id, glyph});\n return;\n }\n\n let requests = entry.requests[range];\n if (!requests) {\n requests = entry.requests[range] = [];\n GlyphManager.loadGlyphRange(stack, range, (this.url: any), this.requestManager,\n (err, response: ?{[_: number]: StyleGlyph | null}) => {\n if (response) {\n for (const id in response) {\n if (!this._doesCharSupportLocalGlyph(+id)) {\n entry.glyphs[+id] = response[+id];\n }\n }\n entry.ranges[range] = true;\n }\n for (const cb of requests) {\n cb(err, response);\n }\n delete entry.requests[range];\n });\n }\n\n requests.push((err, result: ?{[_: number]: StyleGlyph | null}) => {\n if (err) {\n callback(err);\n } else if (result) {\n callback(null, {stack, id, glyph: result[id] || null});\n }\n });\n }, (err, glyphs: ?Array<{stack: string, id: number, glyph: ?StyleGlyph}>) => {\n if (err) {\n callback(err);\n } else if (glyphs) {\n const result = {};\n\n for (const {stack, id, glyph} of glyphs) {\n // Clone the glyph so that our own copy of its ArrayBuffer doesn't get transferred.\n (result[stack] || (result[stack] = {}))[id] = glyph && {\n id: glyph.id,\n bitmap: glyph.bitmap.clone(),\n metrics: glyph.metrics\n };\n }\n\n callback(null, result);\n }\n });\n }\n\n _doesCharSupportLocalGlyph(id: number): boolean {\n /* eslint-disable new-cap */\n return !!this.localIdeographFontFamily &&\n (isChar['CJK Unified Ideographs'](id) ||\n isChar['Hangul Syllables'](id) ||\n isChar['Hiragana'](id) ||\n isChar['Katakana'](id));\n /* eslint-enable new-cap */\n }\n\n _tinySDF(entry: Entry, stack: string, id: number): ?StyleGlyph {\n const family = this.localIdeographFontFamily;\n if (!family) {\n return;\n }\n\n if (!this._doesCharSupportLocalGlyph(id)) {\n return;\n }\n\n let tinySDF = entry.tinySDF;\n if (!tinySDF) {\n let fontWeight = '400';\n if (/bold/i.test(stack)) {\n fontWeight = '900';\n } else if (/medium/i.test(stack)) {\n fontWeight = '500';\n } else if (/light/i.test(stack)) {\n fontWeight = '200';\n }\n tinySDF = entry.tinySDF = new GlyphManager.TinySDF(24, 3, 8, .25, family, fontWeight);\n }\n\n return {\n id,\n bitmap: new AlphaImage({width: 30, height: 30}, tinySDF.draw(String.fromCharCode(id))),\n metrics: {\n width: 24,\n height: 24,\n left: 0,\n top: -8,\n advance: 24\n }\n };\n }\n}\n\nGlyphManager.loadGlyphRange = loadGlyphRange;\nGlyphManager.TinySDF = TinySDF;\n\nexport default GlyphManager;\n","// @flow\n\nimport {getArrayBuffer, ResourceType} from '../util/ajax';\n\nimport parseGlyphPBF from './parse_glyph_pbf';\n\nimport type {StyleGlyph} from './style_glyph';\nimport type {RequestManager} from '../util/mapbox';\nimport type {Callback} from '../types/callback';\n\nexport default function (fontstack: string,\n range: number,\n urlTemplate: string,\n requestManager: RequestManager,\n callback: Callback<{[_: number]: StyleGlyph | null}>) {\n const begin = range * 256;\n const end = begin + 255;\n\n const request = requestManager.transformRequest(\n requestManager.normalizeGlyphsURL(urlTemplate)\n .replace('{fontstack}', fontstack)\n .replace('{range}', `${begin}-${end}`),\n ResourceType.Glyphs);\n\n getArrayBuffer(request, (err: ?Error, data: ?ArrayBuffer) => {\n if (err) {\n callback(err);\n } else if (data) {\n const glyphs = {};\n\n for (const glyph of parseGlyphPBF(data)) {\n glyphs[glyph.id] = glyph;\n }\n\n callback(null, glyphs);\n }\n });\n}\n","// @flow\n\nimport styleSpec from '../style-spec/reference/latest';\n\nimport {endsWith, extend, sphericalToCartesian} from '../util/util';\nimport {Evented} from '../util/evented';\nimport {\n validateStyle,\n validateLight,\n emitValidationErrors\n} from './validate_style';\nimport Color from '../style-spec/util/color';\nimport {number as interpolate} from '../style-spec/util/interpolate';\n\nimport type {StylePropertySpecification} from '../style-spec/style-spec';\nimport type EvaluationParameters from './evaluation_parameters';\nimport type {StyleSetterOptions} from '../style/style';\nimport {Properties, Transitionable, Transitioning, PossiblyEvaluated, DataConstantProperty} from './properties';\n\nimport type {\n Property,\n PropertyValue,\n TransitionParameters\n} from './properties';\n\nimport type {LightSpecification} from '../style-spec/types';\n\ntype LightPosition = {\n x: number,\n y: number,\n z: number\n};\n\nclass LightPositionProperty implements Property<[number, number, number], LightPosition> {\n specification: StylePropertySpecification;\n\n constructor() {\n this.specification = styleSpec.light.position;\n }\n\n possiblyEvaluate(value: PropertyValue<[number, number, number], LightPosition>, parameters: EvaluationParameters): LightPosition {\n return sphericalToCartesian(value.expression.evaluate(parameters));\n }\n\n interpolate(a: LightPosition, b: LightPosition, t: number): LightPosition {\n return {\n x: interpolate(a.x, b.x, t),\n y: interpolate(a.y, b.y, t),\n z: interpolate(a.z, b.z, t),\n };\n }\n}\n\ntype Props = {|\n \"anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"position\": LightPositionProperty,\n \"color\": DataConstantProperty,\n \"intensity\": DataConstantProperty,\n|};\n\nconst properties: Properties = new Properties({\n \"anchor\": new DataConstantProperty(styleSpec.light.anchor),\n \"position\": new LightPositionProperty(),\n \"color\": new DataConstantProperty(styleSpec.light.color),\n \"intensity\": new DataConstantProperty(styleSpec.light.intensity),\n});\n\nconst TRANSITION_SUFFIX = '-transition';\n\n/*\n * Represents the light used to light extruded features.\n */\nclass Light extends Evented {\n _transitionable: Transitionable;\n _transitioning: Transitioning;\n properties: PossiblyEvaluated;\n\n constructor(lightOptions?: LightSpecification) {\n super();\n this._transitionable = new Transitionable(properties);\n this.setLight(lightOptions);\n this._transitioning = this._transitionable.untransitioned();\n }\n\n getLight() {\n return this._transitionable.serialize();\n }\n\n setLight(light?: LightSpecification, options: StyleSetterOptions = {}) {\n if (this._validate(validateLight, light, options)) {\n return;\n }\n\n for (const name in light) {\n const value = light[name];\n if (endsWith(name, TRANSITION_SUFFIX)) {\n this._transitionable.setTransition(name.slice(0, -TRANSITION_SUFFIX.length), value);\n } else {\n this._transitionable.setValue(name, value);\n }\n }\n }\n\n updateTransitions(parameters: TransitionParameters) {\n this._transitioning = this._transitionable.transitioned(parameters, this._transitioning);\n }\n\n hasTransition() {\n return this._transitioning.hasTransition();\n }\n\n recalculate(parameters: EvaluationParameters) {\n this.properties = this._transitioning.possiblyEvaluate(parameters);\n }\n\n _validate(validate: Function, value: mixed, options?: {validate?: boolean}) {\n if (options && options.validate === false) {\n return false;\n }\n\n return emitValidationErrors(this, validate.call(validateStyle, extend({\n value,\n // Workaround for https://github.com/mapbox/mapbox-gl-js/issues/2407\n style: {glyphs: true, sprite: true},\n styleSpec\n })));\n }\n}\n\nexport default Light;\n","// @flow\n\nimport {warnOnce} from '../util/util';\n\nimport type Context from '../gl/context';\n\n/**\n * A LineAtlas lets us reuse rendered dashed lines\n * by writing many of them to a texture and then fetching their positions\n * using .getDash.\n *\n * @param {number} width\n * @param {number} height\n * @private\n */\nclass LineAtlas {\n width: number;\n height: number;\n nextRow: number;\n bytes: number;\n data: Uint8Array;\n dashEntry: {[_: string]: any};\n dirty: boolean;\n texture: WebGLTexture;\n\n constructor(width: number, height: number) {\n this.width = width;\n this.height = height;\n this.nextRow = 0;\n\n this.data = new Uint8Array(this.width * this.height);\n\n this.dashEntry = {};\n }\n\n /**\n * Get or create a dash line pattern.\n *\n * @param {Array} dasharray\n * @param {boolean} round whether to add circle caps in between dash segments\n * @returns {Object} position of dash texture in { y, height, width }\n * @private\n */\n getDash(dasharray: Array, round: boolean) {\n const key = dasharray.join(\",\") + String(round);\n\n if (!this.dashEntry[key]) {\n this.dashEntry[key] = this.addDash(dasharray, round);\n }\n return this.dashEntry[key];\n }\n\n getDashRanges(dasharray: Array, lineAtlasWidth: number, stretch: number) {\n // If dasharray has an odd length, both the first and last parts\n // are dashes and should be joined seamlessly.\n const oddDashArray = dasharray.length % 2 === 1;\n\n const ranges = [];\n\n let left = oddDashArray ? -dasharray[dasharray.length - 1] * stretch : 0;\n let right = dasharray[0] * stretch;\n let isDash = true;\n\n ranges.push({left, right, isDash, zeroLength: dasharray[0] === 0});\n\n let currentDashLength = dasharray[0];\n for (let i = 1; i < dasharray.length; i++) {\n isDash = !isDash;\n\n const dashLength = dasharray[i];\n left = currentDashLength * stretch;\n currentDashLength += dashLength;\n right = currentDashLength * stretch;\n\n ranges.push({left, right, isDash, zeroLength: dashLength === 0});\n }\n\n return ranges;\n }\n\n addRoundDash(ranges: Object, stretch: number, n: number) {\n const halfStretch = stretch / 2;\n\n for (let y = -n; y <= n; y++) {\n const row = this.nextRow + n + y;\n const index = this.width * row;\n let currIndex = 0;\n let range = ranges[currIndex];\n\n for (let x = 0; x < this.width; x++) {\n if (x / range.right > 1) { range = ranges[++currIndex]; }\n\n const distLeft = Math.abs(x - range.left);\n const distRight = Math.abs(x - range.right);\n const minDist = Math.min(distLeft, distRight);\n let signedDistance;\n\n const distMiddle = y / n * (halfStretch + 1);\n if (range.isDash) {\n const distEdge = halfStretch - Math.abs(distMiddle);\n signedDistance = Math.sqrt(minDist * minDist + distEdge * distEdge);\n } else {\n signedDistance = halfStretch - Math.sqrt(minDist * minDist + distMiddle * distMiddle);\n }\n\n this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128));\n }\n }\n }\n\n addRegularDash(ranges: Object) {\n\n // Collapse any zero-length range\n // Collapse neighbouring same-type parts into a single part\n for (let i = ranges.length - 1; i >= 0; --i) {\n const part = ranges[i];\n const next = ranges[i + 1];\n if (part.zeroLength) {\n ranges.splice(i, 1);\n } else if (next && next.isDash === part.isDash) {\n next.left = part.left;\n ranges.splice(i, 1);\n }\n }\n\n // Combine the first and last parts if possible\n const first = ranges[0];\n const last = ranges[ranges.length - 1];\n if (first.isDash === last.isDash) {\n first.left = last.left - this.width;\n last.right = first.right + this.width;\n }\n\n const index = this.width * this.nextRow;\n let currIndex = 0;\n let range = ranges[currIndex];\n\n for (let x = 0; x < this.width; x++) {\n if (x / range.right > 1) {\n range = ranges[++currIndex];\n }\n\n const distLeft = Math.abs(x - range.left);\n const distRight = Math.abs(x - range.right);\n\n const minDist = Math.min(distLeft, distRight);\n const signedDistance = range.isDash ? minDist : -minDist;\n\n this.data[index + x] = Math.max(0, Math.min(255, signedDistance + 128));\n }\n }\n\n addDash(dasharray: Array, round: boolean) {\n const n = round ? 7 : 0;\n const height = 2 * n + 1;\n\n if (this.nextRow + height > this.height) {\n warnOnce('LineAtlas out of space');\n return null;\n }\n\n let length = 0;\n for (let i = 0; i < dasharray.length; i++) { length += dasharray[i]; }\n\n if (length !== 0) {\n const stretch = this.width / length;\n const ranges = this.getDashRanges(dasharray, this.width, stretch);\n\n if (round) {\n this.addRoundDash(ranges, stretch, n);\n } else {\n this.addRegularDash(ranges);\n }\n }\n\n const dashEntry = {\n y: (this.nextRow + n + 0.5) / this.height,\n height: 2 * n / this.height,\n width: length\n };\n\n this.nextRow += height;\n this.dirty = true;\n\n return dashEntry;\n }\n\n bind(context: Context) {\n const gl = context.gl;\n if (!this.texture) {\n this.texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, this.texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, this.width, this.height, 0, gl.ALPHA, gl.UNSIGNED_BYTE, this.data);\n\n } else {\n gl.bindTexture(gl.TEXTURE_2D, this.texture);\n\n if (this.dirty) {\n this.dirty = false;\n gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, this.width, this.height, gl.ALPHA, gl.UNSIGNED_BYTE, this.data);\n }\n }\n }\n}\n\nexport default LineAtlas;\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\nimport {uniqueId, asyncAll} from './util';\nimport Actor from './actor';\nimport assert from 'assert';\n\nimport type WorkerPool from './worker_pool';\n\n/**\n * Responsible for sending messages from a {@link Source} to an associated\n * {@link WorkerSource}.\n *\n * @private\n */\nclass Dispatcher {\n workerPool: WorkerPool;\n actors: Array;\n currentActor: number;\n id: number;\n\n // exposed to allow stubbing in unit tests\n static Actor: Class;\n\n constructor(workerPool: WorkerPool, parent: any) {\n this.workerPool = workerPool;\n this.actors = [];\n this.currentActor = 0;\n this.id = uniqueId();\n const workers = this.workerPool.acquire(this.id);\n for (let i = 0; i < workers.length; i++) {\n const worker = workers[i];\n const actor = new Dispatcher.Actor(worker, parent, this.id);\n actor.name = `Worker ${i}`;\n this.actors.push(actor);\n }\n assert(this.actors.length);\n }\n\n /**\n * Broadcast a message to all Workers.\n * @private\n */\n broadcast(type: string, data: mixed, cb?: Function) {\n assert(this.actors.length);\n cb = cb || function () {};\n asyncAll(this.actors, (actor, done) => {\n actor.send(type, data, done);\n }, cb);\n }\n\n /**\n * Acquires an actor to dispatch messages to. The actors are distributed in round-robin fashion.\n * @returns An actor object backed by a web worker for processing messages.\n */\n getActor(): Actor {\n assert(this.actors.length);\n this.currentActor = (this.currentActor + 1) % this.actors.length;\n return this.actors[this.currentActor];\n }\n\n remove() {\n this.actors.forEach((actor) => { actor.remove(); });\n this.actors = [];\n this.workerPool.release(this.id);\n }\n}\n\nDispatcher.Actor = Actor;\n\nexport default Dispatcher;\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 {pick, extend} from '../util/util';\n\nimport {getJSON, ResourceType} from '../util/ajax';\nimport browser from '../util/browser';\n\nimport type {RequestManager} from '../util/mapbox';\nimport type {Callback} from '../types/callback';\nimport type {TileJSON} from '../types/tilejson';\nimport type {Cancelable} from '../types/cancelable';\n\nexport default function(options: any, requestManager: RequestManager, callback: Callback): Cancelable {\n const loaded = function(err: ?Error, tileJSON: ?Object) {\n if (err) {\n return callback(err);\n } else if (tileJSON) {\n const result: any = pick(\n // explicit source options take precedence over TileJSON\n extend(tileJSON, options),\n ['tiles', 'minzoom', 'maxzoom', 'attribution', 'mapbox_logo', 'bounds', 'scheme', 'tileSize', 'encoding']\n );\n\n if (tileJSON.vector_layers) {\n result.vectorLayers = tileJSON.vector_layers;\n result.vectorLayerIds = result.vectorLayers.map((layer) => { return layer.id; });\n }\n\n result.tiles = requestManager.canonicalizeTileset(result, options.url);\n callback(null, result);\n }\n };\n\n if (options.url) {\n return getJSON(requestManager.transformRequest(requestManager.normalizeSourceURL(options.url), ResourceType.Source), loaded);\n } else {\n return browser.frame(() => loaded(null, options));\n }\n}\n","// @flow\n\nimport LngLatBounds from '../geo/lng_lat_bounds';\nimport {mercatorXfromLng, mercatorYfromLat} from '../geo/mercator_coordinate';\n\nimport type {CanonicalTileID} from './tile_id';\n\nclass TileBounds {\n bounds: LngLatBounds;\n minzoom: number;\n maxzoom: number;\n\n constructor(bounds: [number, number, number, number], minzoom: ?number, maxzoom: ?number) {\n this.bounds = LngLatBounds.convert(this.validateBounds(bounds));\n this.minzoom = minzoom || 0;\n this.maxzoom = maxzoom || 24;\n }\n\n validateBounds(bounds: [number, number, number, number]) {\n // make sure the bounds property contains valid longitude and latitudes\n if (!Array.isArray(bounds) || bounds.length !== 4) return [-180, -90, 180, 90];\n return [Math.max(-180, bounds[0]), Math.max(-90, bounds[1]), Math.min(180, bounds[2]), Math.min(90, bounds[3])];\n }\n\n contains(tileID: CanonicalTileID) {\n const worldSize = Math.pow(2, tileID.z);\n const level = {\n minX: Math.floor(mercatorXfromLng(this.bounds.getWest()) * worldSize),\n minY: Math.floor(mercatorYfromLat(this.bounds.getNorth()) * worldSize),\n maxX: Math.ceil(mercatorXfromLng(this.bounds.getEast()) * worldSize),\n maxY: Math.ceil(mercatorYfromLat(this.bounds.getSouth()) * worldSize)\n };\n const hit = tileID.x >= level.minX && tileID.x < level.maxX && tileID.y >= level.minY && tileID.y < level.maxY;\n return hit;\n }\n}\n\nexport default TileBounds;\n","// @flow\n\nimport {Event, ErrorEvent, Evented} from '../util/evented';\n\nimport {extend, pick} from '../util/util';\nimport loadTileJSON from './load_tilejson';\nimport {postTurnstileEvent, postMapLoadEvent} from '../util/mapbox';\nimport TileBounds from './tile_bounds';\nimport {ResourceType} from '../util/ajax';\nimport browser from '../util/browser';\nimport {cacheEntryPossiblyAdded} from '../util/tile_request_cache';\n\nimport type {Source} from './source';\nimport type {OverscaledTileID} from './tile_id';\nimport type Map from '../ui/map';\nimport type Dispatcher from '../util/dispatcher';\nimport type Tile from './tile';\nimport type {Callback} from '../types/callback';\nimport type {Cancelable} from '../types/cancelable';\nimport type {VectorSourceSpecification, PromoteIdSpecification} from '../style-spec/types';\n\n/**\n * A source containing vector tiles in [Mapbox Vector Tile format](https://docs.mapbox.com/vector-tiles/reference/).\n * (See the [Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector) for detailed documentation of options.)\n *\n * @example\n * map.addSource('some id', {\n * type: 'vector',\n * url: 'mapbox://mapbox.mapbox-streets-v6'\n * });\n *\n * @example\n * map.addSource('some id', {\n * type: 'vector',\n * tiles: ['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt'],\n * minzoom: 6,\n * maxzoom: 14\n * });\n *\n * @example\n * map.getSource('some id').setUrl(\"mapbox://mapbox.mapbox-streets-v6\");\n *\n * @example\n * map.getSource('some id').setTiles(['https://d25uarhxywzl1j.cloudfront.net/v0.1/{z}/{x}/{y}.mvt']);\n * @see [Add a vector tile source](https://docs.mapbox.com/mapbox-gl-js/example/vector-source/)\n * @see [Add a third party vector tile source](https://docs.mapbox.com/mapbox-gl-js/example/third-party/)\n */\nclass VectorTileSource extends Evented implements Source {\n type: 'vector';\n id: string;\n minzoom: number;\n maxzoom: number;\n url: string;\n scheme: string;\n tileSize: number;\n promoteId: ?PromoteIdSpecification;\n\n _options: VectorSourceSpecification;\n _collectResourceTiming: boolean;\n dispatcher: Dispatcher;\n map: Map;\n bounds: ?[number, number, number, number];\n tiles: Array;\n tileBounds: TileBounds;\n reparseOverscaled: boolean;\n isTileClipped: boolean;\n _tileJSONRequest: ?Cancelable;\n _loaded: boolean;\n\n constructor(id: string, options: VectorSourceSpecification & {collectResourceTiming: boolean}, dispatcher: Dispatcher, eventedParent: Evented) {\n super();\n this.id = id;\n this.dispatcher = dispatcher;\n\n this.type = 'vector';\n this.minzoom = 0;\n this.maxzoom = 22;\n this.scheme = 'xyz';\n this.tileSize = 512;\n this.reparseOverscaled = true;\n this.isTileClipped = true;\n this._loaded = false;\n\n extend(this, pick(options, ['url', 'scheme', 'tileSize', 'promoteId']));\n this._options = extend({type: 'vector'}, options);\n\n this._collectResourceTiming = options.collectResourceTiming;\n\n if (this.tileSize !== 512) {\n throw new Error('vector tile sources must have a tileSize of 512');\n }\n\n this.setEventedParent(eventedParent);\n }\n\n load() {\n this._loaded = false;\n this.fire(new Event('dataloading', {dataType: 'source'}));\n this._tileJSONRequest = loadTileJSON(this._options, this.map._requestManager, (err, tileJSON) => {\n this._tileJSONRequest = null;\n this._loaded = true;\n if (err) {\n this.fire(new ErrorEvent(err));\n } else if (tileJSON) {\n extend(this, tileJSON);\n if (tileJSON.bounds) this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);\n postTurnstileEvent(tileJSON.tiles, this.map._requestManager._customAccessToken);\n postMapLoadEvent(tileJSON.tiles, this.map._getMapId(), this.map._requestManager._skuToken, this.map._requestManager._customAccessToken);\n\n // `content` is included here to prevent a race condition where `Style#_updateSources` is called\n // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives\n // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088\n this.fire(new Event('data', {dataType: 'source', sourceDataType: 'metadata'}));\n this.fire(new Event('data', {dataType: 'source', sourceDataType: 'content'}));\n }\n });\n }\n\n loaded(): boolean {\n return this._loaded;\n }\n\n hasTile(tileID: OverscaledTileID) {\n return !this.tileBounds || this.tileBounds.contains(tileID.canonical);\n }\n\n onAdd(map: Map) {\n this.map = map;\n this.load();\n }\n\n setSourceProperty(callback: Function) {\n if (this._tileJSONRequest) {\n this._tileJSONRequest.cancel();\n }\n\n callback();\n\n const sourceCache = this.map.style.sourceCaches[this.id];\n sourceCache.clearTiles();\n this.load();\n }\n\n /**\n * Sets the source `tiles` property and re-renders the map.\n *\n * @param {string[]} tiles An array of one or more tile source URLs, as in the TileJSON spec.\n * @returns {VectorTileSource} this\n */\n setTiles(tiles: Array) {\n this.setSourceProperty(() => {\n this._options.tiles = tiles;\n });\n\n return this;\n }\n\n /**\n * Sets the source `url` property and re-renders the map.\n *\n * @param {string} url A URL to a TileJSON resource. Supported protocols are `http:`, `https:`, and `mapbox://`.\n * @returns {VectorTileSource} this\n */\n setUrl(url: string) {\n this.setSourceProperty(() => {\n this.url = url;\n this._options.url = url;\n });\n\n return this;\n }\n\n onRemove() {\n if (this._tileJSONRequest) {\n this._tileJSONRequest.cancel();\n this._tileJSONRequest = null;\n }\n }\n\n serialize() {\n return extend({}, this._options);\n }\n\n loadTile(tile: Tile, callback: Callback) {\n const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme));\n const params = {\n request: this.map._requestManager.transformRequest(url, ResourceType.Tile),\n uid: tile.uid,\n tileID: tile.tileID,\n zoom: tile.tileID.overscaledZ,\n tileSize: this.tileSize * tile.tileID.overscaleFactor(),\n type: this.type,\n source: this.id,\n pixelRatio: browser.devicePixelRatio,\n showCollisionBoxes: this.map.showCollisionBoxes,\n promoteId: this.promoteId\n };\n params.request.collectResourceTiming = this._collectResourceTiming;\n\n if (!tile.actor || tile.state === 'expired') {\n tile.actor = this.dispatcher.getActor();\n tile.request = tile.actor.send('loadTile', params, done.bind(this));\n } else if (tile.state === 'loading') {\n // schedule tile reloading after it has been loaded\n tile.reloadCallback = callback;\n } else {\n tile.request = tile.actor.send('reloadTile', params, done.bind(this));\n }\n\n function done(err, data) {\n delete tile.request;\n\n if (tile.aborted)\n return callback(null);\n\n if (err && err.status !== 404) {\n return callback(err);\n }\n\n if (data && data.resourceTiming)\n tile.resourceTiming = data.resourceTiming;\n\n if (this.map._refreshExpiredTiles && data) tile.setExpiryData(data);\n tile.loadVectorData(data, this.map.painter);\n\n cacheEntryPossiblyAdded(this.dispatcher);\n\n callback(null);\n\n if (tile.reloadCallback) {\n this.loadTile(tile, tile.reloadCallback);\n tile.reloadCallback = null;\n }\n }\n }\n\n abortTile(tile: Tile) {\n if (tile.request) {\n tile.request.cancel();\n delete tile.request;\n }\n if (tile.actor) {\n tile.actor.send('abortTile', {uid: tile.uid, type: this.type, source: this.id}, undefined);\n }\n }\n\n unloadTile(tile: Tile) {\n tile.unloadVectorData();\n if (tile.actor) {\n tile.actor.send('removeTile', {uid: tile.uid, type: this.type, source: this.id}, undefined);\n }\n }\n\n hasTransition() {\n return false;\n }\n}\n\nexport default VectorTileSource;\n","// @flow\n\nimport {extend, pick} from '../util/util';\n\nimport {getImage, ResourceType} from '../util/ajax';\nimport {Event, ErrorEvent, Evented} from '../util/evented';\nimport loadTileJSON from './load_tilejson';\nimport {postTurnstileEvent, postMapLoadEvent} from '../util/mapbox';\nimport TileBounds from './tile_bounds';\nimport Texture from '../render/texture';\n\nimport {cacheEntryPossiblyAdded} from '../util/tile_request_cache';\n\nimport type {Source} from './source';\nimport type {OverscaledTileID} from './tile_id';\nimport type Map from '../ui/map';\nimport type Dispatcher from '../util/dispatcher';\nimport type Tile from './tile';\nimport type {Callback} from '../types/callback';\nimport type {Cancelable} from '../types/cancelable';\nimport type {\n RasterSourceSpecification,\n RasterDEMSourceSpecification\n} from '../style-spec/types';\n\nclass RasterTileSource extends Evented implements Source {\n type: 'raster' | 'raster-dem';\n id: string;\n minzoom: number;\n maxzoom: number;\n url: string;\n scheme: string;\n tileSize: number;\n\n bounds: ?[number, number, number, number];\n tileBounds: TileBounds;\n roundZoom: boolean;\n dispatcher: Dispatcher;\n map: Map;\n tiles: Array;\n\n _loaded: boolean;\n _options: RasterSourceSpecification | RasterDEMSourceSpecification;\n _tileJSONRequest: ?Cancelable;\n\n constructor(id: string, options: RasterSourceSpecification | RasterDEMSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n super();\n this.id = id;\n this.dispatcher = dispatcher;\n this.setEventedParent(eventedParent);\n\n this.type = 'raster';\n this.minzoom = 0;\n this.maxzoom = 22;\n this.roundZoom = true;\n this.scheme = 'xyz';\n this.tileSize = 512;\n this._loaded = false;\n\n this._options = extend({type: 'raster'}, options);\n extend(this, pick(options, ['url', 'scheme', 'tileSize']));\n }\n\n load() {\n this._loaded = false;\n this.fire(new Event('dataloading', {dataType: 'source'}));\n this._tileJSONRequest = loadTileJSON(this._options, this.map._requestManager, (err, tileJSON) => {\n this._tileJSONRequest = null;\n this._loaded = true;\n if (err) {\n this.fire(new ErrorEvent(err));\n } else if (tileJSON) {\n extend(this, tileJSON);\n if (tileJSON.bounds) this.tileBounds = new TileBounds(tileJSON.bounds, this.minzoom, this.maxzoom);\n\n postTurnstileEvent(tileJSON.tiles);\n postMapLoadEvent(tileJSON.tiles, this.map._getMapId(), this.map._requestManager._skuToken);\n\n // `content` is included here to prevent a race condition where `Style#_updateSources` is called\n // before the TileJSON arrives. this makes sure the tiles needed are loaded once TileJSON arrives\n // ref: https://github.com/mapbox/mapbox-gl-js/pull/4347#discussion_r104418088\n this.fire(new Event('data', {dataType: 'source', sourceDataType: 'metadata'}));\n this.fire(new Event('data', {dataType: 'source', sourceDataType: 'content'}));\n }\n });\n }\n\n loaded(): boolean {\n return this._loaded;\n }\n\n onAdd(map: Map) {\n this.map = map;\n this.load();\n }\n\n onRemove() {\n if (this._tileJSONRequest) {\n this._tileJSONRequest.cancel();\n this._tileJSONRequest = null;\n }\n }\n\n serialize() {\n return extend({}, this._options);\n }\n\n hasTile(tileID: OverscaledTileID) {\n return !this.tileBounds || this.tileBounds.contains(tileID.canonical);\n }\n\n loadTile(tile: Tile, callback: Callback) {\n const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), this.tileSize);\n tile.request = getImage(this.map._requestManager.transformRequest(url, ResourceType.Tile), (err, img) => {\n delete tile.request;\n\n if (tile.aborted) {\n tile.state = 'unloaded';\n callback(null);\n } else if (err) {\n tile.state = 'errored';\n callback(err);\n } else if (img) {\n if (this.map._refreshExpiredTiles) tile.setExpiryData(img);\n delete (img: any).cacheControl;\n delete (img: any).expires;\n\n const context = this.map.painter.context;\n const gl = context.gl;\n tile.texture = this.map.painter.getTileTexture(img.width);\n if (tile.texture) {\n tile.texture.update(img, {useMipmap: true});\n } else {\n tile.texture = new Texture(context, img, gl.RGBA, {useMipmap: true});\n tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);\n\n if (context.extTextureFilterAnisotropic) {\n gl.texParameterf(gl.TEXTURE_2D, context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT, context.extTextureFilterAnisotropicMax);\n }\n }\n\n tile.state = 'loaded';\n\n cacheEntryPossiblyAdded(this.dispatcher);\n\n callback(null);\n }\n });\n }\n\n abortTile(tile: Tile, callback: Callback) {\n if (tile.request) {\n tile.request.cancel();\n delete tile.request;\n }\n callback();\n }\n\n unloadTile(tile: Tile, callback: Callback) {\n if (tile.texture) this.map.painter.saveTileTexture(tile.texture);\n callback();\n }\n\n hasTransition() {\n return false;\n }\n}\n\nexport default RasterTileSource;\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 {getImage, ResourceType} from '../util/ajax';\nimport {extend} from '../util/util';\nimport {Evented} from '../util/evented';\nimport browser from '../util/browser';\nimport window from '../util/window';\nimport offscreenCanvasSupported from '../util/offscreen_canvas_supported';\nimport {OverscaledTileID} from './tile_id';\nimport RasterTileSource from './raster_tile_source';\n// ensure DEMData is registered for worker transfer on main thread:\nimport '../data/dem_data';\n\nimport type {Source} from './source';\nimport type Dispatcher from '../util/dispatcher';\nimport type Tile from './tile';\nimport type {Callback} from '../types/callback';\nimport type {RasterDEMSourceSpecification} from '../style-spec/types';\n\nclass RasterDEMTileSource extends RasterTileSource implements Source {\n encoding: \"mapbox\" | \"terrarium\";\n\n constructor(id: string, options: RasterDEMSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n super(id, options, dispatcher, eventedParent);\n this.type = 'raster-dem';\n this.maxzoom = 22;\n this._options = extend({type: 'raster-dem'}, options);\n this.encoding = options.encoding || \"mapbox\";\n }\n\n serialize() {\n return {\n type: 'raster-dem',\n url: this.url,\n tileSize: this.tileSize,\n tiles: this.tiles,\n bounds: this.bounds,\n encoding: this.encoding\n };\n }\n\n loadTile(tile: Tile, callback: Callback) {\n const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), this.tileSize);\n tile.request = getImage(this.map._requestManager.transformRequest(url, ResourceType.Tile), imageLoaded.bind(this));\n\n tile.neighboringTiles = this._getNeighboringTiles(tile.tileID);\n function imageLoaded(err, img) {\n delete tile.request;\n if (tile.aborted) {\n tile.state = 'unloaded';\n callback(null);\n } else if (err) {\n tile.state = 'errored';\n callback(err);\n } else if (img) {\n if (this.map._refreshExpiredTiles) tile.setExpiryData(img);\n delete (img: any).cacheControl;\n delete (img: any).expires;\n const transfer = window.ImageBitmap && img instanceof window.ImageBitmap && offscreenCanvasSupported();\n const rawImageData = transfer ? img : browser.getImageData(img, 1);\n const params = {\n uid: tile.uid,\n coord: tile.tileID,\n source: this.id,\n rawImageData,\n encoding: this.encoding\n };\n\n if (!tile.actor || tile.state === 'expired') {\n tile.actor = this.dispatcher.getActor();\n tile.actor.send('loadDEMTile', params, done.bind(this));\n }\n }\n }\n\n function done(err, dem) {\n if (err) {\n tile.state = 'errored';\n callback(err);\n }\n\n if (dem) {\n tile.dem = dem;\n tile.needsHillshadePrepare = true;\n tile.state = 'loaded';\n callback(null);\n }\n }\n }\n\n _getNeighboringTiles(tileID: OverscaledTileID) {\n const canonical = tileID.canonical;\n const dim = Math.pow(2, canonical.z);\n\n const px = (canonical.x - 1 + dim) % dim;\n const pxw = canonical.x === 0 ? tileID.wrap - 1 : tileID.wrap;\n const nx = (canonical.x + 1 + dim) % dim;\n const nxw = canonical.x + 1 === dim ? tileID.wrap + 1 : tileID.wrap;\n\n const neighboringTiles = {};\n // add adjacent tiles\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y).key] = {backfilled: false};\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y).key] = {backfilled: false};\n\n // Add upper neighboringTiles\n if (canonical.y > 0) {\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y - 1).key] = {backfilled: false};\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y - 1).key] = {backfilled: false};\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y - 1).key] = {backfilled: false};\n }\n // Add lower neighboringTiles\n if (canonical.y + 1 < dim) {\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, pxw, canonical.z, px, canonical.y + 1).key] = {backfilled: false};\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, tileID.wrap, canonical.z, canonical.x, canonical.y + 1).key] = {backfilled: false};\n neighboringTiles[new OverscaledTileID(tileID.overscaledZ, nxw, canonical.z, nx, canonical.y + 1).key] = {backfilled: false};\n }\n\n return neighboringTiles;\n }\n\n unloadTile(tile: Tile) {\n if (tile.demTexture) this.map.painter.saveTileTexture(tile.demTexture);\n if (tile.fbo) {\n tile.fbo.destroy();\n delete tile.fbo;\n }\n if (tile.dem) delete tile.dem;\n delete tile.neighboringTiles;\n\n tile.state = 'unloaded';\n if (tile.actor) {\n tile.actor.send('removeDEMTile', {uid: tile.uid, source: this.id});\n }\n }\n\n}\n\nexport default RasterDEMTileSource;\n","// @flow\n\nimport {Event, ErrorEvent, Evented} from '../util/evented';\n\nimport {extend} from '../util/util';\nimport EXTENT from '../data/extent';\nimport {ResourceType} from '../util/ajax';\nimport browser from '../util/browser';\n\nimport type {Source} from './source';\nimport type Map from '../ui/map';\nimport type Dispatcher from '../util/dispatcher';\nimport type Tile from './tile';\nimport type Actor from '../util/actor';\nimport type {Callback} from '../types/callback';\nimport type {GeoJSON, GeoJSONFeature} from '@mapbox/geojson-types';\nimport type {GeoJSONSourceSpecification, PromoteIdSpecification} from '../style-spec/types';\n\n/**\n * A source containing GeoJSON.\n * (See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-geojson) for detailed documentation of options.)\n *\n * @example\n * map.addSource('some id', {\n * type: 'geojson',\n * data: 'https://d2ad6b4ur7yvpq.cloudfront.net/naturalearth-3.3.0/ne_10m_ports.geojson'\n * });\n *\n * @example\n * map.addSource('some id', {\n * type: 'geojson',\n * data: {\n * \"type\": \"FeatureCollection\",\n * \"features\": [{\n * \"type\": \"Feature\",\n * \"properties\": {},\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [\n * -76.53063297271729,\n * 39.18174077994108\n * ]\n * }\n * }]\n * }\n * });\n *\n * @example\n * map.getSource('some id').setData({\n * \"type\": \"FeatureCollection\",\n * \"features\": [{\n * \"type\": \"Feature\",\n * \"properties\": { \"name\": \"Null Island\" },\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [ 0, 0 ]\n * }\n * }]\n * });\n * @see [Draw GeoJSON points](https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/)\n * @see [Add a GeoJSON line](https://www.mapbox.com/mapbox-gl-js/example/geojson-line/)\n * @see [Create a heatmap from points](https://www.mapbox.com/mapbox-gl-js/example/heatmap/)\n * @see [Create and style clusters](https://www.mapbox.com/mapbox-gl-js/example/cluster/)\n */\nclass GeoJSONSource extends Evented implements Source {\n type: 'geojson';\n id: string;\n minzoom: number;\n maxzoom: number;\n tileSize: number;\n attribution: string;\n promoteId: ?PromoteIdSpecification;\n\n isTileClipped: boolean;\n reparseOverscaled: boolean;\n _data: GeoJSON | string;\n _options: any;\n workerOptions: any;\n map: Map;\n actor: Actor;\n _loaded: boolean;\n _collectResourceTiming: boolean;\n _resourceTiming: Array;\n _removed: boolean;\n\n /**\n * @private\n */\n constructor(id: string, options: GeoJSONSourceSpecification & {workerOptions?: any, collectResourceTiming: boolean}, dispatcher: Dispatcher, eventedParent: Evented) {\n super();\n\n this.id = id;\n\n // `type` is a property rather than a constant to make it easy for 3rd\n // parties to use GeoJSONSource to build their own source types.\n this.type = 'geojson';\n\n this.minzoom = 0;\n this.maxzoom = 18;\n this.tileSize = 512;\n this.isTileClipped = true;\n this.reparseOverscaled = true;\n this._removed = false;\n this._loaded = false;\n\n this.actor = dispatcher.getActor();\n this.setEventedParent(eventedParent);\n\n this._data = (options.data: any);\n this._options = extend({}, options);\n\n this._collectResourceTiming = options.collectResourceTiming;\n this._resourceTiming = [];\n\n if (options.maxzoom !== undefined) this.maxzoom = options.maxzoom;\n if (options.type) this.type = options.type;\n if (options.attribution) this.attribution = options.attribution;\n this.promoteId = options.promoteId;\n\n const scale = EXTENT / this.tileSize;\n\n // sent to the worker, along with `url: ...` or `data: literal geojson`,\n // so that it can load/parse/index the geojson data\n // extending with `options.workerOptions` helps to make it easy for\n // third-party sources to hack/reuse GeoJSONSource.\n this.workerOptions = extend({\n source: this.id,\n cluster: options.cluster || false,\n geojsonVtOptions: {\n buffer: (options.buffer !== undefined ? options.buffer : 128) * scale,\n tolerance: (options.tolerance !== undefined ? options.tolerance : 0.375) * scale,\n extent: EXTENT,\n maxZoom: this.maxzoom,\n lineMetrics: options.lineMetrics || false,\n generateId: options.generateId || false\n },\n superclusterOptions: {\n maxZoom: options.clusterMaxZoom !== undefined ?\n Math.min(options.clusterMaxZoom, this.maxzoom - 1) :\n (this.maxzoom - 1),\n minPoints: Math.max(2, options.clusterMinPoints || 2),\n extent: EXTENT,\n radius: (options.clusterRadius || 50) * scale,\n log: false,\n generateId: options.generateId || false\n },\n clusterProperties: options.clusterProperties,\n filter: options.filter\n }, options.workerOptions);\n }\n\n load() {\n this.fire(new Event('dataloading', {dataType: 'source'}));\n this._updateWorkerData((err) => {\n if (err) {\n this.fire(new ErrorEvent(err));\n return;\n }\n\n const data: Object = {dataType: 'source', sourceDataType: 'metadata'};\n if (this._collectResourceTiming && this._resourceTiming && (this._resourceTiming.length > 0)) {\n data.resourceTiming = this._resourceTiming;\n this._resourceTiming = [];\n }\n\n // although GeoJSON sources contain no metadata, we fire this event to let the SourceCache\n // know its ok to start requesting tiles.\n this.fire(new Event('data', data));\n });\n }\n\n onAdd(map: Map) {\n this.map = map;\n this.load();\n }\n\n /**\n * Sets the GeoJSON data and re-renders the map.\n *\n * @param {Object|string} data A GeoJSON data object or a URL to one. The latter is preferable in the case of large GeoJSON files.\n * @returns {GeoJSONSource} this\n */\n setData(data: GeoJSON | string) {\n this._data = data;\n this.fire(new Event('dataloading', {dataType: 'source'}));\n this._updateWorkerData((err) => {\n if (err) {\n this.fire(new ErrorEvent(err));\n return;\n }\n\n const data: Object = {dataType: 'source', sourceDataType: 'content'};\n if (this._collectResourceTiming && this._resourceTiming && (this._resourceTiming.length > 0)) {\n data.resourceTiming = this._resourceTiming;\n this._resourceTiming = [];\n }\n this.fire(new Event('data', data));\n });\n\n return this;\n }\n\n /**\n * For clustered sources, fetches the zoom at which the given cluster expands.\n *\n * @param clusterId The value of the cluster's `cluster_id` property.\n * @param callback A callback to be called when the zoom value is retrieved (`(error, zoom) => { ... }`).\n * @returns {GeoJSONSource} this\n */\n getClusterExpansionZoom(clusterId: number, callback: Callback) {\n this.actor.send('geojson.getClusterExpansionZoom', {clusterId, source: this.id}, callback);\n return this;\n }\n\n /**\n * For clustered sources, fetches the children of the given cluster on the next zoom level (as an array of GeoJSON features).\n *\n * @param clusterId The value of the cluster's `cluster_id` property.\n * @param callback A callback to be called when the features are retrieved (`(error, features) => { ... }`).\n * @returns {GeoJSONSource} this\n */\n getClusterChildren(clusterId: number, callback: Callback>) {\n this.actor.send('geojson.getClusterChildren', {clusterId, source: this.id}, callback);\n return this;\n }\n\n /**\n * For clustered sources, fetches the original points that belong to the cluster (as an array of GeoJSON features).\n *\n * @param clusterId The value of the cluster's `cluster_id` property.\n * @param limit The maximum number of features to return.\n * @param offset The number of features to skip (e.g. for pagination).\n * @param callback A callback to be called when the features are retrieved (`(error, features) => { ... }`).\n * @returns {GeoJSONSource} this\n * @example\n * // Retrieve cluster leaves on click\n * map.on('click', 'clusters', function(e) {\n * var features = map.queryRenderedFeatures(e.point, {\n * layers: ['clusters']\n * });\n *\n * var clusterId = features[0].properties.cluster_id;\n * var pointCount = features[0].properties.point_count;\n * var clusterSource = map.getSource('clusters');\n *\n * clusterSource.getClusterLeaves(clusterId, pointCount, 0, function(error, features) {\n * // Print cluster leaves in the console\n * console.log('Cluster leaves:', error, features);\n * })\n * });\n */\n getClusterLeaves(clusterId: number, limit: number, offset: number, callback: Callback>) {\n this.actor.send('geojson.getClusterLeaves', {\n source: this.id,\n clusterId,\n limit,\n offset\n }, callback);\n return this;\n }\n\n /*\n * Responsible for invoking WorkerSource's geojson.loadData target, which\n * handles loading the geojson data and preparing to serve it up as tiles,\n * using geojson-vt or supercluster as appropriate.\n */\n _updateWorkerData(callback: Callback) {\n this._loaded = false;\n const options = extend({}, this.workerOptions);\n const data = this._data;\n if (typeof data === 'string') {\n options.request = this.map._requestManager.transformRequest(browser.resolveURL(data), ResourceType.Source);\n options.request.collectResourceTiming = this._collectResourceTiming;\n } else {\n options.data = JSON.stringify(data);\n }\n\n // target {this.type}.loadData rather than literally geojson.loadData,\n // so that other geojson-like source types can easily reuse this\n // implementation\n this.actor.send(`${this.type}.loadData`, options, (err, result) => {\n if (this._removed || (result && result.abandoned)) {\n return;\n }\n\n this._loaded = true;\n\n if (result && result.resourceTiming && result.resourceTiming[this.id])\n this._resourceTiming = result.resourceTiming[this.id].slice(0);\n // Any `loadData` calls that piled up while we were processing\n // this one will get coalesced into a single call when this\n // 'coalesce' message is processed.\n // We would self-send from the worker if we had access to its\n // message queue. Waiting instead for the 'coalesce' to round-trip\n // through the foreground just means we're throttling the worker\n // to run at a little less than full-throttle.\n this.actor.send(`${this.type}.coalesce`, {source: options.source}, null);\n callback(err);\n });\n }\n\n loaded(): boolean {\n return this._loaded;\n }\n\n loadTile(tile: Tile, callback: Callback) {\n const message = !tile.actor ? 'loadTile' : 'reloadTile';\n tile.actor = this.actor;\n const params = {\n type: this.type,\n uid: tile.uid,\n tileID: tile.tileID,\n zoom: tile.tileID.overscaledZ,\n maxZoom: this.maxzoom,\n tileSize: this.tileSize,\n source: this.id,\n pixelRatio: browser.devicePixelRatio,\n showCollisionBoxes: this.map.showCollisionBoxes,\n promoteId: this.promoteId\n };\n\n tile.request = this.actor.send(message, params, (err, data) => {\n delete tile.request;\n tile.unloadVectorData();\n\n if (tile.aborted) {\n return callback(null);\n }\n\n if (err) {\n return callback(err);\n }\n\n tile.loadVectorData(data, this.map.painter, message === 'reloadTile');\n\n return callback(null);\n });\n }\n\n abortTile(tile: Tile) {\n if (tile.request) {\n tile.request.cancel();\n delete tile.request;\n }\n tile.aborted = true;\n }\n\n unloadTile(tile: Tile) {\n tile.unloadVectorData();\n this.actor.send('removeTile', {uid: tile.uid, type: this.type, source: this.id});\n }\n\n onRemove() {\n this._removed = true;\n this.actor.send('removeSource', {type: this.type, source: this.id});\n }\n\n serialize() {\n return extend({}, this._options, {\n type: this.type,\n data: this._data\n });\n }\n\n hasTransition() {\n return false;\n }\n}\n\nexport default GeoJSONSource;\n","// @flow\n\nimport {CanonicalTileID} from './tile_id';\nimport {Event, ErrorEvent, Evented} from '../util/evented';\nimport {getImage, ResourceType} from '../util/ajax';\nimport EXTENT from '../data/extent';\nimport {RasterBoundsArray} from '../data/array_types';\nimport rasterBoundsAttributes from '../data/raster_bounds_attributes';\nimport SegmentVector from '../data/segment';\nimport Texture from '../render/texture';\nimport MercatorCoordinate from '../geo/mercator_coordinate';\n\nimport type {Source} from './source';\nimport type {CanvasSourceSpecification} from './canvas_source';\nimport type Map from '../ui/map';\nimport type Dispatcher from '../util/dispatcher';\nimport type Tile from './tile';\nimport type {Callback} from '../types/callback';\nimport type VertexBuffer from '../gl/vertex_buffer';\nimport type {\n ImageSourceSpecification,\n VideoSourceSpecification\n} from '../style-spec/types';\n\ntype Coordinates = [[number, number], [number, number], [number, number], [number, number]];\n\n/**\n * A data source containing an image.\n * (See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-image) for detailed documentation of options.)\n *\n * @example\n * // add to map\n * map.addSource('some id', {\n * type: 'image',\n * url: 'https://www.mapbox.com/images/foo.png',\n * coordinates: [\n * [-76.54, 39.18],\n * [-76.52, 39.18],\n * [-76.52, 39.17],\n * [-76.54, 39.17]\n * ]\n * });\n *\n * // update coordinates\n * var mySource = map.getSource('some id');\n * mySource.setCoordinates([\n * [-76.54335737228394, 39.18579907229748],\n * [-76.52803659439087, 39.1838364847587],\n * [-76.5295386314392, 39.17683392507606],\n * [-76.54520273208618, 39.17876344106642]\n * ]);\n *\n * // update url and coordinates simultaneously\n * mySource.updateImage({\n * url: 'https://www.mapbox.com/images/bar.png',\n * coordinates: [\n * [-76.54335737228394, 39.18579907229748],\n * [-76.52803659439087, 39.1838364847587],\n * [-76.5295386314392, 39.17683392507606],\n * [-76.54520273208618, 39.17876344106642]\n * ]\n * })\n *\n * map.removeSource('some id'); // remove\n * @see [Add an image](https://www.mapbox.com/mapbox-gl-js/example/image-on-a-map/)\n */\nclass ImageSource extends Evented implements Source {\n type: string;\n id: string;\n minzoom: number;\n maxzoom: number;\n tileSize: number;\n url: string;\n\n coordinates: Coordinates;\n tiles: {[_: string]: Tile};\n options: any;\n dispatcher: Dispatcher;\n map: Map;\n texture: Texture | null;\n image: HTMLImageElement | ImageBitmap;\n tileID: CanonicalTileID;\n _boundsArray: RasterBoundsArray;\n boundsBuffer: VertexBuffer;\n boundsSegments: SegmentVector;\n _loaded: boolean;\n\n /**\n * @private\n */\n constructor(id: string, options: ImageSourceSpecification | VideoSourceSpecification | CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n super();\n this.id = id;\n this.dispatcher = dispatcher;\n this.coordinates = options.coordinates;\n\n this.type = 'image';\n this.minzoom = 0;\n this.maxzoom = 22;\n this.tileSize = 512;\n this.tiles = {};\n this._loaded = false;\n\n this.setEventedParent(eventedParent);\n\n this.options = options;\n }\n\n load(newCoordinates?: Coordinates, successCallback?: () => void) {\n this._loaded = false;\n this.fire(new Event('dataloading', {dataType: 'source'}));\n\n this.url = this.options.url;\n\n getImage(this.map._requestManager.transformRequest(this.url, ResourceType.Image), (err, image) => {\n this._loaded = true;\n if (err) {\n this.fire(new ErrorEvent(err));\n } else if (image) {\n this.image = image;\n if (newCoordinates) {\n this.coordinates = newCoordinates;\n }\n if (successCallback) {\n successCallback();\n }\n this._finishLoading();\n }\n });\n }\n\n loaded(): boolean {\n return this._loaded;\n }\n\n /**\n * Updates the image URL and, optionally, the coordinates. To avoid having the image flash after changing,\n * set the `raster-fade-duration` paint property on the raster layer to 0.\n *\n * @param {Object} options Options object.\n * @param {string} [options.url] Required image URL.\n * @param {Array>} [options.coordinates] Four geographical coordinates,\n * represented as arrays of longitude and latitude numbers, which define the corners of the image.\n * The coordinates start at the top left corner of the image and proceed in clockwise order.\n * They do not have to represent a rectangle.\n * @returns {ImageSource} this\n */\n updateImage(options: {url: string, coordinates?: Coordinates}) {\n if (!this.image || !options.url) {\n return this;\n }\n this.options.url = options.url;\n this.load(options.coordinates, () => { this.texture = null; });\n return this;\n }\n\n _finishLoading() {\n if (this.map) {\n this.setCoordinates(this.coordinates);\n this.fire(new Event('data', {dataType: 'source', sourceDataType: 'metadata'}));\n }\n }\n\n onAdd(map: Map) {\n this.map = map;\n this.load();\n }\n\n /**\n * Sets the image's coordinates and re-renders the map.\n *\n * @param {Array>} coordinates Four geographical coordinates,\n * represented as arrays of longitude and latitude numbers, which define the corners of the image.\n * The coordinates start at the top left corner of the image and proceed in clockwise order.\n * They do not have to represent a rectangle.\n * @returns {ImageSource} this\n */\n setCoordinates(coordinates: Coordinates) {\n this.coordinates = coordinates;\n\n // Calculate which mercator tile is suitable for rendering the video in\n // and create a buffer with the corner coordinates. These coordinates\n // may be outside the tile, because raster tiles aren't clipped when rendering.\n\n // transform the geo coordinates into (zoom 0) tile space coordinates\n const cornerCoords = coordinates.map(MercatorCoordinate.fromLngLat);\n\n // Compute the coordinates of the tile we'll use to hold this image's\n // render data\n this.tileID = getCoordinatesCenterTileID(cornerCoords);\n\n // Constrain min/max zoom to our tile's zoom level in order to force\n // SourceCache to request this tile (no matter what the map's zoom\n // level)\n this.minzoom = this.maxzoom = this.tileID.z;\n\n // Transform the corner coordinates into the coordinate space of our\n // tile.\n const tileCoords = cornerCoords.map((coord) => this.tileID.getTilePoint(coord)._round());\n\n this._boundsArray = new RasterBoundsArray();\n this._boundsArray.emplaceBack(tileCoords[0].x, tileCoords[0].y, 0, 0);\n this._boundsArray.emplaceBack(tileCoords[1].x, tileCoords[1].y, EXTENT, 0);\n this._boundsArray.emplaceBack(tileCoords[3].x, tileCoords[3].y, 0, EXTENT);\n this._boundsArray.emplaceBack(tileCoords[2].x, tileCoords[2].y, EXTENT, EXTENT);\n\n if (this.boundsBuffer) {\n this.boundsBuffer.destroy();\n delete this.boundsBuffer;\n }\n\n this.fire(new Event('data', {dataType:'source', sourceDataType: 'content'}));\n return this;\n }\n\n prepare() {\n if (Object.keys(this.tiles).length === 0 || !this.image) {\n return;\n }\n\n const context = this.map.painter.context;\n const gl = context.gl;\n\n if (!this.boundsBuffer) {\n this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members);\n }\n\n if (!this.boundsSegments) {\n this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n }\n\n if (!this.texture) {\n this.texture = new Texture(context, this.image, gl.RGBA);\n this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n }\n\n for (const w in this.tiles) {\n const tile = this.tiles[w];\n if (tile.state !== 'loaded') {\n tile.state = 'loaded';\n tile.texture = this.texture;\n }\n }\n }\n\n loadTile(tile: Tile, callback: Callback) {\n // We have a single tile -- whoose coordinates are this.tileID -- that\n // covers the image we want to render. If that's the one being\n // requested, set it up with the image; otherwise, mark the tile as\n // `errored` to indicate that we have no data for it.\n // If the world wraps, we may have multiple \"wrapped\" copies of the\n // single tile.\n if (this.tileID && this.tileID.equals(tile.tileID.canonical)) {\n this.tiles[String(tile.tileID.wrap)] = tile;\n tile.buckets = {};\n callback(null);\n } else {\n tile.state = 'errored';\n callback(null);\n }\n }\n\n serialize(): Object {\n return {\n type: 'image',\n url: this.options.url,\n coordinates: this.coordinates\n };\n }\n\n hasTransition() {\n return false;\n }\n}\n\n/**\n * Given a list of coordinates, get their center as a coordinate.\n *\n * @returns centerpoint\n * @private\n */\nexport function getCoordinatesCenterTileID(coords: Array) {\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n\n for (const coord of coords) {\n minX = Math.min(minX, coord.x);\n minY = Math.min(minY, coord.y);\n maxX = Math.max(maxX, coord.x);\n maxY = Math.max(maxY, coord.y);\n }\n\n const dx = maxX - minX;\n const dy = maxY - minY;\n const dMax = Math.max(dx, dy);\n const zoom = Math.max(0, Math.floor(-Math.log(dMax) / Math.LN2));\n const tilesAtZoom = Math.pow(2, zoom);\n\n return new CanonicalTileID(\n zoom,\n Math.floor((minX + maxX) / 2 * tilesAtZoom),\n Math.floor((minY + maxY) / 2 * tilesAtZoom));\n}\n\nexport default ImageSource;\n","// @flow\n\nimport {getVideo, ResourceType} from '../util/ajax';\n\nimport ImageSource from './image_source';\nimport rasterBoundsAttributes from '../data/raster_bounds_attributes';\nimport SegmentVector from '../data/segment';\nimport Texture from '../render/texture';\nimport {ErrorEvent} from '../util/evented';\nimport ValidationError from '../style-spec/error/validation_error';\n\nimport type Map from '../ui/map';\nimport type Dispatcher from '../util/dispatcher';\nimport type {Evented} from '../util/evented';\nimport type {VideoSourceSpecification} from '../style-spec/types';\n\n/**\n * A data source containing video.\n * (See the [Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#sources-video) for detailed documentation of options.)\n *\n * @example\n * // add to map\n * map.addSource('some id', {\n * type: 'video',\n * url: [\n * 'https://www.mapbox.com/blog/assets/baltimore-smoke.mp4',\n * 'https://www.mapbox.com/blog/assets/baltimore-smoke.webm'\n * ],\n * coordinates: [\n * [-76.54, 39.18],\n * [-76.52, 39.18],\n * [-76.52, 39.17],\n * [-76.54, 39.17]\n * ]\n * });\n *\n * // update\n * var mySource = map.getSource('some id');\n * mySource.setCoordinates([\n * [-76.54335737228394, 39.18579907229748],\n * [-76.52803659439087, 39.1838364847587],\n * [-76.5295386314392, 39.17683392507606],\n * [-76.54520273208618, 39.17876344106642]\n * ]);\n *\n * map.removeSource('some id'); // remove\n * @see [Add a video](https://www.mapbox.com/mapbox-gl-js/example/video-on-a-map/)\n */\nclass VideoSource extends ImageSource {\n options: VideoSourceSpecification;\n urls: Array;\n video: HTMLVideoElement;\n roundZoom: boolean;\n\n /**\n * @private\n */\n constructor(id: string, options: VideoSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n super(id, options, dispatcher, eventedParent);\n this.roundZoom = true;\n this.type = 'video';\n this.options = options;\n }\n\n load() {\n this._loaded = false;\n const options = this.options;\n\n this.urls = [];\n for (const url of options.urls) {\n this.urls.push(this.map._requestManager.transformRequest(url, ResourceType.Source).url);\n }\n\n getVideo(this.urls, (err, video) => {\n this._loaded = true;\n if (err) {\n this.fire(new ErrorEvent(err));\n } else if (video) {\n this.video = video;\n this.video.loop = true;\n\n // Prevent the video from taking over the screen in iOS\n this.video.setAttribute('playsinline', '');\n\n // Start repainting when video starts playing. hasTransition() will then return\n // true to trigger additional frames as long as the videos continues playing.\n this.video.addEventListener('playing', () => {\n this.map.triggerRepaint();\n });\n\n if (this.map) {\n this.video.play();\n }\n\n this._finishLoading();\n }\n });\n }\n\n /**\n * Pauses the video.\n */\n pause() {\n if (this.video) {\n this.video.pause();\n }\n }\n\n /**\n * Plays the video.\n */\n play() {\n if (this.video) {\n this.video.play();\n }\n }\n\n /**\n * Sets playback to a timestamp, in seconds.\n * @private\n */\n seek(seconds: number) {\n if (this.video) {\n const seekableRange = this.video.seekable;\n if (seconds < seekableRange.start(0) || seconds > seekableRange.end(0)) {\n this.fire(new ErrorEvent(new ValidationError(`sources.${this.id}`, null, `Playback for this video can be set only between the ${seekableRange.start(0)} and ${seekableRange.end(0)}-second mark.`)));\n } else this.video.currentTime = seconds;\n }\n }\n\n /**\n * Returns the HTML `video` element.\n *\n * @returns {HTMLVideoElement} The HTML `video` element.\n */\n getVideo() {\n return this.video;\n }\n\n onAdd(map: Map) {\n if (this.map) return;\n this.map = map;\n this.load();\n if (this.video) {\n this.video.play();\n this.setCoordinates(this.coordinates);\n }\n }\n\n /**\n * Sets the video's coordinates and re-renders the map.\n *\n * @method setCoordinates\n * @instance\n * @memberof VideoSource\n * @returns {VideoSource} this\n */\n // setCoordinates inherited from ImageSource\n\n prepare() {\n if (Object.keys(this.tiles).length === 0 || this.video.readyState < 2) {\n return; // not enough data for current position\n }\n\n const context = this.map.painter.context;\n const gl = context.gl;\n\n if (!this.boundsBuffer) {\n this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members);\n }\n\n if (!this.boundsSegments) {\n this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n }\n\n if (!this.texture) {\n this.texture = new Texture(context, this.video, gl.RGBA);\n this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n } else if (!this.video.paused) {\n this.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, this.video);\n }\n\n for (const w in this.tiles) {\n const tile = this.tiles[w];\n if (tile.state !== 'loaded') {\n tile.state = 'loaded';\n tile.texture = this.texture;\n }\n }\n }\n\n serialize() {\n return {\n type: 'video',\n urls: this.urls,\n coordinates: this.coordinates\n };\n }\n\n hasTransition() {\n return this.video && !this.video.paused;\n }\n}\n\nexport default VideoSource;\n","// @flow\n\nimport ImageSource from './image_source';\n\nimport window from '../util/window';\nimport rasterBoundsAttributes from '../data/raster_bounds_attributes';\nimport SegmentVector from '../data/segment';\nimport Texture from '../render/texture';\nimport {ErrorEvent} from '../util/evented';\nimport ValidationError from '../style-spec/error/validation_error';\n\nimport type Map from '../ui/map';\nimport type Dispatcher from '../util/dispatcher';\nimport type {Evented} from '../util/evented';\n\nexport type CanvasSourceSpecification = {|\n \"type\": \"canvas\",\n \"coordinates\": [[number, number], [number, number], [number, number], [number, number]],\n \"animate\"?: boolean,\n \"canvas\": string | HTMLCanvasElement\n|};\n\n/**\n * Options to add a canvas source type to the map.\n *\n * @typedef {Object} CanvasSourceOptions\n * @property {string} type Source type. Must be `\"canvas\"`.\n * @property {string|HTMLCanvasElement} canvas Canvas source from which to read pixels. Can be a string representing the ID of the canvas element, or the `HTMLCanvasElement` itself.\n * @property {Array>} coordinates Four geographical coordinates denoting where to place the corners of the canvas, specified in `[longitude, latitude]` pairs.\n * @property {boolean} [animate=true] Whether the canvas source is animated. If the canvas is static (i.e. pixels do not need to be re-read on every frame), `animate` should be set to `false` to improve performance.\n */\n\n/**\n * A data source containing the contents of an HTML canvas. See {@link CanvasSourceOptions} for detailed documentation of options.\n *\n * @example\n * // add to map\n * map.addSource('some id', {\n * type: 'canvas',\n * canvas: 'idOfMyHTMLCanvas',\n * animate: true,\n * coordinates: [\n * [-76.54, 39.18],\n * [-76.52, 39.18],\n * [-76.52, 39.17],\n * [-76.54, 39.17]\n * ]\n * });\n *\n * // update\n * var mySource = map.getSource('some id');\n * mySource.setCoordinates([\n * [-76.54335737228394, 39.18579907229748],\n * [-76.52803659439087, 39.1838364847587],\n * [-76.5295386314392, 39.17683392507606],\n * [-76.54520273208618, 39.17876344106642]\n * ]);\n *\n * map.removeSource('some id'); // remove\n */\nclass CanvasSource extends ImageSource {\n options: CanvasSourceSpecification;\n animate: boolean;\n canvas: HTMLCanvasElement;\n width: number;\n height: number;\n play: () => void;\n pause: () => void;\n _playing: boolean;\n\n /**\n * @private\n */\n constructor(id: string, options: CanvasSourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n super(id, options, dispatcher, eventedParent);\n\n // We build in some validation here, since canvas sources aren't included in the style spec:\n if (!options.coordinates) {\n this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'missing required property \"coordinates\"')));\n } else if (!Array.isArray(options.coordinates) || options.coordinates.length !== 4 ||\n options.coordinates.some(c => !Array.isArray(c) || c.length !== 2 || c.some(l => typeof l !== 'number'))) {\n this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, '\"coordinates\" property must be an array of 4 longitude/latitude array pairs')));\n }\n\n if (options.animate && typeof options.animate !== 'boolean') {\n this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'optional \"animate\" property must be a boolean value')));\n }\n\n if (!options.canvas) {\n this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, 'missing required property \"canvas\"')));\n } else if (typeof options.canvas !== 'string' && !(options.canvas instanceof window.HTMLCanvasElement)) {\n this.fire(new ErrorEvent(new ValidationError(`sources.${id}`, null, '\"canvas\" must be either a string representing the ID of the canvas element from which to read, or an HTMLCanvasElement instance')));\n }\n\n this.options = options;\n this.animate = options.animate !== undefined ? options.animate : true;\n }\n\n /**\n * Enables animation. The image will be copied from the canvas to the map on each frame.\n * @method play\n * @instance\n * @memberof CanvasSource\n */\n\n /**\n * Disables animation. The map will display a static copy of the canvas image.\n * @method pause\n * @instance\n * @memberof CanvasSource\n */\n\n load() {\n this._loaded = true;\n if (!this.canvas) {\n this.canvas = (this.options.canvas instanceof window.HTMLCanvasElement) ?\n this.options.canvas :\n window.document.getElementById(this.options.canvas);\n }\n this.width = this.canvas.width;\n this.height = this.canvas.height;\n\n if (this._hasInvalidDimensions()) {\n this.fire(new ErrorEvent(new Error('Canvas dimensions cannot be less than or equal to zero.')));\n return;\n }\n\n this.play = function() {\n this._playing = true;\n this.map.triggerRepaint();\n };\n\n this.pause = function() {\n if (this._playing) {\n this.prepare();\n this._playing = false;\n }\n };\n\n this._finishLoading();\n }\n\n /**\n * Returns the HTML `canvas` element.\n *\n * @returns {HTMLCanvasElement} The HTML `canvas` element.\n */\n getCanvas() {\n return this.canvas;\n }\n\n onAdd(map: Map) {\n this.map = map;\n this.load();\n if (this.canvas) {\n if (this.animate) this.play();\n }\n }\n\n onRemove() {\n this.pause();\n }\n\n /**\n * Sets the canvas's coordinates and re-renders the map.\n *\n * @method setCoordinates\n * @instance\n * @memberof CanvasSource\n * @param {Array>} coordinates Four geographical coordinates,\n * represented as arrays of longitude and latitude numbers, which define the corners of the canvas.\n * The coordinates start at the top left corner of the canvas and proceed in clockwise order.\n * They do not have to represent a rectangle.\n * @returns {CanvasSource} this\n */\n // setCoordinates inherited from ImageSource\n\n prepare() {\n let resize = false;\n if (this.canvas.width !== this.width) {\n this.width = this.canvas.width;\n resize = true;\n }\n if (this.canvas.height !== this.height) {\n this.height = this.canvas.height;\n resize = true;\n }\n\n if (this._hasInvalidDimensions()) return;\n\n if (Object.keys(this.tiles).length === 0) return; // not enough data for current position\n\n const context = this.map.painter.context;\n const gl = context.gl;\n\n if (!this.boundsBuffer) {\n this.boundsBuffer = context.createVertexBuffer(this._boundsArray, rasterBoundsAttributes.members);\n }\n\n if (!this.boundsSegments) {\n this.boundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n }\n\n if (!this.texture) {\n this.texture = new Texture(context, this.canvas, gl.RGBA, {premultiply: true});\n } else if (resize || this._playing) {\n this.texture.update(this.canvas, {premultiply: true});\n }\n\n for (const w in this.tiles) {\n const tile = this.tiles[w];\n if (tile.state !== 'loaded') {\n tile.state = 'loaded';\n tile.texture = this.texture;\n }\n }\n }\n\n serialize(): Object {\n return {\n type: 'canvas',\n coordinates: this.coordinates\n };\n }\n\n hasTransition() {\n return this._playing;\n }\n\n _hasInvalidDimensions() {\n for (const x of [this.canvas.width, this.canvas.height]) {\n if (isNaN(x) || x <= 0) return true;\n }\n return false;\n }\n}\n\nexport default CanvasSource;\n","// @flow\n\nimport {bindAll} from '../util/util';\n\nimport type Dispatcher from '../util/dispatcher';\nimport type {Event, Evented} from '../util/evented';\nimport type Map from '../ui/map';\nimport type Tile from './tile';\nimport type {OverscaledTileID} from './tile_id';\nimport type {Callback} from '../types/callback';\nimport {CanonicalTileID} from './tile_id';\n\n/**\n * The `Source` interface must be implemented by each source type, including \"core\" types (`vector`, `raster`,\n * `video`, etc.) and all custom, third-party types.\n *\n * @private\n *\n * @param {string} id The id for the source. Must not be used by any existing source.\n * @param {Object} options Source options, specific to the source type (except for `options.type`, which is always\n * required).\n * @param {string} options.type The source type, matching the value of `name` used in {@link Style#addSourceType}.\n * @param {Dispatcher} dispatcher A {@link Dispatcher} instance, which can be used to send messages to the workers.\n *\n * @fires data with `{dataType: 'source', sourceDataType: 'metadata'}` to indicate that any necessary metadata\n * has been loaded so that it's okay to call `loadTile`; and with `{dataType: 'source', sourceDataType: 'content'}`\n * to indicate that the source data has changed, so that any current caches should be flushed.\n * @property {string} id The id for the source. Must match the id passed to the constructor.\n * @property {number} minzoom\n * @property {number} maxzoom\n * @property {boolean} isTileClipped `false` if tiles can be drawn outside their boundaries, `true` if they cannot.\n * @property {boolean} reparseOverscaled `true` if tiles should be sent back to the worker for each overzoomed zoom\n * level, `false` if not.\n * @property {boolean} roundZoom `true` if zoom levels are rounded to the nearest integer in the source data, `false`\n * if they are floor-ed to the nearest integer.\n */\nexport interface Source {\n +type: string;\n id: string;\n minzoom: number,\n maxzoom: number,\n tileSize: number,\n attribution?: string,\n\n roundZoom?: boolean,\n isTileClipped?: boolean,\n mapbox_logo?: boolean,\n tileID?: CanonicalTileID;\n reparseOverscaled?: boolean,\n vectorLayerIds?: Array,\n\n hasTransition(): boolean;\n loaded(): boolean;\n\n fire(event: Event): mixed;\n\n +onAdd?: (map: Map) => void;\n +onRemove?: (map: Map) => void;\n\n loadTile(tile: Tile, callback: Callback): void;\n +hasTile?: (tileID: OverscaledTileID) => boolean;\n +abortTile?: (tile: Tile, callback: Callback) => void;\n +unloadTile?: (tile: Tile, callback: Callback) => void;\n\n /**\n * @returns A plain (stringifiable) JS object representing the current state of the source.\n * Creating a source using the returned object as the `options` should result in a Source that is\n * equivalent to this one.\n * @private\n */\n serialize(): Object;\n\n +prepare?: () => void;\n}\n\ntype SourceStatics = {\n /*\n * An optional URL to a script which, when run by a Worker, registers a {@link WorkerSource}\n * implementation for this Source type by calling `self.registerWorkerSource(workerSource: WorkerSource)`.\n */\n workerSourceURL?: URL;\n};\n\nexport type SourceClass = Class & SourceStatics;\n\nimport vector from '../source/vector_tile_source';\nimport raster from '../source/raster_tile_source';\nimport rasterDem from '../source/raster_dem_tile_source';\nimport geojson from '../source/geojson_source';\nimport video from '../source/video_source';\nimport image from '../source/image_source';\nimport canvas from '../source/canvas_source';\n\nimport type {SourceSpecification} from '../style-spec/types';\n\nconst sourceTypes = {\n vector,\n raster,\n 'raster-dem': rasterDem,\n geojson,\n video,\n image,\n canvas\n};\n\n/*\n * Creates a tiled data source instance given an options object.\n *\n * @param id\n * @param {Object} source A source definition object compliant with\n * [`mapbox-gl-style-spec`](https://www.mapbox.com/mapbox-gl-style-spec/#sources) or, for a third-party source type,\n * with that type's requirements.\n * @param {Dispatcher} dispatcher\n * @returns {Source}\n */\nexport const create = function(id: string, specification: SourceSpecification, dispatcher: Dispatcher, eventedParent: Evented) {\n const source = new sourceTypes[specification.type](id, (specification: any), dispatcher, eventedParent);\n\n if (source.id !== id) {\n throw new Error(`Expected Source id to be ${id} instead of ${source.id}`);\n }\n\n bindAll(['load', 'abort', 'unload', 'serialize', 'prepare'], source);\n return source;\n};\n\nexport const getType = function (name: string) {\n return sourceTypes[name];\n};\n\nexport const setType = function (name: string, type: Class) {\n sourceTypes[name] = type;\n};\n\nexport interface Actor {\n send(type: string, data: Object, callback: Callback): void;\n}\n","// @flow\n\nimport type SourceCache from './source_cache';\nimport type StyleLayer from '../style/style_layer';\nimport type CollisionIndex from '../symbol/collision_index';\nimport type Transform from '../geo/transform';\nimport type {RetainedQueryData} from '../symbol/placement';\nimport type {FilterSpecification} from '../style-spec/types';\nimport assert from 'assert';\nimport {mat4} from 'gl-matrix';\n\n/*\n * Returns a matrix that can be used to convert from tile coordinates to viewport pixel coordinates.\n */\nfunction getPixelPosMatrix(transform, tileID) {\n const t = mat4.identity([]);\n mat4.translate(t, t, [1, 1, 0]);\n mat4.scale(t, t, [transform.width * 0.5, transform.height * 0.5, 1]);\n return mat4.multiply(t, t, transform.calculatePosMatrix(tileID.toUnwrapped()));\n}\n\nfunction queryIncludes3DLayer(layers?: Array, styleLayers: {[_: string]: StyleLayer}, sourceID: string) {\n if (layers) {\n for (const layerID of layers) {\n const layer = styleLayers[layerID];\n if (layer && layer.source === sourceID && layer.type === 'fill-extrusion') {\n return true;\n }\n }\n } else {\n for (const key in styleLayers) {\n const layer = styleLayers[key];\n if (layer.source === sourceID && layer.type === 'fill-extrusion') {\n return true;\n }\n }\n }\n return false;\n}\n\nexport function queryRenderedFeatures(sourceCache: SourceCache,\n styleLayers: {[_: string]: StyleLayer},\n serializedLayers: {[_: string]: Object},\n queryGeometry: Array,\n params: { filter: FilterSpecification, layers: Array, availableImages: Array },\n transform: Transform) {\n\n const has3DLayer = queryIncludes3DLayer(params && params.layers, styleLayers, sourceCache.id);\n const maxPitchScaleFactor = transform.maxPitchScaleFactor();\n const tilesIn = sourceCache.tilesIn(queryGeometry, maxPitchScaleFactor, has3DLayer);\n\n tilesIn.sort(sortTilesIn);\n const renderedFeatureLayers = [];\n for (const tileIn of tilesIn) {\n renderedFeatureLayers.push({\n wrappedTileID: tileIn.tileID.wrapped().key,\n queryResults: tileIn.tile.queryRenderedFeatures(\n styleLayers,\n serializedLayers,\n sourceCache._state,\n tileIn.queryGeometry,\n tileIn.cameraQueryGeometry,\n tileIn.scale,\n params,\n transform,\n maxPitchScaleFactor,\n getPixelPosMatrix(sourceCache.transform, tileIn.tileID))\n });\n }\n\n const result = mergeRenderedFeatureLayers(renderedFeatureLayers);\n\n // Merge state from SourceCache into the results\n for (const layerID in result) {\n result[layerID].forEach((featureWrapper) => {\n const feature = featureWrapper.feature;\n const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id);\n feature.source = feature.layer.source;\n if (feature.layer['source-layer']) {\n feature.sourceLayer = feature.layer['source-layer'];\n }\n feature.state = state;\n });\n }\n return result;\n}\n\nexport function queryRenderedSymbols(styleLayers: {[_: string]: StyleLayer},\n serializedLayers: {[_: string]: StyleLayer},\n sourceCaches: {[_: string]: SourceCache},\n queryGeometry: Array,\n params: { filter: FilterSpecification, layers: Array, availableImages: Array },\n collisionIndex: CollisionIndex,\n retainedQueryData: {[_: number]: RetainedQueryData}) {\n const result = {};\n const renderedSymbols = collisionIndex.queryRenderedSymbols(queryGeometry);\n const bucketQueryData = [];\n for (const bucketInstanceId of Object.keys(renderedSymbols).map(Number)) {\n bucketQueryData.push(retainedQueryData[bucketInstanceId]);\n }\n bucketQueryData.sort(sortTilesIn);\n\n for (const queryData of bucketQueryData) {\n const bucketSymbols = queryData.featureIndex.lookupSymbolFeatures(\n renderedSymbols[queryData.bucketInstanceId],\n serializedLayers,\n queryData.bucketIndex,\n queryData.sourceLayerIndex,\n params.filter,\n params.layers,\n params.availableImages,\n styleLayers);\n\n for (const layerID in bucketSymbols) {\n const resultFeatures = result[layerID] = result[layerID] || [];\n const layerSymbols = bucketSymbols[layerID];\n layerSymbols.sort((a, b) => {\n // Match topDownFeatureComparator from FeatureIndex, but using\n // most recent sorting of features from bucket.sortFeatures\n const featureSortOrder = queryData.featureSortOrder;\n if (featureSortOrder) {\n // queryRenderedSymbols documentation says we'll return features in\n // \"top-to-bottom\" rendering order (aka last-to-first).\n // Actually there can be multiple symbol instances per feature, so\n // we sort each feature based on the first matching symbol instance.\n const sortedA = featureSortOrder.indexOf(a.featureIndex);\n const sortedB = featureSortOrder.indexOf(b.featureIndex);\n assert(sortedA >= 0);\n assert(sortedB >= 0);\n return sortedB - sortedA;\n } else {\n // Bucket hasn't been re-sorted based on angle, so use the\n // reverse of the order the features appeared in the data.\n return b.featureIndex - a.featureIndex;\n }\n });\n for (const symbolFeature of layerSymbols) {\n resultFeatures.push(symbolFeature);\n }\n }\n }\n\n // Merge state from SourceCache into the results\n for (const layerName in result) {\n result[layerName].forEach((featureWrapper) => {\n const feature = featureWrapper.feature;\n const layer = styleLayers[layerName];\n const sourceCache = sourceCaches[layer.source];\n const state = sourceCache.getFeatureState(feature.layer['source-layer'], feature.id);\n feature.source = feature.layer.source;\n if (feature.layer['source-layer']) {\n feature.sourceLayer = feature.layer['source-layer'];\n }\n feature.state = state;\n });\n }\n return result;\n}\n\nexport function querySourceFeatures(sourceCache: SourceCache, params: any) {\n const tiles = sourceCache.getRenderableIds().map((id) => {\n return sourceCache.getTileByID(id);\n });\n\n const result = [];\n\n const dataTiles = {};\n for (let i = 0; i < tiles.length; i++) {\n const tile = tiles[i];\n const dataID = tile.tileID.canonical.key;\n if (!dataTiles[dataID]) {\n dataTiles[dataID] = true;\n tile.querySourceFeatures(result, params);\n }\n }\n\n return result;\n}\n\nfunction sortTilesIn(a, b) {\n const idA = a.tileID;\n const idB = b.tileID;\n return (idA.overscaledZ - idB.overscaledZ) || (idA.canonical.y - idB.canonical.y) || (idA.wrap - idB.wrap) || (idA.canonical.x - idB.canonical.x);\n}\n\nfunction mergeRenderedFeatureLayers(tiles) {\n // Merge results from all tiles, but if two tiles share the same\n // wrapped ID, don't duplicate features between the two tiles\n const result = {};\n const wrappedIDLayerMap = {};\n for (const tile of tiles) {\n const queryResults = tile.queryResults;\n const wrappedID = tile.wrappedTileID;\n const wrappedIDLayers = wrappedIDLayerMap[wrappedID] = wrappedIDLayerMap[wrappedID] || {};\n for (const layerID in queryResults) {\n const tileFeatures = queryResults[layerID];\n const wrappedIDFeatures = wrappedIDLayers[layerID] = wrappedIDLayers[layerID] || {};\n const resultFeatures = result[layerID] = result[layerID] || [];\n for (const tileFeature of tileFeatures) {\n if (!wrappedIDFeatures[tileFeature.featureIndex]) {\n wrappedIDFeatures[tileFeature.featureIndex] = true;\n resultFeatures.push(tileFeature);\n }\n }\n }\n }\n return result;\n}\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","// @flow\n\nimport {extend} from '../util/util';\nimport Tile from './tile';\nimport type {FeatureState} from '../style-spec/expression';\n\nexport type FeatureStates = {[feature_id: string]: FeatureState};\nexport type LayerFeatureStates = {[layer: string]: FeatureStates};\n\n/**\n * SourceFeatureState manages the state and pending changes\n * to features in a source, separated by source layer.\n * stateChanges and deletedStates batch all changes to the tile (updates and removes, respectively)\n * between coalesce() events. addFeatureState() and removeFeatureState() also update their counterpart's\n * list of changes, such that coalesce() can apply the proper state changes while agnostic to the order of operations.\n * In deletedStates, all null's denote complete removal of state at that scope\n * @private\n*/\nclass SourceFeatureState {\n state: LayerFeatureStates;\n stateChanges: LayerFeatureStates;\n deletedStates: {};\n\n constructor() {\n this.state = {};\n this.stateChanges = {};\n this.deletedStates = {};\n }\n\n updateState(sourceLayer: string, featureId: number | string, newState: Object) {\n const feature = String(featureId);\n this.stateChanges[sourceLayer] = this.stateChanges[sourceLayer] || {};\n this.stateChanges[sourceLayer][feature] = this.stateChanges[sourceLayer][feature] || {};\n extend(this.stateChanges[sourceLayer][feature], newState);\n\n if (this.deletedStates[sourceLayer] === null) {\n this.deletedStates[sourceLayer] = {};\n for (const ft in this.state[sourceLayer]) {\n if (ft !== feature) this.deletedStates[sourceLayer][ft] = null;\n }\n } else {\n const featureDeletionQueued = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] === null;\n if (featureDeletionQueued) {\n this.deletedStates[sourceLayer][feature] = {};\n for (const prop in this.state[sourceLayer][feature]) {\n if (!newState[prop]) this.deletedStates[sourceLayer][feature][prop] = null;\n }\n } else {\n for (const key in newState) {\n const deletionInQueue = this.deletedStates[sourceLayer] && this.deletedStates[sourceLayer][feature] && this.deletedStates[sourceLayer][feature][key] === null;\n if (deletionInQueue) delete this.deletedStates[sourceLayer][feature][key];\n }\n }\n }\n }\n\n removeFeatureState(sourceLayer: string, featureId?: number | string, key?: string) {\n const sourceLayerDeleted = this.deletedStates[sourceLayer] === null;\n if (sourceLayerDeleted) return;\n\n const feature = String(featureId);\n\n this.deletedStates[sourceLayer] = this.deletedStates[sourceLayer] || {};\n\n if (key && featureId !== undefined) {\n if (this.deletedStates[sourceLayer][feature] !== null) {\n this.deletedStates[sourceLayer][feature] = this.deletedStates[sourceLayer][feature] || {};\n this.deletedStates[sourceLayer][feature][key] = null;\n }\n } else if (featureId !== undefined) {\n const updateInQueue = this.stateChanges[sourceLayer] && this.stateChanges[sourceLayer][feature];\n if (updateInQueue) {\n this.deletedStates[sourceLayer][feature] = {};\n for (key in this.stateChanges[sourceLayer][feature]) this.deletedStates[sourceLayer][feature][key] = null;\n\n } else {\n this.deletedStates[sourceLayer][feature] = null;\n }\n } else {\n this.deletedStates[sourceLayer] = null;\n }\n\n }\n\n getState(sourceLayer: string, featureId: number | string) {\n const feature = String(featureId);\n const base = this.state[sourceLayer] || {};\n const changes = this.stateChanges[sourceLayer] || {};\n\n const reconciledState = extend({}, base[feature], changes[feature]);\n\n //return empty object if the whole source layer is awaiting deletion\n if (this.deletedStates[sourceLayer] === null) return {};\n else if (this.deletedStates[sourceLayer]) {\n const featureDeletions = this.deletedStates[sourceLayer][featureId];\n if (featureDeletions === null) return {};\n for (const prop in featureDeletions) delete reconciledState[prop];\n }\n return reconciledState;\n }\n\n initializeTileState(tile: Tile, painter: any) {\n tile.setFeatureState(this.state, painter);\n }\n\n coalesceChanges(tiles: {[_: any]: Tile}, painter: any) {\n //track changes with full state objects, but only for features that got modified\n const featuresChanged: LayerFeatureStates = {};\n\n for (const sourceLayer in this.stateChanges) {\n this.state[sourceLayer] = this.state[sourceLayer] || {};\n const layerStates = {};\n for (const feature in this.stateChanges[sourceLayer]) {\n if (!this.state[sourceLayer][feature]) this.state[sourceLayer][feature] = {};\n extend(this.state[sourceLayer][feature], this.stateChanges[sourceLayer][feature]);\n layerStates[feature] = this.state[sourceLayer][feature];\n }\n featuresChanged[sourceLayer] = layerStates;\n }\n\n for (const sourceLayer in this.deletedStates) {\n this.state[sourceLayer] = this.state[sourceLayer] || {};\n const layerStates = {};\n\n if (this.deletedStates[sourceLayer] === null) {\n for (const ft in this.state[sourceLayer]) {\n layerStates[ft] = {};\n this.state[sourceLayer][ft] = {};\n }\n } else {\n for (const feature in this.deletedStates[sourceLayer]) {\n const deleteWholeFeatureState = this.deletedStates[sourceLayer][feature] === null;\n if (deleteWholeFeatureState) this.state[sourceLayer][feature] = {};\n else {\n for (const key of Object.keys(this.deletedStates[sourceLayer][feature])) {\n delete this.state[sourceLayer][feature][key];\n }\n }\n layerStates[feature] = this.state[sourceLayer][feature];\n }\n }\n\n featuresChanged[sourceLayer] = featuresChanged[sourceLayer] || {};\n extend(featuresChanged[sourceLayer], layerStates);\n }\n\n this.stateChanges = {};\n this.deletedStates = {};\n\n if (Object.keys(featuresChanged).length === 0) return;\n\n for (const id in tiles) {\n const tile = tiles[id];\n tile.setFeatureState(featuresChanged, painter);\n }\n }\n}\n\nexport default SourceFeatureState;\n","// @flow\n\nimport 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 {uniqueId, parseCacheControl} from '../util/util';\nimport {deserialize as deserializeBucket} from '../data/bucket';\nimport FeatureIndex from '../data/feature_index';\nimport GeoJSONFeature from '../util/vectortile_to_geojson';\nimport featureFilter from '../style-spec/feature_filter';\nimport SymbolBucket from '../data/bucket/symbol_bucket';\nimport {CollisionBoxArray} from '../data/array_types';\nimport Texture from '../render/texture';\nimport browser from '../util/browser';\nimport toEvaluationFeature from '../data/evaluation_feature';\nimport EvaluationParameters from '../style/evaluation_parameters';\nimport SourceFeatureState from '../source/source_state';\nimport {lazyLoadRTLTextPlugin} from './rtl_text_plugin';\n\nconst CLOCK_SKEW_RETRY_TIMEOUT = 30000;\n\nimport type {Bucket} from '../data/bucket';\nimport type StyleLayer from '../style/style_layer';\nimport type {WorkerTileResult} from './worker_source';\nimport type Actor from '../util/actor';\nimport type DEMData from '../data/dem_data';\nimport type {AlphaImage} from '../util/image';\nimport type ImageAtlas from '../render/image_atlas';\nimport type ImageManager from '../render/image_manager';\nimport type Context from '../gl/context';\nimport type {OverscaledTileID} from './tile_id';\nimport type Framebuffer from '../gl/framebuffer';\nimport type Transform from '../geo/transform';\nimport type {LayerFeatureStates} from './source_state';\nimport type {Cancelable} from '../types/cancelable';\nimport type {FilterSpecification} from '../style-spec/types';\n\nexport type TileState =\n | 'loading' // Tile data is in the process of loading.\n | 'loaded' // Tile data has been loaded. Tile can be rendered.\n | 'reloading' // Tile data has been loaded and is being updated. Tile can be rendered.\n | 'unloaded' // Tile data has been deleted.\n | 'errored' // Tile data was not loaded because of an error.\n | 'expired'; /* Tile data was previously loaded, but has expired per its\n * HTTP headers and is in the process of refreshing. */\n\n/**\n * A tile object is the combination of a Coordinate, which defines\n * its place, as well as a unique ID and data tracking for its content\n *\n * @private\n */\nclass Tile {\n tileID: OverscaledTileID;\n uid: number;\n uses: number;\n tileSize: number;\n buckets: {[_: string]: Bucket};\n latestFeatureIndex: ?FeatureIndex;\n latestRawTileData: ?ArrayBuffer;\n imageAtlas: ?ImageAtlas;\n imageAtlasTexture: Texture;\n glyphAtlasImage: ?AlphaImage;\n glyphAtlasTexture: Texture;\n expirationTime: any;\n expiredRequestCount: number;\n state: TileState;\n timeAdded: any;\n fadeEndTime: any;\n collisionBoxArray: ?CollisionBoxArray;\n redoWhenDone: boolean;\n showCollisionBoxes: boolean;\n placementSource: any;\n actor: ?Actor;\n vtLayers: {[_: string]: VectorTileLayer};\n\n neighboringTiles: ?Object;\n dem: ?DEMData;\n aborted: ?boolean;\n needsHillshadePrepare: ?boolean;\n request: ?Cancelable;\n texture: any;\n fbo: ?Framebuffer;\n demTexture: ?Texture;\n refreshedUponExpiration: boolean;\n reloadCallback: any;\n resourceTiming: ?Array;\n queryPadding: number;\n\n symbolFadeHoldUntil: ?number;\n hasSymbolBuckets: boolean;\n hasRTLText: boolean;\n dependencies: Object;\n\n /**\n * @param {OverscaledTileID} tileID\n * @param size\n * @private\n */\n constructor(tileID: OverscaledTileID, size: number) {\n this.tileID = tileID;\n this.uid = uniqueId();\n this.uses = 0;\n this.tileSize = size;\n this.buckets = {};\n this.expirationTime = null;\n this.queryPadding = 0;\n this.hasSymbolBuckets = false;\n this.hasRTLText = false;\n this.dependencies = {};\n\n // Counts the number of times a response was already expired when\n // received. We're using this to add a delay when making a new request\n // so we don't have to keep retrying immediately in case of a server\n // serving expired tiles.\n this.expiredRequestCount = 0;\n\n this.state = 'loading';\n }\n\n registerFadeDuration(duration: number) {\n const fadeEndTime = duration + this.timeAdded;\n if (fadeEndTime < browser.now()) return;\n if (this.fadeEndTime && fadeEndTime < this.fadeEndTime) return;\n\n this.fadeEndTime = fadeEndTime;\n }\n\n wasRequested() {\n return this.state === 'errored' || this.state === 'loaded' || this.state === 'reloading';\n }\n\n /**\n * Given a data object with a 'buffers' property, load it into\n * this tile's elementGroups and buffers properties and set loaded\n * to true. If the data is null, like in the case of an empty\n * GeoJSON tile, no-op but still set loaded to true.\n * @param {Object} data\n * @param painter\n * @returns {undefined}\n * @private\n */\n loadVectorData(data: WorkerTileResult, painter: any, justReloaded: ?boolean) {\n if (this.hasData()) {\n this.unloadVectorData();\n }\n\n this.state = 'loaded';\n\n // empty GeoJSON tile\n if (!data) {\n this.collisionBoxArray = new CollisionBoxArray();\n return;\n }\n\n if (data.featureIndex) {\n this.latestFeatureIndex = data.featureIndex;\n if (data.rawTileData) {\n // Only vector tiles have rawTileData, and they won't update it for\n // 'reloadTile'\n this.latestRawTileData = data.rawTileData;\n this.latestFeatureIndex.rawTileData = data.rawTileData;\n } else if (this.latestRawTileData) {\n // If rawTileData hasn't updated, hold onto a pointer to the last\n // one we received\n this.latestFeatureIndex.rawTileData = this.latestRawTileData;\n }\n }\n this.collisionBoxArray = data.collisionBoxArray;\n this.buckets = deserializeBucket(data.buckets, painter.style);\n\n this.hasSymbolBuckets = false;\n for (const id in this.buckets) {\n const bucket = this.buckets[id];\n if (bucket instanceof SymbolBucket) {\n this.hasSymbolBuckets = true;\n if (justReloaded) {\n bucket.justReloaded = true;\n } else {\n break;\n }\n }\n }\n\n this.hasRTLText = false;\n if (this.hasSymbolBuckets) {\n for (const id in this.buckets) {\n const bucket = this.buckets[id];\n if (bucket instanceof SymbolBucket) {\n if (bucket.hasRTLText) {\n this.hasRTLText = true;\n lazyLoadRTLTextPlugin();\n break;\n }\n }\n }\n }\n\n this.queryPadding = 0;\n for (const id in this.buckets) {\n const bucket = this.buckets[id];\n this.queryPadding = Math.max(this.queryPadding, painter.style.getLayer(id).queryRadius(bucket));\n }\n\n if (data.imageAtlas) {\n this.imageAtlas = data.imageAtlas;\n }\n if (data.glyphAtlasImage) {\n this.glyphAtlasImage = data.glyphAtlasImage;\n }\n }\n\n /**\n * Release any data or WebGL resources referenced by this tile.\n * @returns {undefined}\n * @private\n */\n unloadVectorData() {\n for (const id in this.buckets) {\n this.buckets[id].destroy();\n }\n this.buckets = {};\n\n if (this.imageAtlasTexture) {\n this.imageAtlasTexture.destroy();\n }\n\n if (this.imageAtlas) {\n this.imageAtlas = null;\n }\n\n if (this.glyphAtlasTexture) {\n this.glyphAtlasTexture.destroy();\n }\n\n this.latestFeatureIndex = null;\n this.state = 'unloaded';\n }\n\n getBucket(layer: StyleLayer) {\n return this.buckets[layer.id];\n }\n\n upload(context: Context) {\n for (const id in this.buckets) {\n const bucket = this.buckets[id];\n if (bucket.uploadPending()) {\n bucket.upload(context);\n }\n }\n\n const gl = context.gl;\n if (this.imageAtlas && !this.imageAtlas.uploaded) {\n this.imageAtlasTexture = new Texture(context, this.imageAtlas.image, gl.RGBA);\n this.imageAtlas.uploaded = true;\n }\n\n if (this.glyphAtlasImage) {\n this.glyphAtlasTexture = new Texture(context, this.glyphAtlasImage, gl.ALPHA);\n this.glyphAtlasImage = null;\n }\n }\n\n prepare(imageManager: ImageManager) {\n if (this.imageAtlas) {\n this.imageAtlas.patchUpdatedImages(imageManager, this.imageAtlasTexture);\n }\n }\n\n // Queries non-symbol features rendered for this tile.\n // Symbol features are queried globally\n queryRenderedFeatures(layers: {[_: string]: StyleLayer},\n serializedLayers: {[string]: Object},\n sourceFeatureState: SourceFeatureState,\n queryGeometry: Array,\n cameraQueryGeometry: Array,\n scale: number,\n params: { filter: FilterSpecification, layers: Array, availableImages: Array },\n transform: Transform,\n maxPitchScaleFactor: number,\n pixelPosMatrix: Float32Array): {[_: string]: Array<{ featureIndex: number, feature: GeoJSONFeature }>} {\n if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData)\n return {};\n\n return this.latestFeatureIndex.query({\n queryGeometry,\n cameraQueryGeometry,\n scale,\n tileSize: this.tileSize,\n pixelPosMatrix,\n transform,\n params,\n queryPadding: this.queryPadding * maxPitchScaleFactor\n }, layers, serializedLayers, sourceFeatureState);\n }\n\n querySourceFeatures(result: Array, params: any) {\n const featureIndex = this.latestFeatureIndex;\n if (!featureIndex || !featureIndex.rawTileData) return;\n\n const vtLayers = featureIndex.loadVTLayers();\n\n const sourceLayer = params ? params.sourceLayer : '';\n const layer = vtLayers._geojsonTileLayer || vtLayers[sourceLayer];\n\n if (!layer) return;\n\n const filter = featureFilter(params && params.filter);\n const {z, x, y} = this.tileID.canonical;\n const coord = {z, x, y};\n\n for (let i = 0; i < layer.length; i++) {\n const feature = layer.feature(i);\n if (filter.needGeometry) {\n const evaluationFeature = toEvaluationFeature(feature, true);\n if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), evaluationFeature, this.tileID.canonical)) continue;\n } else if (!filter.filter(new EvaluationParameters(this.tileID.overscaledZ), feature)) {\n continue;\n }\n const id = featureIndex.getId(feature, sourceLayer);\n const geojsonFeature = new GeoJSONFeature(feature, z, x, y, id);\n (geojsonFeature: any).tile = coord;\n result.push(geojsonFeature);\n }\n }\n\n hasData() {\n return this.state === 'loaded' || this.state === 'reloading' || this.state === 'expired';\n }\n\n patternsLoaded() {\n return this.imageAtlas && !!Object.keys(this.imageAtlas.patternPositions).length;\n }\n\n setExpiryData(data: any) {\n const prior = this.expirationTime;\n\n if (data.cacheControl) {\n const parsedCC = parseCacheControl(data.cacheControl);\n if (parsedCC['max-age']) this.expirationTime = Date.now() + parsedCC['max-age'] * 1000;\n } else if (data.expires) {\n this.expirationTime = new Date(data.expires).getTime();\n }\n\n if (this.expirationTime) {\n const now = Date.now();\n let isExpired = false;\n\n if (this.expirationTime > now) {\n isExpired = false;\n } else if (!prior) {\n isExpired = true;\n } else if (this.expirationTime < prior) {\n // Expiring date is going backwards:\n // fall back to exponential backoff\n isExpired = true;\n\n } else {\n const delta = this.expirationTime - prior;\n\n if (!delta) {\n // Server is serving the same expired resource over and over: fall\n // back to exponential backoff.\n isExpired = true;\n\n } else {\n // Assume that either the client or the server clock is wrong and\n // try to interpolate a valid expiration date (from the client POV)\n // observing a minimum timeout.\n this.expirationTime = now + Math.max(delta, CLOCK_SKEW_RETRY_TIMEOUT);\n\n }\n }\n\n if (isExpired) {\n this.expiredRequestCount++;\n this.state = 'expired';\n } else {\n this.expiredRequestCount = 0;\n }\n }\n }\n\n getExpiryTimeout() {\n if (this.expirationTime) {\n if (this.expiredRequestCount) {\n return 1000 * (1 << Math.min(this.expiredRequestCount - 1, 31));\n } else {\n // Max value for `setTimeout` implementations is a 32 bit integer; cap this accordingly\n return Math.min(this.expirationTime - new Date().getTime(), Math.pow(2, 31) - 1);\n }\n }\n }\n\n setFeatureState(states: LayerFeatureStates, painter: any) {\n if (!this.latestFeatureIndex ||\n !this.latestFeatureIndex.rawTileData ||\n Object.keys(states).length === 0) {\n return;\n }\n\n const vtLayers = this.latestFeatureIndex.loadVTLayers();\n\n for (const id in this.buckets) {\n if (!painter.style.hasLayer(id)) continue;\n\n const bucket = this.buckets[id];\n // Buckets are grouped by common source-layer\n const sourceLayerId = bucket.layers[0]['sourceLayer'] || '_geojsonTileLayer';\n const sourceLayer = vtLayers[sourceLayerId];\n const sourceLayerStates = states[sourceLayerId];\n if (!sourceLayer || !sourceLayerStates || Object.keys(sourceLayerStates).length === 0) continue;\n\n bucket.update(sourceLayerStates, sourceLayer, this.imageAtlas && this.imageAtlas.patternPositions || {});\n const layer = painter && painter.style && painter.style.getLayer(id);\n if (layer) {\n this.queryPadding = Math.max(this.queryPadding, layer.queryRadius(bucket));\n }\n }\n }\n\n holdingForFade(): boolean {\n return this.symbolFadeHoldUntil !== undefined;\n }\n\n symbolFadeFinished(): boolean {\n return !this.symbolFadeHoldUntil || this.symbolFadeHoldUntil < browser.now();\n }\n\n clearFadeHold() {\n this.symbolFadeHoldUntil = undefined;\n }\n\n setHoldDuration(duration: number) {\n this.symbolFadeHoldUntil = browser.now() + duration;\n }\n\n setDependencies(namespace: string, dependencies: Array) {\n const index = {};\n for (const dep of dependencies) {\n index[dep] = true;\n }\n this.dependencies[namespace] = index;\n }\n\n hasDependency(namespaces: Array, keys: Array) {\n for (const namespace of namespaces) {\n const dependencies = this.dependencies[namespace];\n if (dependencies) {\n for (const key of keys) {\n if (dependencies[key]) {\n return true;\n }\n }\n }\n }\n return false;\n }\n}\n\nexport default Tile;\n","// @flow\n\nimport type {CollisionBoxArray} from './array_types';\nimport type Style from '../style/style';\nimport type {TypedStyleLayer} from '../style/style_layer/typed_style_layer';\nimport type FeatureIndex from './feature_index';\nimport type Context from '../gl/context';\nimport type {FeatureStates} from '../source/source_state';\nimport type {ImagePosition} from '../render/image_atlas';\nimport type {CanonicalTileID} from '../source/tile_id';\n\nexport type BucketParameters = {\n index: number,\n layers: Array,\n zoom: number,\n pixelRatio: number,\n overscaling: number,\n collisionBoxArray: CollisionBoxArray,\n sourceLayerIndex: number,\n sourceID: string\n}\n\nexport type PopulateParameters = {\n featureIndex: FeatureIndex,\n iconDependencies: {},\n patternDependencies: {},\n glyphDependencies: {},\n availableImages: Array\n}\n\nexport type IndexedFeature = {\n feature: VectorTileFeature,\n id: number | string,\n index: number,\n sourceLayerIndex: number,\n}\n\nexport type BucketFeature = {|\n index: number,\n sourceLayerIndex: number,\n geometry: Array>,\n properties: Object,\n type: 1 | 2 | 3,\n id?: any,\n +patterns: {[_: string]: {\"min\": string, \"mid\": string, \"max\": string}},\n sortKey?: number\n|};\n\n/**\n * The `Bucket` interface is the single point of knowledge about turning vector\n * tiles into WebGL buffers.\n *\n * `Bucket` is an abstract interface. An implementation exists for each style layer type.\n * Create a bucket via the `StyleLayer#createBucket` method.\n *\n * The concrete bucket types, using layout options from the style layer,\n * transform feature geometries into vertex and index data for use by the\n * vertex shader. They also (via `ProgramConfiguration`) use feature\n * properties and the zoom level to populate the attributes needed for\n * data-driven styling.\n *\n * Buckets are designed to be built on a worker thread and then serialized and\n * transferred back to the main thread for rendering. On the worker side, a\n * bucket's vertex, index, and attribute data is stored in `bucket.arrays:\n * ArrayGroup`. When a bucket's data is serialized and sent back to the main\n * thread, is gets deserialized (using `new Bucket(serializedBucketData)`, with\n * the array data now stored in `bucket.buffers: BufferGroup`. BufferGroups\n * hold the same data as ArrayGroups, but are tuned for consumption by WebGL.\n *\n * @private\n */\nexport interface Bucket {\n layerIds: Array;\n hasPattern: boolean;\n +layers: Array;\n +stateDependentLayers: Array;\n +stateDependentLayerIds: Array;\n populate(features: Array, options: PopulateParameters, canonical: CanonicalTileID): void;\n update(states: FeatureStates, vtLayer: VectorTileLayer, imagePositions: {[_: string]: ImagePosition}): void;\n isEmpty(): boolean;\n\n upload(context: Context): void;\n uploadPending(): boolean;\n\n /**\n * Release the WebGL resources associated with the buffers. Note that because\n * buckets are shared between layers having the same layout properties, they\n * must be destroyed in groups (all buckets for a tile, or all symbol buckets).\n *\n * @private\n */\n destroy(): void;\n}\n\nexport function deserialize(input: Array, style: Style): {[_: string]: Bucket} {\n const output = {};\n\n // Guard against the case where the map's style has been set to null while\n // this bucket has been parsing.\n if (!style) return output;\n\n for (const bucket of input) {\n const layers = bucket.layerIds\n .map((id) => style.getLayer(id))\n .filter(Boolean);\n\n if (layers.length === 0) {\n continue;\n }\n\n // look up StyleLayer objects from layer ids (since we don't\n // want to waste time serializing/copying them from the worker)\n (bucket: any).layers = layers;\n if ((bucket: any).stateDependentLayerIds) {\n (bucket: any).stateDependentLayers = (bucket: any).stateDependentLayerIds.map((lId) => layers.filter((l) => l.id === lId)[0]);\n }\n for (const layer of layers) {\n output[layer.id] = bucket;\n }\n }\n\n return output;\n}\n","// @flow\n\nimport {OverscaledTileID} from './tile_id';\nimport type Tile from './tile';\n\n/**\n * A [least-recently-used cache](http://en.wikipedia.org/wiki/Cache_algorithms)\n * with hash lookup made possible by keeping a list of keys in parallel to\n * an array of dictionary of values\n *\n * @private\n */\nclass TileCache {\n max: number;\n data: {[key: string]: Array<{ value: Tile, timeout: ?TimeoutID}>};\n order: Array;\n onRemove: (element: Tile) => void;\n /**\n * @param {number} max number of permitted values\n * @param {Function} onRemove callback called with items when they expire\n */\n constructor(max: number, onRemove: (element: Tile) => void) {\n this.max = max;\n this.onRemove = onRemove;\n this.reset();\n }\n\n /**\n * Clear the cache\n *\n * @returns {TileCache} this cache\n * @private\n */\n reset() {\n for (const key in this.data) {\n for (const removedData of this.data[key]) {\n if (removedData.timeout) clearTimeout(removedData.timeout);\n this.onRemove(removedData.value);\n }\n }\n\n this.data = {};\n this.order = [];\n\n return this;\n }\n\n /**\n * Add a key, value combination to the cache, trimming its size if this pushes\n * it over max length.\n *\n * @param {OverscaledTileID} tileID lookup key for the item\n * @param {*} data any value\n *\n * @returns {TileCache} this cache\n * @private\n */\n add(tileID: OverscaledTileID, data: Tile, expiryTimeout: number | void) {\n const key = tileID.wrapped().key;\n if (this.data[key] === undefined) {\n this.data[key] = [];\n }\n\n const dataWrapper = {\n value: data,\n timeout: undefined\n };\n\n if (expiryTimeout !== undefined) {\n dataWrapper.timeout = setTimeout(() => {\n this.remove(tileID, dataWrapper);\n }, expiryTimeout);\n }\n\n this.data[key].push(dataWrapper);\n this.order.push(key);\n\n if (this.order.length > this.max) {\n const removedData = this._getAndRemoveByKey(this.order[0]);\n if (removedData) this.onRemove(removedData);\n }\n\n return this;\n }\n\n /**\n * Determine whether the value attached to `key` is present\n *\n * @param {OverscaledTileID} tileID the key to be looked-up\n * @returns {boolean} whether the cache has this value\n * @private\n */\n has(tileID: OverscaledTileID): boolean {\n return tileID.wrapped().key in this.data;\n }\n\n /**\n * Get the value attached to a specific key and remove data from cache.\n * If the key is not found, returns `null`\n *\n * @param {OverscaledTileID} tileID the key to look up\n * @returns {*} the data, or null if it isn't found\n * @private\n */\n getAndRemove(tileID: OverscaledTileID): ?Tile {\n if (!this.has(tileID)) { return null; }\n return this._getAndRemoveByKey(tileID.wrapped().key);\n }\n\n /*\n * Get and remove the value with the specified key.\n */\n _getAndRemoveByKey(key: string): ?Tile {\n const data = this.data[key].shift();\n if (data.timeout) clearTimeout(data.timeout);\n\n if (this.data[key].length === 0) {\n delete this.data[key];\n }\n this.order.splice(this.order.indexOf(key), 1);\n\n return data.value;\n }\n\n /*\n * Get the value with the specified (wrapped tile) key.\n */\n getByKey(key: string): ?Tile {\n const data = this.data[key];\n return data ? data[0].value : null;\n }\n\n /**\n * Get the value attached to a specific key without removing data\n * from the cache. If the key is not found, returns `null`\n *\n * @param {OverscaledTileID} tileID the key to look up\n * @returns {*} the data, or null if it isn't found\n * @private\n */\n get(tileID: OverscaledTileID): ?Tile {\n if (!this.has(tileID)) { return null; }\n\n const data = this.data[tileID.wrapped().key][0];\n return data.value;\n }\n\n /**\n * Remove a key/value combination from the cache.\n *\n * @param {OverscaledTileID} tileID the key for the pair to delete\n * @param {Tile} value If a value is provided, remove that exact version of the value.\n * @returns {TileCache} this cache\n * @private\n */\n remove(tileID: OverscaledTileID, value: ?{ value: Tile, timeout: ?TimeoutID}) {\n if (!this.has(tileID)) { return this; }\n const key = tileID.wrapped().key;\n\n const dataIndex = value === undefined ? 0 : this.data[key].indexOf(value);\n const data = this.data[key][dataIndex];\n this.data[key].splice(dataIndex, 1);\n if (data.timeout) clearTimeout(data.timeout);\n if (this.data[key].length === 0) {\n delete this.data[key];\n }\n this.onRemove(data.value);\n this.order.splice(this.order.indexOf(key), 1);\n\n return this;\n }\n\n /**\n * Change the max size of the cache.\n *\n * @param {number} max the max size of the cache\n * @returns {TileCache} this cache\n * @private\n */\n setMaxSize(max: number): TileCache {\n this.max = max;\n\n while (this.order.length > this.max) {\n const removedData = this._getAndRemoveByKey(this.order[0]);\n if (removedData) this.onRemove(removedData);\n }\n\n return this;\n }\n\n /**\n * Remove entries that do not pass a filter function. Used for removing\n * stale tiles from the cache.\n *\n * @param {function} filterFn Determines whether the tile is filtered. If the supplied function returns false, the tile will be filtered out.\n */\n filter(filterFn: (tile: Tile) => boolean) {\n const removed = [];\n for (const key in this.data) {\n for (const entry of this.data[key]) {\n if (!filterFn(entry.value)) {\n removed.push(entry);\n }\n }\n }\n for (const r of removed) {\n this.remove(r.value.tileID, r);\n }\n }\n}\n\nexport default TileCache;\n","// @flow\nimport assert from 'assert';\n\nimport type {StructArray} from '../util/struct_array';\nimport type {TriangleIndexArray, LineIndexArray, LineStripIndexArray} from '../data/index_array_type';\nimport type Context from '../gl/context';\n\nclass IndexBuffer {\n context: Context;\n buffer: WebGLBuffer;\n dynamicDraw: boolean;\n\n constructor(context: Context, array: TriangleIndexArray | LineIndexArray | LineStripIndexArray, dynamicDraw?: boolean) {\n this.context = context;\n const gl = context.gl;\n this.buffer = gl.createBuffer();\n this.dynamicDraw = Boolean(dynamicDraw);\n\n // The bound index buffer is part of vertex array object state. We don't want to\n // modify whatever VAO happens to be currently bound, so make sure the default\n // vertex array provided by the context is bound instead.\n this.context.unbindVAO();\n\n context.bindElementBuffer.set(this.buffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW);\n\n if (!this.dynamicDraw) {\n delete array.arrayBuffer;\n }\n }\n\n bind() {\n this.context.bindElementBuffer.set(this.buffer);\n }\n\n updateData(array: StructArray) {\n const gl = this.context.gl;\n assert(this.dynamicDraw);\n // The right VAO will get this buffer re-bound later in VertexArrayObject#bind\n // See https://github.com/mapbox/mapbox-gl-js/issues/5620\n this.context.unbindVAO();\n this.bind();\n gl.bufferSubData(gl.ELEMENT_ARRAY_BUFFER, 0, array.arrayBuffer);\n }\n\n destroy() {\n const gl = this.context.gl;\n if (this.buffer) {\n gl.deleteBuffer(this.buffer);\n delete this.buffer;\n }\n }\n}\n\nexport default IndexBuffer;\n","// @flow\n\nimport assert from 'assert';\n\nimport type {\n StructArray,\n StructArrayMember\n} from '../util/struct_array';\n\nimport type Program from '../render/program';\nimport type Context from '../gl/context';\n\n/**\n * @enum {string} AttributeType\n * @private\n * @readonly\n */\nconst AttributeType = {\n Int8: 'BYTE',\n Uint8: 'UNSIGNED_BYTE',\n Int16: 'SHORT',\n Uint16: 'UNSIGNED_SHORT',\n Int32: 'INT',\n Uint32: 'UNSIGNED_INT',\n Float32: 'FLOAT'\n};\n\n/**\n * The `VertexBuffer` class turns a `StructArray` into a WebGL buffer. Each member of the StructArray's\n * Struct type is converted to a WebGL atribute.\n * @private\n */\nclass VertexBuffer {\n length: number;\n attributes: $ReadOnlyArray;\n itemSize: number;\n dynamicDraw: ?boolean;\n context: Context;\n buffer: WebGLBuffer;\n\n /**\n * @param dynamicDraw Whether this buffer will be repeatedly updated.\n * @private\n */\n constructor(context: Context, array: StructArray, attributes: $ReadOnlyArray, dynamicDraw?: boolean) {\n this.length = array.length;\n this.attributes = attributes;\n this.itemSize = array.bytesPerElement;\n this.dynamicDraw = dynamicDraw;\n\n this.context = context;\n const gl = context.gl;\n this.buffer = gl.createBuffer();\n context.bindVertexBuffer.set(this.buffer);\n gl.bufferData(gl.ARRAY_BUFFER, array.arrayBuffer, this.dynamicDraw ? gl.DYNAMIC_DRAW : gl.STATIC_DRAW);\n\n if (!this.dynamicDraw) {\n delete array.arrayBuffer;\n }\n }\n\n bind() {\n this.context.bindVertexBuffer.set(this.buffer);\n }\n\n updateData(array: StructArray) {\n assert(array.length === this.length);\n const gl = this.context.gl;\n this.bind();\n gl.bufferSubData(gl.ARRAY_BUFFER, 0, array.arrayBuffer);\n }\n\n enableAttributes(gl: WebGLRenderingContext, program: Program<*>) {\n for (let j = 0; j < this.attributes.length; j++) {\n const member = this.attributes[j];\n const attribIndex: number | void = program.attributes[member.name];\n if (attribIndex !== undefined) {\n gl.enableVertexAttribArray(attribIndex);\n }\n }\n }\n\n /**\n * Set the attribute pointers in a WebGL context\n * @param gl The WebGL context\n * @param program The active WebGL program\n * @param vertexOffset Index of the starting vertex of the segment\n */\n setVertexAttribPointers(gl: WebGLRenderingContext, program: Program<*>, vertexOffset: ?number) {\n for (let j = 0; j < this.attributes.length; j++) {\n const member = this.attributes[j];\n const attribIndex: number | void = program.attributes[member.name];\n\n if (attribIndex !== undefined) {\n gl.vertexAttribPointer(\n attribIndex,\n member.components,\n (gl: any)[AttributeType[member.type]],\n false,\n this.itemSize,\n member.offset + (this.itemSize * (vertexOffset || 0))\n );\n }\n }\n }\n\n /**\n * Destroy the GL buffer bound to the given WebGL context\n */\n destroy() {\n const gl = this.context.gl;\n if (this.buffer) {\n gl.deleteBuffer(this.buffer);\n delete this.buffer;\n }\n }\n}\n\nexport default VertexBuffer;\n","// @flow\n\nimport Color from '../style-spec/util/color';\n\nimport type Context from './context';\nimport type {\n BlendFuncType,\n BlendEquationType,\n ColorMaskType,\n DepthRangeType,\n DepthMaskType,\n StencilFuncType,\n StencilOpType,\n DepthFuncType,\n TextureUnitType,\n ViewportType,\n CullFaceModeType,\n FrontFaceType,\n} from './types';\n\nexport interface Value {\n current: T;\n default: T;\n dirty: boolean;\n get(): T;\n setDefault(): void;\n set(value: T): void;\n}\n\nclass BaseValue implements Value {\n gl: WebGLRenderingContext;\n current: T;\n default: T;\n dirty: boolean;\n\n constructor(context: Context) {\n this.gl = context.gl;\n this.default = this.getDefault();\n this.current = this.default;\n this.dirty = false;\n }\n\n get(): T {\n return this.current;\n }\n set(value: T) { // eslint-disable-line\n // overridden in child classes;\n }\n\n getDefault(): T {\n return this.default; // overriden in child classes\n }\n setDefault() {\n this.set(this.default);\n }\n}\n\nexport class ClearColor extends BaseValue {\n getDefault(): Color {\n return Color.transparent;\n }\n set(v: Color) {\n const c = this.current;\n if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) return;\n this.gl.clearColor(v.r, v.g, v.b, v.a);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class ClearDepth extends BaseValue {\n getDefault(): number {\n return 1;\n }\n set(v: number) {\n if (v === this.current && !this.dirty) return;\n this.gl.clearDepth(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class ClearStencil extends BaseValue {\n getDefault(): number {\n return 0;\n }\n set(v: number) {\n if (v === this.current && !this.dirty) return;\n this.gl.clearStencil(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class ColorMask extends BaseValue {\n getDefault(): ColorMaskType {\n return [true, true, true, true];\n }\n set(v: ColorMaskType) {\n const c = this.current;\n if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) return;\n this.gl.colorMask(v[0], v[1], v[2], v[3]);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class DepthMask extends BaseValue {\n getDefault(): DepthMaskType {\n return true;\n }\n set(v: DepthMaskType): void {\n if (v === this.current && !this.dirty) return;\n this.gl.depthMask(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class StencilMask extends BaseValue {\n getDefault(): number {\n return 0xFF;\n }\n set(v: number): void {\n if (v === this.current && !this.dirty) return;\n this.gl.stencilMask(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class StencilFunc extends BaseValue {\n getDefault(): StencilFuncType {\n return {\n func: this.gl.ALWAYS,\n ref: 0,\n mask: 0xFF\n };\n }\n set(v: StencilFuncType): void {\n const c = this.current;\n if (v.func === c.func && v.ref === c.ref && v.mask === c.mask && !this.dirty) return;\n this.gl.stencilFunc(v.func, v.ref, v.mask);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class StencilOp extends BaseValue {\n getDefault(): StencilOpType {\n const gl = this.gl;\n return [gl.KEEP, gl.KEEP, gl.KEEP];\n }\n set(v: StencilOpType) {\n const c = this.current;\n if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && !this.dirty) return;\n this.gl.stencilOp(v[0], v[1], v[2]);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class StencilTest extends BaseValue {\n getDefault(): boolean {\n return false;\n }\n set(v: boolean) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n if (v) {\n gl.enable(gl.STENCIL_TEST);\n } else {\n gl.disable(gl.STENCIL_TEST);\n }\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class DepthRange extends BaseValue {\n getDefault(): DepthRangeType {\n return [0, 1];\n }\n set(v: DepthRangeType) {\n const c = this.current;\n if (v[0] === c[0] && v[1] === c[1] && !this.dirty) return;\n this.gl.depthRange(v[0], v[1]);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class DepthTest extends BaseValue {\n getDefault(): boolean {\n return false;\n }\n set(v: boolean) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n if (v) {\n gl.enable(gl.DEPTH_TEST);\n } else {\n gl.disable(gl.DEPTH_TEST);\n }\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class DepthFunc extends BaseValue {\n getDefault(): DepthFuncType {\n return this.gl.LESS;\n }\n set(v: DepthFuncType) {\n if (v === this.current && !this.dirty) return;\n this.gl.depthFunc(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class Blend extends BaseValue {\n getDefault(): boolean {\n return false;\n }\n set(v: boolean) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n if (v) {\n gl.enable(gl.BLEND);\n } else {\n gl.disable(gl.BLEND);\n }\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BlendFunc extends BaseValue {\n getDefault(): BlendFuncType {\n const gl = this.gl;\n return [gl.ONE, gl.ZERO];\n }\n set(v: BlendFuncType) {\n const c = this.current;\n if (v[0] === c[0] && v[1] === c[1] && !this.dirty) return;\n this.gl.blendFunc(v[0], v[1]);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BlendColor extends BaseValue {\n getDefault(): Color {\n return Color.transparent;\n }\n set(v: Color) {\n const c = this.current;\n if (v.r === c.r && v.g === c.g && v.b === c.b && v.a === c.a && !this.dirty) return;\n this.gl.blendColor(v.r, v.g, v.b, v.a);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BlendEquation extends BaseValue {\n getDefault(): BlendEquationType {\n return this.gl.FUNC_ADD;\n }\n set(v: BlendEquationType) {\n if (v === this.current && !this.dirty) return;\n this.gl.blendEquation(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class CullFace extends BaseValue {\n getDefault(): boolean {\n return false;\n }\n set(v: boolean) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n if (v) {\n gl.enable(gl.CULL_FACE);\n } else {\n gl.disable(gl.CULL_FACE);\n }\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class CullFaceSide extends BaseValue {\n getDefault(): CullFaceModeType {\n return this.gl.BACK;\n }\n set(v: CullFaceModeType) {\n if (v === this.current && !this.dirty) return;\n this.gl.cullFace(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class FrontFace extends BaseValue {\n getDefault(): FrontFaceType {\n return this.gl.CCW;\n }\n set(v: FrontFaceType) {\n if (v === this.current && !this.dirty) return;\n this.gl.frontFace(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class Program extends BaseValue {\n getDefault(): WebGLProgram {\n return null;\n }\n set(v: ?WebGLProgram) {\n if (v === this.current && !this.dirty) return;\n this.gl.useProgram(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class ActiveTextureUnit extends BaseValue {\n getDefault(): TextureUnitType {\n return this.gl.TEXTURE0;\n }\n set(v: TextureUnitType) {\n if (v === this.current && !this.dirty) return;\n this.gl.activeTexture(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class Viewport extends BaseValue {\n getDefault(): ViewportType {\n const gl = this.gl;\n return [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight];\n }\n set(v: ViewportType) {\n const c = this.current;\n if (v[0] === c[0] && v[1] === c[1] && v[2] === c[2] && v[3] === c[3] && !this.dirty) return;\n this.gl.viewport(v[0], v[1], v[2], v[3]);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BindFramebuffer extends BaseValue {\n getDefault(): WebGLFramebuffer {\n return null;\n }\n set(v: ?WebGLFramebuffer) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n gl.bindFramebuffer(gl.FRAMEBUFFER, v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BindRenderbuffer extends BaseValue {\n getDefault(): WebGLRenderbuffer {\n return null;\n }\n set(v: ?WebGLRenderbuffer) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n gl.bindRenderbuffer(gl.RENDERBUFFER, v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BindTexture extends BaseValue {\n getDefault(): WebGLTexture {\n return null;\n }\n set(v: ?WebGLTexture) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n gl.bindTexture(gl.TEXTURE_2D, v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BindVertexBuffer extends BaseValue {\n getDefault(): WebGLBuffer {\n return null;\n }\n set(v: ?WebGLBuffer) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n gl.bindBuffer(gl.ARRAY_BUFFER, v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BindElementBuffer extends BaseValue {\n getDefault(): WebGLBuffer {\n return null;\n }\n set(v: ?WebGLBuffer) {\n // Always rebind\n const gl = this.gl;\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class BindVertexArrayOES extends BaseValue {\n vao: any;\n\n constructor(context: Context) {\n super(context);\n this.vao = context.extVertexArrayObject;\n }\n getDefault(): any {\n return null;\n }\n set(v: any) {\n if (!this.vao || v === this.current && !this.dirty) return;\n this.vao.bindVertexArrayOES(v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class PixelStoreUnpack extends BaseValue {\n getDefault(): number {\n return 4;\n }\n set(v: number) {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n gl.pixelStorei(gl.UNPACK_ALIGNMENT, v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class PixelStoreUnpackPremultiplyAlpha extends BaseValue {\n getDefault(): boolean {\n return false;\n }\n set(v: boolean): void {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, (v: any));\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class PixelStoreUnpackFlipY extends BaseValue {\n getDefault(): boolean {\n return false;\n }\n set(v: boolean): void {\n if (v === this.current && !this.dirty) return;\n const gl = this.gl;\n gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, (v: any));\n this.current = v;\n this.dirty = false;\n }\n}\n\nclass FramebufferAttachment extends BaseValue {\n parent: WebGLFramebuffer;\n context: Context;\n\n constructor(context: Context, parent: WebGLFramebuffer) {\n super(context);\n this.context = context;\n this.parent = parent;\n }\n getDefault() {\n return null;\n }\n}\n\nexport class ColorAttachment extends FramebufferAttachment {\n setDirty() {\n this.dirty = true;\n }\n set(v: ?WebGLTexture): void {\n if (v === this.current && !this.dirty) return;\n this.context.bindFramebuffer.set(this.parent);\n // note: it's possible to attach a renderbuffer to the color\n // attachment point, but thus far MBGL only uses textures for color\n const gl = this.gl;\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, v, 0);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class DepthAttachment extends FramebufferAttachment {\n set(v: ?WebGLRenderbuffer): void {\n if (v === this.current && !this.dirty) return;\n this.context.bindFramebuffer.set(this.parent);\n // note: it's possible to attach a texture to the depth attachment\n // point, but thus far MBGL only uses renderbuffers for depth\n const gl = this.gl;\n gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, v);\n this.current = v;\n this.dirty = false;\n }\n}\n","// @flow\nimport {ColorAttachment, DepthAttachment} from './value';\nimport assert from 'assert';\n\nimport type Context from './context';\n\nclass Framebuffer {\n context: Context;\n width: number;\n height: number;\n framebuffer: WebGLFramebuffer;\n colorAttachment: ColorAttachment;\n depthAttachment: DepthAttachment;\n\n constructor(context: Context, width: number, height: number, hasDepth: boolean) {\n this.context = context;\n this.width = width;\n this.height = height;\n const gl = context.gl;\n const fbo = this.framebuffer = gl.createFramebuffer();\n\n this.colorAttachment = new ColorAttachment(context, fbo);\n if (hasDepth) {\n this.depthAttachment = new DepthAttachment(context, fbo);\n }\n assert(gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE);\n }\n\n destroy() {\n const gl = this.context.gl;\n\n const texture = this.colorAttachment.get();\n if (texture) gl.deleteTexture(texture);\n\n if (this.depthAttachment) {\n const renderbuffer = this.depthAttachment.get();\n if (renderbuffer) gl.deleteRenderbuffer(renderbuffer);\n }\n\n gl.deleteFramebuffer(this.framebuffer);\n }\n}\n\nexport default Framebuffer;\n","// @flow\nimport type {DepthFuncType, DepthMaskType, DepthRangeType} from './types';\n\nconst ALWAYS = 0x0207;\n\nclass DepthMode {\n func: DepthFuncType;\n mask: DepthMaskType;\n range: DepthRangeType;\n\n // DepthMask enums\n static ReadOnly: boolean;\n static ReadWrite: boolean;\n\n constructor(depthFunc: DepthFuncType, depthMask: DepthMaskType, depthRange: DepthRangeType) {\n this.func = depthFunc;\n this.mask = depthMask;\n this.range = depthRange;\n }\n\n static disabled: $ReadOnly;\n}\n\nDepthMode.ReadOnly = false;\nDepthMode.ReadWrite = true;\n\nDepthMode.disabled = new DepthMode(ALWAYS, DepthMode.ReadOnly, [0, 1]);\n\nexport default DepthMode;\n","// @flow\nimport type {StencilOpConstant, StencilTest} from './types';\n\nconst ALWAYS = 0x0207;\nconst KEEP = 0x1E00;\n\nclass StencilMode {\n test: StencilTest;\n ref: number;\n mask: number;\n fail: StencilOpConstant;\n depthFail: StencilOpConstant;\n pass: StencilOpConstant;\n\n constructor(test: StencilTest, ref: number, mask: number, fail: StencilOpConstant,\n depthFail: StencilOpConstant, pass: StencilOpConstant) {\n this.test = test;\n this.ref = ref;\n this.mask = mask;\n this.fail = fail;\n this.depthFail = depthFail;\n this.pass = pass;\n }\n\n static disabled: $ReadOnly;\n}\n\nStencilMode.disabled = new StencilMode({func: ALWAYS, mask: 0}, 0, 0, KEEP, KEEP, KEEP);\n\nexport default StencilMode;\n","// @flow\nimport Color from '../style-spec/util/color';\n\nimport type {BlendFuncType, ColorMaskType} from './types';\n\nconst ZERO = 0x0000;\nconst ONE = 0x0001;\nconst ONE_MINUS_SRC_ALPHA = 0x0303;\n\nclass ColorMode {\n blendFunction: BlendFuncType;\n blendColor: Color;\n mask: ColorMaskType;\n\n constructor(blendFunction: BlendFuncType, blendColor: Color, mask: ColorMaskType) {\n this.blendFunction = blendFunction;\n this.blendColor = blendColor;\n this.mask = mask;\n }\n\n static Replace: BlendFuncType;\n\n static disabled: $ReadOnly;\n static unblended: $ReadOnly;\n static alphaBlended: $ReadOnly;\n}\n\nColorMode.Replace = [ONE, ZERO];\n\nColorMode.disabled = new ColorMode(ColorMode.Replace, Color.transparent, [false, false, false, false]);\nColorMode.unblended = new ColorMode(ColorMode.Replace, Color.transparent, [true, true, true, true]);\nColorMode.alphaBlended = new ColorMode([ONE, ONE_MINUS_SRC_ALPHA], Color.transparent, [true, true, true, true]);\n\nexport default ColorMode;\n","// @flow\n\nimport type {CullFaceModeType, FrontFaceType} from './types';\n\nconst BACK = 0x0405;\nconst CCW = 0x0901;\n\nclass CullFaceMode {\n enable: boolean;\n mode: CullFaceModeType;\n frontFace: FrontFaceType;\n\n constructor(enable: boolean, mode: CullFaceModeType, frontFace: FrontFaceType) {\n this.enable = enable;\n this.mode = mode;\n this.frontFace = frontFace;\n }\n\n static disabled: $ReadOnly;\n static backCCW: $ReadOnly;\n}\n\nCullFaceMode.disabled = new CullFaceMode(false, BACK, CCW);\nCullFaceMode.backCCW = new CullFaceMode(true, BACK, CCW);\n\nexport default CullFaceMode;\n","// @flow\nimport IndexBuffer from './index_buffer';\n\nimport VertexBuffer from './vertex_buffer';\nimport Framebuffer from './framebuffer';\nimport DepthMode from './depth_mode';\nimport StencilMode from './stencil_mode';\nimport ColorMode from './color_mode';\nimport CullFaceMode from './cull_face_mode';\nimport {deepEqual} from '../util/util';\nimport {ClearColor, ClearDepth, ClearStencil, ColorMask, DepthMask, StencilMask, StencilFunc, StencilOp, StencilTest, DepthRange, DepthTest, DepthFunc, Blend, BlendFunc, BlendColor, BlendEquation, CullFace, CullFaceSide, FrontFace, Program, ActiveTextureUnit, Viewport, BindFramebuffer, BindRenderbuffer, BindTexture, BindVertexBuffer, BindElementBuffer, BindVertexArrayOES, PixelStoreUnpack, PixelStoreUnpackPremultiplyAlpha, PixelStoreUnpackFlipY} from './value';\n\nimport type {TriangleIndexArray, LineIndexArray, LineStripIndexArray} from '../data/index_array_type';\nimport type {\n StructArray,\n StructArrayMember\n} from '../util/struct_array';\nimport type Color from '../style-spec/util/color';\n\ntype ClearArgs = {\n color?: Color,\n depth?: number,\n stencil?: number\n};\n\nclass Context {\n gl: WebGLRenderingContext;\n extVertexArrayObject: any;\n currentNumAttributes: ?number;\n maxTextureSize: number;\n\n clearColor: ClearColor;\n clearDepth: ClearDepth;\n clearStencil: ClearStencil;\n colorMask: ColorMask;\n depthMask: DepthMask;\n stencilMask: StencilMask;\n stencilFunc: StencilFunc;\n stencilOp: StencilOp;\n stencilTest: StencilTest;\n depthRange: DepthRange;\n depthTest: DepthTest;\n depthFunc: DepthFunc;\n blend: Blend;\n blendFunc: BlendFunc;\n blendColor: BlendColor;\n blendEquation: BlendEquation;\n cullFace: CullFace;\n cullFaceSide: CullFaceSide;\n frontFace: FrontFace;\n program: Program;\n activeTexture: ActiveTextureUnit;\n viewport: Viewport;\n bindFramebuffer: BindFramebuffer;\n bindRenderbuffer: BindRenderbuffer;\n bindTexture: BindTexture;\n bindVertexBuffer: BindVertexBuffer;\n bindElementBuffer: BindElementBuffer;\n bindVertexArrayOES: BindVertexArrayOES;\n pixelStoreUnpack: PixelStoreUnpack;\n pixelStoreUnpackPremultiplyAlpha: PixelStoreUnpackPremultiplyAlpha;\n pixelStoreUnpackFlipY: PixelStoreUnpackFlipY;\n\n extTextureFilterAnisotropic: any;\n extTextureFilterAnisotropicMax: any;\n extTextureHalfFloat: any;\n extRenderToTextureHalfFloat: any;\n extTimerQuery: any;\n\n constructor(gl: WebGLRenderingContext) {\n this.gl = gl;\n this.extVertexArrayObject = this.gl.getExtension('OES_vertex_array_object');\n\n this.clearColor = new ClearColor(this);\n this.clearDepth = new ClearDepth(this);\n this.clearStencil = new ClearStencil(this);\n this.colorMask = new ColorMask(this);\n this.depthMask = new DepthMask(this);\n this.stencilMask = new StencilMask(this);\n this.stencilFunc = new StencilFunc(this);\n this.stencilOp = new StencilOp(this);\n this.stencilTest = new StencilTest(this);\n this.depthRange = new DepthRange(this);\n this.depthTest = new DepthTest(this);\n this.depthFunc = new DepthFunc(this);\n this.blend = new Blend(this);\n this.blendFunc = new BlendFunc(this);\n this.blendColor = new BlendColor(this);\n this.blendEquation = new BlendEquation(this);\n this.cullFace = new CullFace(this);\n this.cullFaceSide = new CullFaceSide(this);\n this.frontFace = new FrontFace(this);\n this.program = new Program(this);\n this.activeTexture = new ActiveTextureUnit(this);\n this.viewport = new Viewport(this);\n this.bindFramebuffer = new BindFramebuffer(this);\n this.bindRenderbuffer = new BindRenderbuffer(this);\n this.bindTexture = new BindTexture(this);\n this.bindVertexBuffer = new BindVertexBuffer(this);\n this.bindElementBuffer = new BindElementBuffer(this);\n this.bindVertexArrayOES = this.extVertexArrayObject && new BindVertexArrayOES(this);\n this.pixelStoreUnpack = new PixelStoreUnpack(this);\n this.pixelStoreUnpackPremultiplyAlpha = new PixelStoreUnpackPremultiplyAlpha(this);\n this.pixelStoreUnpackFlipY = new PixelStoreUnpackFlipY(this);\n\n this.extTextureFilterAnisotropic = (\n gl.getExtension('EXT_texture_filter_anisotropic') ||\n gl.getExtension('MOZ_EXT_texture_filter_anisotropic') ||\n gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic')\n );\n if (this.extTextureFilterAnisotropic) {\n this.extTextureFilterAnisotropicMax = gl.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT);\n }\n\n this.extTextureHalfFloat = gl.getExtension('OES_texture_half_float');\n if (this.extTextureHalfFloat) {\n gl.getExtension('OES_texture_half_float_linear');\n this.extRenderToTextureHalfFloat = gl.getExtension('EXT_color_buffer_half_float');\n }\n\n this.extTimerQuery = gl.getExtension('EXT_disjoint_timer_query');\n this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);\n }\n\n setDefault() {\n this.unbindVAO();\n\n this.clearColor.setDefault();\n this.clearDepth.setDefault();\n this.clearStencil.setDefault();\n this.colorMask.setDefault();\n this.depthMask.setDefault();\n this.stencilMask.setDefault();\n this.stencilFunc.setDefault();\n this.stencilOp.setDefault();\n this.stencilTest.setDefault();\n this.depthRange.setDefault();\n this.depthTest.setDefault();\n this.depthFunc.setDefault();\n this.blend.setDefault();\n this.blendFunc.setDefault();\n this.blendColor.setDefault();\n this.blendEquation.setDefault();\n this.cullFace.setDefault();\n this.cullFaceSide.setDefault();\n this.frontFace.setDefault();\n this.program.setDefault();\n this.activeTexture.setDefault();\n this.bindFramebuffer.setDefault();\n this.pixelStoreUnpack.setDefault();\n this.pixelStoreUnpackPremultiplyAlpha.setDefault();\n this.pixelStoreUnpackFlipY.setDefault();\n }\n\n setDirty() {\n this.clearColor.dirty = true;\n this.clearDepth.dirty = true;\n this.clearStencil.dirty = true;\n this.colorMask.dirty = true;\n this.depthMask.dirty = true;\n this.stencilMask.dirty = true;\n this.stencilFunc.dirty = true;\n this.stencilOp.dirty = true;\n this.stencilTest.dirty = true;\n this.depthRange.dirty = true;\n this.depthTest.dirty = true;\n this.depthFunc.dirty = true;\n this.blend.dirty = true;\n this.blendFunc.dirty = true;\n this.blendColor.dirty = true;\n this.blendEquation.dirty = true;\n this.cullFace.dirty = true;\n this.cullFaceSide.dirty = true;\n this.frontFace.dirty = true;\n this.program.dirty = true;\n this.activeTexture.dirty = true;\n this.viewport.dirty = true;\n this.bindFramebuffer.dirty = true;\n this.bindRenderbuffer.dirty = true;\n this.bindTexture.dirty = true;\n this.bindVertexBuffer.dirty = true;\n this.bindElementBuffer.dirty = true;\n if (this.extVertexArrayObject) {\n this.bindVertexArrayOES.dirty = true;\n }\n this.pixelStoreUnpack.dirty = true;\n this.pixelStoreUnpackPremultiplyAlpha.dirty = true;\n this.pixelStoreUnpackFlipY.dirty = true;\n }\n\n createIndexBuffer(array: TriangleIndexArray | LineIndexArray | LineStripIndexArray, dynamicDraw?: boolean) {\n return new IndexBuffer(this, array, dynamicDraw);\n }\n\n createVertexBuffer(array: StructArray, attributes: $ReadOnlyArray, dynamicDraw?: boolean) {\n return new VertexBuffer(this, array, attributes, dynamicDraw);\n }\n\n createRenderbuffer(storageFormat: number, width: number, height: number) {\n const gl = this.gl;\n\n const rbo = gl.createRenderbuffer();\n this.bindRenderbuffer.set(rbo);\n gl.renderbufferStorage(gl.RENDERBUFFER, storageFormat, width, height);\n this.bindRenderbuffer.set(null);\n\n return rbo;\n }\n\n createFramebuffer(width: number, height: number, hasDepth: boolean) {\n return new Framebuffer(this, width, height, hasDepth);\n }\n\n clear({color, depth}: ClearArgs) {\n const gl = this.gl;\n let mask = 0;\n\n if (color) {\n mask |= gl.COLOR_BUFFER_BIT;\n this.clearColor.set(color);\n this.colorMask.set([true, true, true, true]);\n }\n\n if (typeof depth !== 'undefined') {\n mask |= gl.DEPTH_BUFFER_BIT;\n\n // Workaround for platforms where clearDepth doesn't seem to work\n // without reseting the depthRange. See https://github.com/mapbox/mapbox-gl-js/issues/3437\n this.depthRange.set([0, 1]);\n\n this.clearDepth.set(depth);\n this.depthMask.set(true);\n }\n\n // See note in Painter#clearStencil: implement this the easy way once GPU bug/workaround is fixed upstream\n // if (typeof stencil !== 'undefined') {\n // mask |= gl.STENCIL_BUFFER_BIT;\n // this.clearStencil.set(stencil);\n // this.stencilMask.set(0xFF);\n // }\n\n gl.clear(mask);\n }\n\n setCullFace(cullFaceMode: $ReadOnly) {\n if (cullFaceMode.enable === false) {\n this.cullFace.set(false);\n } else {\n this.cullFace.set(true);\n this.cullFaceSide.set(cullFaceMode.mode);\n this.frontFace.set(cullFaceMode.frontFace);\n }\n }\n\n setDepthMode(depthMode: $ReadOnly) {\n if (depthMode.func === this.gl.ALWAYS && !depthMode.mask) {\n this.depthTest.set(false);\n } else {\n this.depthTest.set(true);\n this.depthFunc.set(depthMode.func);\n this.depthMask.set(depthMode.mask);\n this.depthRange.set(depthMode.range);\n }\n }\n\n setStencilMode(stencilMode: $ReadOnly) {\n if (stencilMode.test.func === this.gl.ALWAYS && !stencilMode.mask) {\n this.stencilTest.set(false);\n } else {\n this.stencilTest.set(true);\n this.stencilMask.set(stencilMode.mask);\n this.stencilOp.set([stencilMode.fail, stencilMode.depthFail, stencilMode.pass]);\n this.stencilFunc.set({\n func: stencilMode.test.func,\n ref: stencilMode.ref,\n mask: stencilMode.test.mask\n });\n }\n }\n\n setColorMode(colorMode: $ReadOnly) {\n if (deepEqual(colorMode.blendFunction, ColorMode.Replace)) {\n this.blend.set(false);\n } else {\n this.blend.set(true);\n this.blendFunc.set(colorMode.blendFunction);\n this.blendColor.set(colorMode.blendColor);\n }\n\n this.colorMask.set(colorMode.mask);\n }\n\n unbindVAO() {\n // Unbinding the VAO prevents other things (custom layers, new buffer creation) from\n // unintentionally changing the state of the last VAO used.\n if (this.extVertexArrayObject) {\n this.bindVertexArrayOES.set(null);\n }\n }\n}\n\nexport default Context;\n","// @flow\n\nimport {create as createSource} from './source';\n\nimport Tile from './tile';\nimport {Event, ErrorEvent, Evented} from '../util/evented';\nimport TileCache from './tile_cache';\nimport MercatorCoordinate from '../geo/mercator_coordinate';\nimport {keysDifference, values} from '../util/util';\nimport EXTENT from '../data/extent';\nimport Context from '../gl/context';\nimport Point from '@mapbox/point-geometry';\nimport browser from '../util/browser';\nimport {OverscaledTileID} from './tile_id';\nimport assert from 'assert';\nimport SourceFeatureState from './source_state';\n\nimport type {Source} from './source';\nimport type Map from '../ui/map';\nimport type Style from '../style/style';\nimport type Dispatcher from '../util/dispatcher';\nimport type Transform from '../geo/transform';\nimport type {TileState} from './tile';\nimport type {Callback} from '../types/callback';\nimport type {SourceSpecification} from '../style-spec/types';\n\n/**\n * `SourceCache` is responsible for\n *\n * - creating an instance of `Source`\n * - forwarding events from `Source`\n * - caching tiles loaded from an instance of `Source`\n * - loading the tiles needed to render a given viewport\n * - unloading the cached tiles not needed to render a given viewport\n *\n * @private\n */\nclass SourceCache extends Evented {\n id: string;\n dispatcher: Dispatcher;\n map: Map;\n style: Style;\n\n _source: Source;\n _sourceLoaded: boolean;\n _sourceErrored: boolean;\n _tiles: {[_: string]: Tile};\n _prevLng: number | void;\n _cache: TileCache;\n _timers: {[_: any]: TimeoutID};\n _cacheTimers: {[_: any]: TimeoutID};\n _maxTileCacheSize: ?number;\n _paused: boolean;\n _shouldReloadOnResume: boolean;\n _coveredTiles: {[_: string]: boolean};\n transform: Transform;\n _isIdRenderable: (id: string, symbolLayer?: boolean) => boolean;\n used: boolean;\n _state: SourceFeatureState;\n _loadedParentTiles: {[_: string]: ?Tile};\n\n static maxUnderzooming: number;\n static maxOverzooming: number;\n\n constructor(id: string, options: SourceSpecification, dispatcher: Dispatcher) {\n super();\n this.id = id;\n this.dispatcher = dispatcher;\n\n this.on('data', (e) => {\n // this._sourceLoaded signifies that the TileJSON is loaded if applicable.\n // if the source type does not come with a TileJSON, the flag signifies the\n // source data has loaded (i.e geojson has been tiled on the worker and is ready)\n if (e.dataType === 'source' && e.sourceDataType === 'metadata') this._sourceLoaded = true;\n\n // for sources with mutable data, this event fires when the underlying data\n // to a source is changed. (i.e. GeoJSONSource#setData and ImageSource#serCoordinates)\n if (this._sourceLoaded && !this._paused && e.dataType === \"source\" && e.sourceDataType === 'content') {\n this.reload();\n if (this.transform) {\n this.update(this.transform);\n }\n }\n });\n\n this.on('error', () => {\n this._sourceErrored = true;\n });\n\n this._source = createSource(id, options, dispatcher, this);\n\n this._tiles = {};\n this._cache = new TileCache(0, this._unloadTile.bind(this));\n this._timers = {};\n this._cacheTimers = {};\n this._maxTileCacheSize = null;\n this._loadedParentTiles = {};\n\n this._coveredTiles = {};\n this._state = new SourceFeatureState();\n }\n\n onAdd(map: Map) {\n this.map = map;\n this._maxTileCacheSize = map ? map._maxTileCacheSize : null;\n if (this._source && this._source.onAdd) {\n this._source.onAdd(map);\n }\n }\n\n onRemove(map: Map) {\n if (this._source && this._source.onRemove) {\n this._source.onRemove(map);\n }\n }\n\n /**\n * Return true if no tile data is pending, tiles will not change unless\n * an additional API call is received.\n * @private\n */\n loaded(): boolean {\n if (this._sourceErrored) { return true; }\n if (!this._sourceLoaded) { return false; }\n if (!this._source.loaded()) { return false; }\n for (const t in this._tiles) {\n const tile = this._tiles[t];\n if (tile.state !== 'loaded' && tile.state !== 'errored')\n return false;\n }\n return true;\n }\n\n getSource(): Source {\n return this._source;\n }\n\n pause() {\n this._paused = true;\n }\n\n resume() {\n if (!this._paused) return;\n const shouldReload = this._shouldReloadOnResume;\n this._paused = false;\n this._shouldReloadOnResume = false;\n if (shouldReload) this.reload();\n if (this.transform) this.update(this.transform);\n }\n\n _loadTile(tile: Tile, callback: Callback) {\n return this._source.loadTile(tile, callback);\n }\n\n _unloadTile(tile: Tile) {\n if (this._source.unloadTile)\n return this._source.unloadTile(tile, () => {});\n }\n\n _abortTile(tile: Tile) {\n if (this._source.abortTile)\n return this._source.abortTile(tile, () => {});\n }\n\n serialize() {\n return this._source.serialize();\n }\n\n prepare(context: Context) {\n if (this._source.prepare) {\n this._source.prepare();\n }\n\n this._state.coalesceChanges(this._tiles, this.map ? this.map.painter : null);\n for (const i in this._tiles) {\n const tile = this._tiles[i];\n tile.upload(context);\n tile.prepare(this.map.style.imageManager);\n }\n }\n\n /**\n * Return all tile ids ordered with z-order, and cast to numbers\n * @private\n */\n getIds(): Array {\n return (values(this._tiles): any).map((tile: Tile) => tile.tileID).sort(compareTileId).map(id => id.key);\n }\n\n getRenderableIds(symbolLayer?: boolean): Array {\n const renderables: Array = [];\n for (const id in this._tiles) {\n if (this._isIdRenderable(id, symbolLayer)) renderables.push(this._tiles[id]);\n }\n if (symbolLayer) {\n return renderables.sort((a_: Tile, b_: Tile) => {\n const a = a_.tileID;\n const b = b_.tileID;\n const rotatedA = (new Point(a.canonical.x, a.canonical.y))._rotate(this.transform.angle);\n const rotatedB = (new Point(b.canonical.x, b.canonical.y))._rotate(this.transform.angle);\n return a.overscaledZ - b.overscaledZ || rotatedB.y - rotatedA.y || rotatedB.x - rotatedA.x;\n }).map(tile => tile.tileID.key);\n }\n return renderables.map(tile => tile.tileID).sort(compareTileId).map(id => id.key);\n }\n\n hasRenderableParent(tileID: OverscaledTileID) {\n const parentTile = this.findLoadedParent(tileID, 0);\n if (parentTile) {\n return this._isIdRenderable(parentTile.tileID.key);\n }\n return false;\n }\n\n _isIdRenderable(id: string, symbolLayer?: boolean) {\n return this._tiles[id] && this._tiles[id].hasData() &&\n !this._coveredTiles[id] && (symbolLayer || !this._tiles[id].holdingForFade());\n }\n\n reload() {\n if (this._paused) {\n this._shouldReloadOnResume = true;\n return;\n }\n\n this._cache.reset();\n\n for (const i in this._tiles) {\n if (this._tiles[i].state !== \"errored\") this._reloadTile(i, 'reloading');\n }\n }\n\n _reloadTile(id: string, state: TileState) {\n const tile = this._tiles[id];\n\n // this potentially does not address all underlying\n // issues https://github.com/mapbox/mapbox-gl-js/issues/4252\n // - hard to tell without repro steps\n if (!tile) return;\n\n // The difference between \"loading\" tiles and \"reloading\" or \"expired\"\n // tiles is that \"reloading\"/\"expired\" tiles are \"renderable\".\n // Therefore, a \"loading\" tile cannot become a \"reloading\" tile without\n // first becoming a \"loaded\" tile.\n if (tile.state !== 'loading') {\n tile.state = state;\n }\n\n this._loadTile(tile, this._tileLoaded.bind(this, tile, id, state));\n }\n\n _tileLoaded(tile: Tile, id: string, previousState: TileState, err: ?Error) {\n if (err) {\n tile.state = 'errored';\n if ((err: any).status !== 404) this._source.fire(new ErrorEvent(err, {tile}));\n // continue to try loading parent/children tiles if a tile doesn't exist (404)\n else this.update(this.transform);\n return;\n }\n\n tile.timeAdded = browser.now();\n if (previousState === 'expired') tile.refreshedUponExpiration = true;\n this._setTileReloadTimer(id, tile);\n if (this.getSource().type === 'raster-dem' && tile.dem) this._backfillDEM(tile);\n this._state.initializeTileState(tile, this.map ? this.map.painter : null);\n\n this._source.fire(new Event('data', {dataType: 'source', tile, coord: tile.tileID}));\n }\n\n /**\n * For raster terrain source, backfill DEM to eliminate visible tile boundaries\n * @private\n */\n _backfillDEM(tile: Tile) {\n const renderables = this.getRenderableIds();\n for (let i = 0; i < renderables.length; i++) {\n const borderId = renderables[i];\n if (tile.neighboringTiles && tile.neighboringTiles[borderId]) {\n const borderTile = this.getTileByID(borderId);\n fillBorder(tile, borderTile);\n fillBorder(borderTile, tile);\n }\n }\n\n function fillBorder(tile, borderTile) {\n tile.needsHillshadePrepare = true;\n let dx = borderTile.tileID.canonical.x - tile.tileID.canonical.x;\n const dy = borderTile.tileID.canonical.y - tile.tileID.canonical.y;\n const dim = Math.pow(2, tile.tileID.canonical.z);\n const borderId = borderTile.tileID.key;\n if (dx === 0 && dy === 0) return;\n\n if (Math.abs(dy) > 1) {\n return;\n }\n if (Math.abs(dx) > 1) {\n // Adjust the delta coordinate for world wraparound.\n if (Math.abs(dx + dim) === 1) {\n dx += dim;\n } else if (Math.abs(dx - dim) === 1) {\n dx -= dim;\n }\n }\n if (!borderTile.dem || !tile.dem) return;\n tile.dem.backfillBorder(borderTile.dem, dx, dy);\n if (tile.neighboringTiles && tile.neighboringTiles[borderId])\n tile.neighboringTiles[borderId].backfilled = true;\n }\n }\n /**\n * Get a specific tile by TileID\n * @private\n */\n getTile(tileID: OverscaledTileID): Tile {\n return this.getTileByID(tileID.key);\n }\n\n /**\n * Get a specific tile by id\n * @private\n */\n getTileByID(id: string): Tile {\n return this._tiles[id];\n }\n\n /**\n * For a given set of tiles, retain children that are loaded and have a zoom\n * between `zoom` (exclusive) and `maxCoveringZoom` (inclusive)\n * @private\n */\n _retainLoadedChildren(\n idealTiles: {[_: any]: OverscaledTileID},\n zoom: number,\n maxCoveringZoom: number,\n retain: {[_: any]: OverscaledTileID}\n ) {\n for (const id in this._tiles) {\n let tile = this._tiles[id];\n\n // only consider renderable tiles up to maxCoveringZoom\n if (retain[id] ||\n !tile.hasData() ||\n tile.tileID.overscaledZ <= zoom ||\n tile.tileID.overscaledZ > maxCoveringZoom\n ) continue;\n\n // loop through parents and retain the topmost loaded one if found\n let topmostLoadedID = tile.tileID;\n while (tile && tile.tileID.overscaledZ > zoom + 1) {\n const parentID = tile.tileID.scaledTo(tile.tileID.overscaledZ - 1);\n\n tile = this._tiles[parentID.key];\n\n if (tile && tile.hasData()) {\n topmostLoadedID = parentID;\n }\n }\n\n // loop through ancestors of the topmost loaded child to see if there's one that needed it\n let tileID = topmostLoadedID;\n while (tileID.overscaledZ > zoom) {\n tileID = tileID.scaledTo(tileID.overscaledZ - 1);\n\n if (idealTiles[tileID.key]) {\n // found a parent that needed a loaded child; retain that child\n retain[topmostLoadedID.key] = topmostLoadedID;\n break;\n }\n }\n }\n }\n\n /**\n * Find a loaded parent of the given tile (up to minCoveringZoom)\n * @private\n */\n findLoadedParent(tileID: OverscaledTileID, minCoveringZoom: number): ?Tile {\n if (tileID.key in this._loadedParentTiles) {\n const parent = this._loadedParentTiles[tileID.key];\n if (parent && parent.tileID.overscaledZ >= minCoveringZoom) {\n return parent;\n } else {\n return null;\n }\n }\n for (let z = tileID.overscaledZ - 1; z >= minCoveringZoom; z--) {\n const parentTileID = tileID.scaledTo(z);\n const tile = this._getLoadedTile(parentTileID);\n if (tile) {\n return tile;\n }\n }\n }\n\n _getLoadedTile(tileID: OverscaledTileID): ?Tile {\n const tile = this._tiles[tileID.key];\n if (tile && tile.hasData()) {\n return tile;\n }\n // TileCache ignores wrap in lookup.\n const cachedTile = this._cache.getByKey(tileID.wrapped().key);\n return cachedTile;\n }\n\n /**\n * Resizes the tile cache based on the current viewport's size\n * or the maxTileCacheSize option passed during map creation\n *\n * Larger viewports use more tiles and need larger caches. Larger viewports\n * are more likely to be found on devices with more memory and on pages where\n * the map is more important.\n * @private\n */\n updateCacheSize(transform: Transform) {\n const widthInTiles = Math.ceil(transform.width / this._source.tileSize) + 1;\n const heightInTiles = Math.ceil(transform.height / this._source.tileSize) + 1;\n const approxTilesInView = widthInTiles * heightInTiles;\n const commonZoomRange = 5;\n\n const viewDependentMaxSize = Math.floor(approxTilesInView * commonZoomRange);\n const maxSize = typeof this._maxTileCacheSize === 'number' ? Math.min(this._maxTileCacheSize, viewDependentMaxSize) : viewDependentMaxSize;\n\n this._cache.setMaxSize(maxSize);\n }\n\n handleWrapJump(lng: number) {\n // On top of the regular z/x/y values, TileIDs have a `wrap` value that specify\n // which cppy of the world the tile belongs to. For example, at `lng: 10` you\n // might render z/x/y/0 while at `lng: 370` you would render z/x/y/1.\n //\n // When lng values get wrapped (going from `lng: 370` to `long: 10`) you expect\n // to see the same thing on the screen (370 degrees and 10 degrees is the same\n // place in the world) but all the TileIDs will have different wrap values.\n //\n // In order to make this transition seamless, we calculate the rounded difference of\n // \"worlds\" between the last frame and the current frame. If the map panned by\n // a world, then we can assign all the tiles new TileIDs with updated wrap values.\n // For example, assign z/x/y/1 a new id: z/x/y/0. It is the same tile, just rendered\n // in a different position.\n //\n // This enables us to reuse the tiles at more ideal locations and prevent flickering.\n const prevLng = this._prevLng === undefined ? lng : this._prevLng;\n const lngDifference = lng - prevLng;\n const worldDifference = lngDifference / 360;\n const wrapDelta = Math.round(worldDifference);\n this._prevLng = lng;\n\n if (wrapDelta) {\n const tiles: {[_: string]: Tile} = {};\n for (const key in this._tiles) {\n const tile = this._tiles[key];\n tile.tileID = tile.tileID.unwrapTo(tile.tileID.wrap + wrapDelta);\n tiles[tile.tileID.key] = tile;\n }\n this._tiles = tiles;\n\n // Reset tile reload timers\n for (const id in this._timers) {\n clearTimeout(this._timers[id]);\n delete this._timers[id];\n }\n for (const id in this._tiles) {\n const tile = this._tiles[id];\n this._setTileReloadTimer(id, tile);\n }\n }\n }\n\n /**\n * Removes tiles that are outside the viewport and adds new tiles that\n * are inside the viewport.\n * @private\n */\n update(transform: Transform) {\n this.transform = transform;\n if (!this._sourceLoaded || this._paused) { return; }\n\n this.updateCacheSize(transform);\n this.handleWrapJump(this.transform.center.lng);\n\n // Covered is a list of retained tiles who's areas are fully covered by other,\n // better, retained tiles. They are not drawn separately.\n this._coveredTiles = {};\n\n let idealTileIDs;\n if (!this.used) {\n idealTileIDs = [];\n } else if (this._source.tileID) {\n idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID)\n .map((unwrapped) => new OverscaledTileID(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y));\n } else {\n idealTileIDs = transform.coveringTiles({\n tileSize: this._source.tileSize,\n minzoom: this._source.minzoom,\n maxzoom: this._source.maxzoom,\n roundZoom: this._source.roundZoom,\n reparseOverscaled: this._source.reparseOverscaled\n });\n\n if (this._source.hasTile) {\n idealTileIDs = idealTileIDs.filter((coord) => (this._source.hasTile: any)(coord));\n }\n }\n\n // Determine the overzooming/underzooming amounts.\n const zoom = transform.coveringZoomLevel(this._source);\n const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom);\n const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom);\n\n // Retain is a list of tiles that we shouldn't delete, even if they are not\n // the most ideal tile for the current viewport. This may include tiles like\n // parent or child tiles that are *already* loaded.\n const retain = this._updateRetainedTiles(idealTileIDs, zoom);\n\n if (isRasterType(this._source.type)) {\n const parentsForFading: {[_: string]: OverscaledTileID} = {};\n const fadingTiles = {};\n const ids = Object.keys(retain);\n for (const id of ids) {\n const tileID = retain[id];\n assert(tileID.key === id);\n\n const tile = this._tiles[id];\n if (!tile || tile.fadeEndTime && tile.fadeEndTime <= browser.now()) continue;\n\n // if the tile is loaded but still fading in, find parents to cross-fade with it\n const parentTile = this.findLoadedParent(tileID, minCoveringZoom);\n if (parentTile) {\n this._addTile(parentTile.tileID);\n parentsForFading[parentTile.tileID.key] = parentTile.tileID;\n }\n\n fadingTiles[id] = tileID;\n }\n\n // for tiles that are still fading in, also find children to cross-fade with\n this._retainLoadedChildren(fadingTiles, zoom, maxCoveringZoom, retain);\n\n for (const id in parentsForFading) {\n if (!retain[id]) {\n // If a tile is only needed for fading, mark it as covered so that it isn't rendered on it's own.\n this._coveredTiles[id] = true;\n retain[id] = parentsForFading[id];\n }\n }\n }\n\n for (const retainedId in retain) {\n // Make sure retained tiles always clear any existing fade holds\n // so that if they're removed again their fade timer starts fresh.\n this._tiles[retainedId].clearFadeHold();\n }\n\n // Remove the tiles we don't need anymore.\n const remove = keysDifference(this._tiles, retain);\n for (const tileID of remove) {\n const tile = this._tiles[tileID];\n if (tile.hasSymbolBuckets && !tile.holdingForFade()) {\n tile.setHoldDuration(this.map._fadeDuration);\n } else if (!tile.hasSymbolBuckets || tile.symbolFadeFinished()) {\n this._removeTile(tileID);\n }\n }\n\n // Construct a cache of loaded parents\n this._updateLoadedParentTileCache();\n }\n\n releaseSymbolFadeTiles() {\n for (const id in this._tiles) {\n if (this._tiles[id].holdingForFade()) {\n this._removeTile(id);\n }\n }\n }\n\n _updateRetainedTiles(idealTileIDs: Array, zoom: number): {[_: string]: OverscaledTileID} {\n const retain: {[_: string]: OverscaledTileID} = {};\n const checked: {[_: string]: boolean } = {};\n const minCoveringZoom = Math.max(zoom - SourceCache.maxOverzooming, this._source.minzoom);\n const maxCoveringZoom = Math.max(zoom + SourceCache.maxUnderzooming, this._source.minzoom);\n\n const missingTiles = {};\n for (const tileID of idealTileIDs) {\n const tile = this._addTile(tileID);\n\n // retain the tile even if it's not loaded because it's an ideal tile.\n retain[tileID.key] = tileID;\n\n if (tile.hasData()) continue;\n\n if (zoom < this._source.maxzoom) {\n // save missing tiles that potentially have loaded children\n missingTiles[tileID.key] = tileID;\n }\n }\n\n // retain any loaded children of ideal tiles up to maxCoveringZoom\n this._retainLoadedChildren(missingTiles, zoom, maxCoveringZoom, retain);\n\n for (const tileID of idealTileIDs) {\n let tile = this._tiles[tileID.key];\n\n if (tile.hasData()) continue;\n\n // The tile we require is not yet loaded or does not exist;\n // Attempt to find children that fully cover it.\n\n if (zoom + 1 > this._source.maxzoom) {\n // We're looking for an overzoomed child tile.\n const childCoord = tileID.children(this._source.maxzoom)[0];\n const childTile = this.getTile(childCoord);\n if (!!childTile && childTile.hasData()) {\n retain[childCoord.key] = childCoord;\n continue; // tile is covered by overzoomed child\n }\n } else {\n // check if all 4 immediate children are loaded (i.e. the missing ideal tile is covered)\n const children = tileID.children(this._source.maxzoom);\n\n if (retain[children[0].key] &&\n retain[children[1].key] &&\n retain[children[2].key] &&\n retain[children[3].key]) continue; // tile is covered by children\n }\n\n // We couldn't find child tiles that entirely cover the ideal tile; look for parents now.\n\n // As we ascend up the tile pyramid of the ideal tile, we check whether the parent\n // tile has been previously requested (and errored because we only loop over tiles with no data)\n // in order to determine if we need to request its parent.\n let parentWasRequested = tile.wasRequested();\n\n for (let overscaledZ = tileID.overscaledZ - 1; overscaledZ >= minCoveringZoom; --overscaledZ) {\n const parentId = tileID.scaledTo(overscaledZ);\n\n // Break parent tile ascent if this route has been previously checked by another child.\n if (checked[parentId.key]) break;\n checked[parentId.key] = true;\n\n tile = this.getTile(parentId);\n if (!tile && parentWasRequested) {\n tile = this._addTile(parentId);\n }\n if (tile) {\n retain[parentId.key] = parentId;\n // Save the current values, since they're the parent of the next iteration\n // of the parent tile ascent loop.\n parentWasRequested = tile.wasRequested();\n if (tile.hasData()) break;\n }\n }\n }\n\n return retain;\n }\n\n _updateLoadedParentTileCache() {\n this._loadedParentTiles = {};\n\n for (const tileKey in this._tiles) {\n const path = [];\n let parentTile: ?Tile;\n let currentId = this._tiles[tileKey].tileID;\n\n // Find the closest loaded ancestor by traversing the tile tree towards the root and\n // caching results along the way\n while (currentId.overscaledZ > 0) {\n\n // Do we have a cached result from previous traversals?\n if (currentId.key in this._loadedParentTiles) {\n parentTile = this._loadedParentTiles[currentId.key];\n break;\n }\n\n path.push(currentId.key);\n\n // Is the parent loaded?\n const parentId = currentId.scaledTo(currentId.overscaledZ - 1);\n parentTile = this._getLoadedTile(parentId);\n if (parentTile) {\n break;\n }\n\n currentId = parentId;\n }\n\n // Cache the result of this traversal to all newly visited tiles\n for (const key of path) {\n this._loadedParentTiles[key] = parentTile;\n }\n }\n }\n\n /**\n * Add a tile, given its coordinate, to the pyramid.\n * @private\n */\n _addTile(tileID: OverscaledTileID): Tile {\n let tile = this._tiles[tileID.key];\n if (tile)\n return tile;\n\n tile = this._cache.getAndRemove(tileID);\n if (tile) {\n this._setTileReloadTimer(tileID.key, tile);\n // set the tileID because the cached tile could have had a different wrap value\n tile.tileID = tileID;\n this._state.initializeTileState(tile, this.map ? this.map.painter : null);\n if (this._cacheTimers[tileID.key]) {\n clearTimeout(this._cacheTimers[tileID.key]);\n delete this._cacheTimers[tileID.key];\n this._setTileReloadTimer(tileID.key, tile);\n }\n }\n\n const cached = Boolean(tile);\n if (!cached) {\n tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor());\n this._loadTile(tile, this._tileLoaded.bind(this, tile, tileID.key, tile.state));\n }\n\n // Impossible, but silence flow.\n if (!tile) return (null: any);\n\n tile.uses++;\n this._tiles[tileID.key] = tile;\n if (!cached) this._source.fire(new Event('dataloading', {tile, coord: tile.tileID, dataType: 'source'}));\n\n return tile;\n }\n\n _setTileReloadTimer(id: string, tile: Tile) {\n if (id in this._timers) {\n clearTimeout(this._timers[id]);\n delete this._timers[id];\n }\n\n const expiryTimeout = tile.getExpiryTimeout();\n if (expiryTimeout) {\n this._timers[id] = setTimeout(() => {\n this._reloadTile(id, 'expired');\n delete this._timers[id];\n }, expiryTimeout);\n }\n }\n\n /**\n * Remove a tile, given its id, from the pyramid\n * @private\n */\n _removeTile(id: string) {\n const tile = this._tiles[id];\n if (!tile)\n return;\n\n tile.uses--;\n delete this._tiles[id];\n if (this._timers[id]) {\n clearTimeout(this._timers[id]);\n delete this._timers[id];\n }\n\n if (tile.uses > 0)\n return;\n\n if (tile.hasData() && tile.state !== 'reloading') {\n this._cache.add(tile.tileID, tile, tile.getExpiryTimeout());\n } else {\n tile.aborted = true;\n this._abortTile(tile);\n this._unloadTile(tile);\n }\n }\n\n /**\n * Remove all tiles from this pyramid\n */\n clearTiles() {\n this._shouldReloadOnResume = false;\n this._paused = false;\n\n for (const id in this._tiles)\n this._removeTile(id);\n\n this._cache.reset();\n }\n\n /**\n * Search through our current tiles and attempt to find the tiles that\n * cover the given bounds.\n * @param pointQueryGeometry coordinates of the corners of bounding rectangle\n * @returns {Array} result items have {tile, minX, maxX, minY, maxY}, where min/max bounding values are the given bounds transformed in into the coordinate space of this tile.\n * @private\n */\n tilesIn(pointQueryGeometry: Array, maxPitchScaleFactor: number, has3DLayer: boolean) {\n\n const tileResults = [];\n\n const transform = this.transform;\n if (!transform) return tileResults;\n\n const cameraPointQueryGeometry = has3DLayer ?\n transform.getCameraQueryGeometry(pointQueryGeometry) :\n pointQueryGeometry;\n\n const queryGeometry = pointQueryGeometry.map((p) => transform.pointCoordinate(p));\n const cameraQueryGeometry = cameraPointQueryGeometry.map((p) => transform.pointCoordinate(p));\n\n const ids = this.getIds();\n\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n\n for (const p of cameraQueryGeometry) {\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x);\n maxY = Math.max(maxY, p.y);\n }\n\n for (let i = 0; i < ids.length; i++) {\n const tile = this._tiles[ids[i]];\n if (tile.holdingForFade()) {\n // Tiles held for fading are covered by tiles that are closer to ideal\n continue;\n }\n const tileID = tile.tileID;\n const scale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ);\n const queryPadding = maxPitchScaleFactor * tile.queryPadding * EXTENT / tile.tileSize / scale;\n\n const tileSpaceBounds = [\n tileID.getTilePoint(new MercatorCoordinate(minX, minY)),\n tileID.getTilePoint(new MercatorCoordinate(maxX, maxY))\n ];\n\n if (tileSpaceBounds[0].x - queryPadding < EXTENT && tileSpaceBounds[0].y - queryPadding < EXTENT &&\n tileSpaceBounds[1].x + queryPadding >= 0 && tileSpaceBounds[1].y + queryPadding >= 0) {\n\n const tileSpaceQueryGeometry: Array = queryGeometry.map((c) => tileID.getTilePoint(c));\n const tileSpaceCameraQueryGeometry = cameraQueryGeometry.map((c) => tileID.getTilePoint(c));\n\n tileResults.push({\n tile,\n tileID,\n queryGeometry: tileSpaceQueryGeometry,\n cameraQueryGeometry: tileSpaceCameraQueryGeometry,\n scale\n });\n }\n }\n\n return tileResults;\n }\n\n getVisibleCoordinates(symbolLayer?: boolean): Array {\n const coords = this.getRenderableIds(symbolLayer).map((id) => this._tiles[id].tileID);\n for (const coord of coords) {\n coord.posMatrix = this.transform.calculatePosMatrix(coord.toUnwrapped());\n }\n return coords;\n }\n\n hasTransition() {\n if (this._source.hasTransition()) {\n return true;\n }\n\n if (isRasterType(this._source.type)) {\n for (const id in this._tiles) {\n const tile = this._tiles[id];\n if (tile.fadeEndTime !== undefined && tile.fadeEndTime >= browser.now()) {\n return true;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Set the value of a particular state for a feature\n * @private\n */\n setFeatureState(sourceLayer?: string, featureId: number | string, state: Object) {\n sourceLayer = sourceLayer || '_geojsonTileLayer';\n this._state.updateState(sourceLayer, featureId, state);\n }\n\n /**\n * Resets the value of a particular state key for a feature\n * @private\n */\n removeFeatureState(sourceLayer?: string, featureId?: number | string, key?: string) {\n sourceLayer = sourceLayer || '_geojsonTileLayer';\n this._state.removeFeatureState(sourceLayer, featureId, key);\n }\n\n /**\n * Get the entire state object for a feature\n * @private\n */\n getFeatureState(sourceLayer?: string, featureId: number | string) {\n sourceLayer = sourceLayer || '_geojsonTileLayer';\n return this._state.getState(sourceLayer, featureId);\n }\n\n /**\n * Sets the set of keys that the tile depends on. This allows tiles to\n * be reloaded when their dependencies change.\n * @private\n */\n setDependencies(tileKey: string, namespace: string, dependencies: Array) {\n const tile = this._tiles[tileKey];\n if (tile) {\n tile.setDependencies(namespace, dependencies);\n }\n }\n\n /**\n * Reloads all tiles that depend on the given keys.\n * @private\n */\n reloadTilesForDependencies(namespaces: Array, keys: Array) {\n for (const id in this._tiles) {\n const tile = this._tiles[id];\n if (tile.hasDependency(namespaces, keys)) {\n this._reloadTile(id, 'reloading');\n }\n }\n this._cache.filter(tile => !tile.hasDependency(namespaces, keys));\n }\n}\n\nSourceCache.maxOverzooming = 10;\nSourceCache.maxUnderzooming = 3;\n\nfunction compareTileId(a: OverscaledTileID, b: OverscaledTileID): number {\n // Different copies of the world are sorted based on their distance to the center.\n // Wrap values are converted to unsigned distances by reserving odd number for copies\n // with negative wrap and even numbers for copies with positive wrap.\n const aWrap = Math.abs(a.wrap * 2) - +(a.wrap < 0);\n const bWrap = Math.abs(b.wrap * 2) - +(b.wrap < 0);\n return a.overscaledZ - b.overscaledZ || bWrap - aWrap || b.canonical.y - a.canonical.y || b.canonical.x - a.canonical.x;\n}\n\nfunction isRasterType(type) {\n return type === 'raster' || type === 'image' || type === 'video';\n}\n\nexport default SourceCache;\n","// @flow\n\nimport window from '../window';\nimport mapboxgl from '../../';\n\nimport type {WorkerInterface} from '../web_worker';\n\nexport default function (): WorkerInterface {\n return (new window.Worker(mapboxgl.workerUrl): any);\n}\n","// @flow\n\nimport WebWorker from './web_worker';\nimport type {WorkerInterface} from './web_worker';\nimport browser from './browser';\n\nexport const PRELOAD_POOL_ID = 'mapboxgl_preloaded_worker_pool';\n\n/**\n * Constructs a worker pool.\n * @private\n */\nexport default class WorkerPool {\n static workerCount: number;\n\n active: {[_: number | string]: boolean};\n workers: Array;\n\n constructor() {\n this.active = {};\n }\n\n acquire(mapId: number | string): Array {\n if (!this.workers) {\n // Lazily look up the value of mapboxgl.workerCount so that\n // client code has had a chance to set it.\n this.workers = [];\n while (this.workers.length < WorkerPool.workerCount) {\n this.workers.push(new WebWorker());\n }\n }\n\n this.active[mapId] = true;\n return this.workers.slice();\n }\n\n release(mapId: number | string) {\n delete this.active[mapId];\n if (this.numActive() === 0) {\n this.workers.forEach((w) => {\n w.terminate();\n });\n this.workers = (null: any);\n }\n }\n\n isPreloaded(): boolean {\n return !!this.active[PRELOAD_POOL_ID];\n }\n\n numActive(): number {\n return Object.keys(this.active).length;\n }\n}\n\nconst availableLogicalProcessors = Math.floor(browser.hardwareConcurrency / 2);\nWorkerPool.workerCount = Math.max(Math.min(availableLogicalProcessors, 6), 1);\n","// @flow\n\nimport WorkerPool, {PRELOAD_POOL_ID} from './worker_pool';\n\nlet globalWorkerPool;\n\n/**\n * Creates (if necessary) and returns the single, global WorkerPool instance\n * to be shared across each Map\n * @private\n */\nexport default function getGlobalWorkerPool () {\n if (!globalWorkerPool) {\n globalWorkerPool = new WorkerPool();\n }\n return globalWorkerPool;\n}\n\nexport function prewarm() {\n const workerPool = getGlobalWorkerPool();\n workerPool.acquire(PRELOAD_POOL_ID);\n}\n\nexport function clearPrewarmedResources() {\n const pool = globalWorkerPool;\n if (pool) {\n // Remove the pool only if all maps that referenced the preloaded global worker pool have been removed.\n if (pool.isPreloaded() && pool.numActive() === 1) {\n pool.release(PRELOAD_POOL_ID);\n globalWorkerPool = null;\n } else {\n console.warn('Could not clear WebWorkers since there are active Map instances that still reference it. The pre-warmed WebWorker pool can only be cleared when all map instances have been removed with map.remove()');\n }\n }\n}\n","\nexport default ['type', 'source', 'source-layer', 'minzoom', 'maxzoom', 'filter', 'layout'];\n","\nimport refProperties from './util/ref_properties';\n\nfunction deref(layer, parent) {\n const result = {};\n\n for (const k in layer) {\n if (k !== 'ref') {\n result[k] = layer[k];\n }\n }\n\n refProperties.forEach((k) => {\n if (k in parent) {\n result[k] = parent[k];\n }\n });\n\n return result;\n}\n\nexport default derefLayers;\n\n/**\n * Given an array of layers, some of which may contain `ref` properties\n * whose value is the `id` of another property, return a new array where\n * such layers have been augmented with the 'type', 'source', etc. properties\n * from the parent layer, and the `ref` property has been removed.\n *\n * The input is not modified. The output may contain references to portions\n * of the input.\n *\n * @private\n * @param {Array} layers\n * @returns {Array}\n */\nfunction derefLayers(layers) {\n layers = layers.slice();\n\n const map = Object.create(null);\n for (let i = 0; i < layers.length; i++) {\n map[layers[i].id] = layers[i];\n }\n\n for (let i = 0; i < layers.length; i++) {\n if ('ref' in layers[i]) {\n layers[i] = deref(layers[i], map[layers[i].ref]);\n }\n }\n\n return layers;\n}\n","\nimport isEqual from './util/deep_equal';\n\nconst operations = {\n\n /*\n * { command: 'setStyle', args: [stylesheet] }\n */\n setStyle: 'setStyle',\n\n /*\n * { command: 'addLayer', args: [layer, 'beforeLayerId'] }\n */\n addLayer: 'addLayer',\n\n /*\n * { command: 'removeLayer', args: ['layerId'] }\n */\n removeLayer: 'removeLayer',\n\n /*\n * { command: 'setPaintProperty', args: ['layerId', 'prop', value] }\n */\n setPaintProperty: 'setPaintProperty',\n\n /*\n * { command: 'setLayoutProperty', args: ['layerId', 'prop', value] }\n */\n setLayoutProperty: 'setLayoutProperty',\n\n /*\n * { command: 'setFilter', args: ['layerId', filter] }\n */\n setFilter: 'setFilter',\n\n /*\n * { command: 'addSource', args: ['sourceId', source] }\n */\n addSource: 'addSource',\n\n /*\n * { command: 'removeSource', args: ['sourceId'] }\n */\n removeSource: 'removeSource',\n\n /*\n * { command: 'setGeoJSONSourceData', args: ['sourceId', data] }\n */\n setGeoJSONSourceData: 'setGeoJSONSourceData',\n\n /*\n * { command: 'setLayerZoomRange', args: ['layerId', 0, 22] }\n */\n setLayerZoomRange: 'setLayerZoomRange',\n\n /*\n * { command: 'setLayerProperty', args: ['layerId', 'prop', value] }\n */\n setLayerProperty: 'setLayerProperty',\n\n /*\n * { command: 'setCenter', args: [[lon, lat]] }\n */\n setCenter: 'setCenter',\n\n /*\n * { command: 'setZoom', args: [zoom] }\n */\n setZoom: 'setZoom',\n\n /*\n * { command: 'setBearing', args: [bearing] }\n */\n setBearing: 'setBearing',\n\n /*\n * { command: 'setPitch', args: [pitch] }\n */\n setPitch: 'setPitch',\n\n /*\n * { command: 'setSprite', args: ['spriteUrl'] }\n */\n setSprite: 'setSprite',\n\n /*\n * { command: 'setGlyphs', args: ['glyphsUrl'] }\n */\n setGlyphs: 'setGlyphs',\n\n /*\n * { command: 'setTransition', args: [transition] }\n */\n setTransition: 'setTransition',\n\n /*\n * { command: 'setLighting', args: [lightProperties] }\n */\n setLight: 'setLight'\n\n};\n\nfunction addSource(sourceId, after, commands) {\n commands.push({command: operations.addSource, args: [sourceId, after[sourceId]]});\n}\n\nfunction removeSource(sourceId, commands, sourcesRemoved) {\n commands.push({command: operations.removeSource, args: [sourceId]});\n sourcesRemoved[sourceId] = true;\n}\n\nfunction updateSource(sourceId, after, commands, sourcesRemoved) {\n removeSource(sourceId, commands, sourcesRemoved);\n addSource(sourceId, after, commands);\n}\n\nfunction canUpdateGeoJSON(before, after, sourceId) {\n let prop;\n for (prop in before[sourceId]) {\n if (!before[sourceId].hasOwnProperty(prop)) continue;\n if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) {\n return false;\n }\n }\n for (prop in after[sourceId]) {\n if (!after[sourceId].hasOwnProperty(prop)) continue;\n if (prop !== 'data' && !isEqual(before[sourceId][prop], after[sourceId][prop])) {\n return false;\n }\n }\n return true;\n}\n\nfunction diffSources(before, after, commands, sourcesRemoved) {\n before = before || {};\n after = after || {};\n\n let sourceId;\n\n // look for sources to remove\n for (sourceId in before) {\n if (!before.hasOwnProperty(sourceId)) continue;\n if (!after.hasOwnProperty(sourceId)) {\n removeSource(sourceId, commands, sourcesRemoved);\n }\n }\n\n // look for sources to add/update\n for (sourceId in after) {\n if (!after.hasOwnProperty(sourceId)) continue;\n if (!before.hasOwnProperty(sourceId)) {\n addSource(sourceId, after, commands);\n } else if (!isEqual(before[sourceId], after[sourceId])) {\n if (before[sourceId].type === 'geojson' && after[sourceId].type === 'geojson' && canUpdateGeoJSON(before, after, sourceId)) {\n commands.push({command: operations.setGeoJSONSourceData, args: [sourceId, after[sourceId].data]});\n } else {\n // no update command, must remove then add\n updateSource(sourceId, after, commands, sourcesRemoved);\n }\n }\n }\n}\n\nfunction diffLayerPropertyChanges(before, after, commands, layerId, klass, command) {\n before = before || {};\n after = after || {};\n\n let prop;\n\n for (prop in before) {\n if (!before.hasOwnProperty(prop)) continue;\n if (!isEqual(before[prop], after[prop])) {\n commands.push({command, args: [layerId, prop, after[prop], klass]});\n }\n }\n for (prop in after) {\n if (!after.hasOwnProperty(prop) || before.hasOwnProperty(prop)) continue;\n if (!isEqual(before[prop], after[prop])) {\n commands.push({command, args: [layerId, prop, after[prop], klass]});\n }\n }\n}\n\nfunction pluckId(layer) {\n return layer.id;\n}\nfunction indexById(group, layer) {\n group[layer.id] = layer;\n return group;\n}\n\nfunction diffLayers(before, after, commands) {\n before = before || [];\n after = after || [];\n\n // order of layers by id\n const beforeOrder = before.map(pluckId);\n const afterOrder = after.map(pluckId);\n\n // index of layer by id\n const beforeIndex = before.reduce(indexById, {});\n const afterIndex = after.reduce(indexById, {});\n\n // track order of layers as if they have been mutated\n const tracker = beforeOrder.slice();\n\n // layers that have been added do not need to be diffed\n const clean = Object.create(null);\n\n let i, d, layerId, beforeLayer, afterLayer, insertBeforeLayerId, prop;\n\n // remove layers\n for (i = 0, d = 0; i < beforeOrder.length; i++) {\n layerId = beforeOrder[i];\n if (!afterIndex.hasOwnProperty(layerId)) {\n commands.push({command: operations.removeLayer, args: [layerId]});\n tracker.splice(tracker.indexOf(layerId, d), 1);\n } else {\n // limit where in tracker we need to look for a match\n d++;\n }\n }\n\n // add/reorder layers\n for (i = 0, d = 0; i < afterOrder.length; i++) {\n // work backwards as insert is before an existing layer\n layerId = afterOrder[afterOrder.length - 1 - i];\n\n if (tracker[tracker.length - 1 - i] === layerId) continue;\n\n if (beforeIndex.hasOwnProperty(layerId)) {\n // remove the layer before we insert at the correct position\n commands.push({command: operations.removeLayer, args: [layerId]});\n tracker.splice(tracker.lastIndexOf(layerId, tracker.length - d), 1);\n } else {\n // limit where in tracker we need to look for a match\n d++;\n }\n\n // add layer at correct position\n insertBeforeLayerId = tracker[tracker.length - i];\n commands.push({command: operations.addLayer, args: [afterIndex[layerId], insertBeforeLayerId]});\n tracker.splice(tracker.length - i, 0, layerId);\n clean[layerId] = true;\n }\n\n // update layers\n for (i = 0; i < afterOrder.length; i++) {\n layerId = afterOrder[i];\n beforeLayer = beforeIndex[layerId];\n afterLayer = afterIndex[layerId];\n\n // no need to update if previously added (new or moved)\n if (clean[layerId] || isEqual(beforeLayer, afterLayer)) continue;\n\n // If source, source-layer, or type have changes, then remove the layer\n // and add it back 'from scratch'.\n if (!isEqual(beforeLayer.source, afterLayer.source) || !isEqual(beforeLayer['source-layer'], afterLayer['source-layer']) || !isEqual(beforeLayer.type, afterLayer.type)) {\n commands.push({command: operations.removeLayer, args: [layerId]});\n // we add the layer back at the same position it was already in, so\n // there's no need to update the `tracker`\n insertBeforeLayerId = tracker[tracker.lastIndexOf(layerId) + 1];\n commands.push({command: operations.addLayer, args: [afterLayer, insertBeforeLayerId]});\n continue;\n }\n\n // layout, paint, filter, minzoom, maxzoom\n diffLayerPropertyChanges(beforeLayer.layout, afterLayer.layout, commands, layerId, null, operations.setLayoutProperty);\n diffLayerPropertyChanges(beforeLayer.paint, afterLayer.paint, commands, layerId, null, operations.setPaintProperty);\n if (!isEqual(beforeLayer.filter, afterLayer.filter)) {\n commands.push({command: operations.setFilter, args: [layerId, afterLayer.filter]});\n }\n if (!isEqual(beforeLayer.minzoom, afterLayer.minzoom) || !isEqual(beforeLayer.maxzoom, afterLayer.maxzoom)) {\n commands.push({command: operations.setLayerZoomRange, args: [layerId, afterLayer.minzoom, afterLayer.maxzoom]});\n }\n\n // handle all other layer props, including paint.*\n for (prop in beforeLayer) {\n if (!beforeLayer.hasOwnProperty(prop)) continue;\n if (prop === 'layout' || prop === 'paint' || prop === 'filter' ||\n prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue;\n if (prop.indexOf('paint.') === 0) {\n diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);\n } else if (!isEqual(beforeLayer[prop], afterLayer[prop])) {\n commands.push({command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]]});\n }\n }\n for (prop in afterLayer) {\n if (!afterLayer.hasOwnProperty(prop) || beforeLayer.hasOwnProperty(prop)) continue;\n if (prop === 'layout' || prop === 'paint' || prop === 'filter' ||\n prop === 'metadata' || prop === 'minzoom' || prop === 'maxzoom') continue;\n if (prop.indexOf('paint.') === 0) {\n diffLayerPropertyChanges(beforeLayer[prop], afterLayer[prop], commands, layerId, prop.slice(6), operations.setPaintProperty);\n } else if (!isEqual(beforeLayer[prop], afterLayer[prop])) {\n commands.push({command: operations.setLayerProperty, args: [layerId, prop, afterLayer[prop]]});\n }\n }\n }\n}\n\n/**\n * Diff two stylesheet\n *\n * Creates semanticly aware diffs that can easily be applied at runtime.\n * Operations produced by the diff closely resemble the mapbox-gl-js API. Any\n * error creating the diff will fall back to the 'setStyle' operation.\n *\n * Example diff:\n * [\n * { command: 'setConstant', args: ['@water', '#0000FF'] },\n * { command: 'setPaintProperty', args: ['background', 'background-color', 'black'] }\n * ]\n *\n * @private\n * @param {*} [before] stylesheet to compare from\n * @param {*} after stylesheet to compare to\n * @returns Array list of changes\n */\nfunction diffStyles(before, after) {\n if (!before) return [{command: operations.setStyle, args: [after]}];\n\n let commands = [];\n\n try {\n // Handle changes to top-level properties\n if (!isEqual(before.version, after.version)) {\n return [{command: operations.setStyle, args: [after]}];\n }\n if (!isEqual(before.center, after.center)) {\n commands.push({command: operations.setCenter, args: [after.center]});\n }\n if (!isEqual(before.zoom, after.zoom)) {\n commands.push({command: operations.setZoom, args: [after.zoom]});\n }\n if (!isEqual(before.bearing, after.bearing)) {\n commands.push({command: operations.setBearing, args: [after.bearing]});\n }\n if (!isEqual(before.pitch, after.pitch)) {\n commands.push({command: operations.setPitch, args: [after.pitch]});\n }\n if (!isEqual(before.sprite, after.sprite)) {\n commands.push({command: operations.setSprite, args: [after.sprite]});\n }\n if (!isEqual(before.glyphs, after.glyphs)) {\n commands.push({command: operations.setGlyphs, args: [after.glyphs]});\n }\n if (!isEqual(before.transition, after.transition)) {\n commands.push({command: operations.setTransition, args: [after.transition]});\n }\n if (!isEqual(before.light, after.light)) {\n commands.push({command: operations.setLight, args: [after.light]});\n }\n\n // Handle changes to `sources`\n // If a source is to be removed, we also--before the removeSource\n // command--need to remove all the style layers that depend on it.\n const sourcesRemoved = {};\n\n // First collect the {add,remove}Source commands\n const removeOrAddSourceCommands = [];\n diffSources(before.sources, after.sources, removeOrAddSourceCommands, sourcesRemoved);\n\n // Push a removeLayer command for each style layer that depends on a\n // source that's being removed.\n // Also, exclude any such layers them from the input to `diffLayers`\n // below, so that diffLayers produces the appropriate `addLayers`\n // command\n const beforeLayers = [];\n if (before.layers) {\n before.layers.forEach((layer) => {\n if (sourcesRemoved[layer.source]) {\n commands.push({command: operations.removeLayer, args: [layer.id]});\n } else {\n beforeLayers.push(layer);\n }\n });\n }\n commands = commands.concat(removeOrAddSourceCommands);\n\n // Handle changes to `layers`\n diffLayers(beforeLayers, after.layers, commands);\n\n } catch (e) {\n // fall back to setStyle\n console.warn('Unable to compute style diff:', e);\n commands = [{command: operations.setStyle, args: [after]}];\n }\n\n return commands;\n}\n\nexport default diffStyles;\nexport {operations};\n","// @flow\n\nimport {clamp} from '../util/util';\nimport Point from '@mapbox/point-geometry';\nimport assert from 'assert';\n\nclass PathInterpolator {\n points: Array;\n length: number;\n paddedLength: number;\n padding: number;\n _distances: Array;\n\n constructor(points_: ?Array, padding_: ?number) {\n this.reset(points_, padding_);\n }\n\n reset(points_: ?Array, padding_: ?number) {\n this.points = points_ || [];\n\n // Compute cumulative distance from first point to every other point in the segment.\n // Last entry in the array is total length of the path\n this._distances = [0.0];\n\n for (let i = 1; i < this.points.length; i++) {\n this._distances[i] = this._distances[i - 1] + this.points[i].dist(this.points[i - 1]);\n }\n\n this.length = this._distances[this._distances.length - 1];\n this.padding = Math.min(padding_ || 0, this.length * 0.5);\n this.paddedLength = this.length - this.padding * 2.0;\n }\n\n lerp(t: number): Point {\n assert(this.points.length > 0);\n if (this.points.length === 1) {\n return this.points[0];\n }\n\n t = clamp(t, 0, 1);\n\n // Find the correct segment [p0, p1] where p0 <= x < p1\n let currentIndex = 1;\n let distOfCurrentIdx = this._distances[currentIndex];\n const distToTarget = t * this.paddedLength + this.padding;\n\n while (distOfCurrentIdx < distToTarget && currentIndex < this._distances.length) {\n distOfCurrentIdx = this._distances[++currentIndex];\n }\n\n // Interpolate between the two points of the segment\n const idxOfPrevPoint = currentIndex - 1;\n const distOfPrevIdx = this._distances[idxOfPrevPoint];\n const segmentLength = distOfCurrentIdx - distOfPrevIdx;\n const segmentT = segmentLength > 0 ? (distToTarget - distOfPrevIdx) / segmentLength : 0;\n\n return this.points[idxOfPrevPoint].mult(1.0 - segmentT).add(this.points[currentIndex].mult(segmentT));\n }\n}\n\nexport default PathInterpolator;\n","// @flow\n\n/**\n * GridIndex is a data structure for testing the intersection of\n * circles and rectangles in a 2d plane.\n * It is optimized for rapid insertion and querying.\n * GridIndex splits the plane into a set of \"cells\" and keeps track\n * of which geometries intersect with each cell. At query time,\n * full geometry comparisons are only done for items that share\n * at least one cell. As long as the geometries are relatively\n * uniformly distributed across the plane, this greatly reduces\n * the number of comparisons necessary.\n *\n * @private\n */\nclass GridIndex {\n circleKeys: Array;\n boxKeys: Array;\n boxCells: Array>;\n circleCells: Array>;\n bboxes: Array;\n circles: Array;\n xCellCount: number;\n yCellCount: number;\n width: number;\n height: number;\n xScale: number;\n yScale: number;\n boxUid: number;\n circleUid: number;\n\n constructor (width: number, height: number, cellSize: number) {\n const boxCells = this.boxCells = [];\n const circleCells = this.circleCells = [];\n\n // More cells -> fewer geometries to check per cell, but items tend\n // to be split across more cells.\n // Sweet spot allows most small items to fit in one cell\n this.xCellCount = Math.ceil(width / cellSize);\n this.yCellCount = Math.ceil(height / cellSize);\n\n for (let i = 0; i < this.xCellCount * this.yCellCount; i++) {\n boxCells.push([]);\n circleCells.push([]);\n }\n this.circleKeys = [];\n this.boxKeys = [];\n this.bboxes = [];\n this.circles = [];\n\n this.width = width;\n this.height = height;\n this.xScale = this.xCellCount / width;\n this.yScale = this.yCellCount / height;\n this.boxUid = 0;\n this.circleUid = 0;\n }\n\n keysLength() {\n return this.boxKeys.length + this.circleKeys.length;\n }\n\n insert(key: any, x1: number, y1: number, x2: number, y2: number) {\n this._forEachCell(x1, y1, x2, y2, this._insertBoxCell, this.boxUid++);\n this.boxKeys.push(key);\n this.bboxes.push(x1);\n this.bboxes.push(y1);\n this.bboxes.push(x2);\n this.bboxes.push(y2);\n }\n\n insertCircle(key: any, x: number, y: number, radius: number) {\n // Insert circle into grid for all cells in the circumscribing square\n // It's more than necessary (by a factor of 4/PI), but fast to insert\n this._forEachCell(x - radius, y - radius, x + radius, y + radius, this._insertCircleCell, this.circleUid++);\n this.circleKeys.push(key);\n this.circles.push(x);\n this.circles.push(y);\n this.circles.push(radius);\n }\n\n _insertBoxCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number) {\n this.boxCells[cellIndex].push(uid);\n }\n\n _insertCircleCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, uid: number) {\n this.circleCells[cellIndex].push(uid);\n }\n\n _query(x1: number, y1: number, x2: number, y2: number, hitTest: boolean, predicate?: any) {\n if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) {\n return hitTest ? false : [];\n }\n const result = [];\n if (x1 <= 0 && y1 <= 0 && this.width <= x2 && this.height <= y2) {\n if (hitTest) {\n return true;\n }\n for (let boxUid = 0; boxUid < this.boxKeys.length; boxUid++) {\n result.push({\n key: this.boxKeys[boxUid],\n x1: this.bboxes[boxUid * 4],\n y1: this.bboxes[boxUid * 4 + 1],\n x2: this.bboxes[boxUid * 4 + 2],\n y2: this.bboxes[boxUid * 4 + 3]\n });\n }\n for (let circleUid = 0; circleUid < this.circleKeys.length; circleUid++) {\n const x = this.circles[circleUid * 3];\n const y = this.circles[circleUid * 3 + 1];\n const radius = this.circles[circleUid * 3 + 2];\n result.push({\n key: this.circleKeys[circleUid],\n x1: x - radius,\n y1: y - radius,\n x2: x + radius,\n y2: y + radius\n });\n }\n return predicate ? result.filter(predicate) : result;\n } else {\n const queryArgs = {\n hitTest,\n seenUids: {box: {}, circle: {}}\n };\n this._forEachCell(x1, y1, x2, y2, this._queryCell, result, queryArgs, predicate);\n return hitTest ? result.length > 0 : result;\n }\n }\n\n _queryCircle(x: number, y: number, radius: number, hitTest: boolean, predicate?: any) {\n // Insert circle into grid for all cells in the circumscribing square\n // It's more than necessary (by a factor of 4/PI), but fast to insert\n const x1 = x - radius;\n const x2 = x + radius;\n const y1 = y - radius;\n const y2 = y + radius;\n if (x2 < 0 || x1 > this.width || y2 < 0 || y1 > this.height) {\n return hitTest ? false : [];\n }\n\n // Box query early exits if the bounding box is larger than the grid, but we don't do\n // the equivalent calculation for circle queries because early exit is less likely\n // and the calculation is more expensive\n const result = [];\n const queryArgs = {\n hitTest,\n circle: {x, y, radius},\n seenUids: {box: {}, circle: {}}\n };\n this._forEachCell(x1, y1, x2, y2, this._queryCellCircle, result, queryArgs, predicate);\n return hitTest ? result.length > 0 : result;\n }\n\n query(x1: number, y1: number, x2: number, y2: number, predicate?: any): Array {\n return (this._query(x1, y1, x2, y2, false, predicate): any);\n }\n\n hitTest(x1: number, y1: number, x2: number, y2: number, predicate?: any): boolean {\n return (this._query(x1, y1, x2, y2, true, predicate): any);\n }\n\n hitTestCircle(x: number, y: number, radius: number, predicate?: any): boolean {\n return (this._queryCircle(x, y, radius, true, predicate): any);\n }\n\n _queryCell(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: any, queryArgs: any, predicate?: any) {\n const seenUids = queryArgs.seenUids;\n const boxCell = this.boxCells[cellIndex];\n if (boxCell !== null) {\n const bboxes = this.bboxes;\n for (const boxUid of boxCell) {\n if (!seenUids.box[boxUid]) {\n seenUids.box[boxUid] = true;\n const offset = boxUid * 4;\n if ((x1 <= bboxes[offset + 2]) &&\n (y1 <= bboxes[offset + 3]) &&\n (x2 >= bboxes[offset + 0]) &&\n (y2 >= bboxes[offset + 1]) &&\n (!predicate || predicate(this.boxKeys[boxUid]))) {\n if (queryArgs.hitTest) {\n result.push(true);\n return true;\n } else {\n result.push({\n key: this.boxKeys[boxUid],\n x1: bboxes[offset],\n y1: bboxes[offset + 1],\n x2: bboxes[offset + 2],\n y2: bboxes[offset + 3]\n });\n }\n }\n }\n }\n }\n const circleCell = this.circleCells[cellIndex];\n if (circleCell !== null) {\n const circles = this.circles;\n for (const circleUid of circleCell) {\n if (!seenUids.circle[circleUid]) {\n seenUids.circle[circleUid] = true;\n const offset = circleUid * 3;\n if (this._circleAndRectCollide(\n circles[offset],\n circles[offset + 1],\n circles[offset + 2],\n x1,\n y1,\n x2,\n y2) &&\n (!predicate || predicate(this.circleKeys[circleUid]))) {\n if (queryArgs.hitTest) {\n result.push(true);\n return true;\n } else {\n const x = circles[offset];\n const y = circles[offset + 1];\n const radius = circles[offset + 2];\n result.push({\n key: this.circleKeys[circleUid],\n x1: x - radius,\n y1: y - radius,\n x2: x + radius,\n y2: y + radius\n });\n }\n }\n }\n }\n }\n }\n\n _queryCellCircle(x1: number, y1: number, x2: number, y2: number, cellIndex: number, result: any, queryArgs: any, predicate?: any) {\n const circle = queryArgs.circle;\n const seenUids = queryArgs.seenUids;\n const boxCell = this.boxCells[cellIndex];\n if (boxCell !== null) {\n const bboxes = this.bboxes;\n for (const boxUid of boxCell) {\n if (!seenUids.box[boxUid]) {\n seenUids.box[boxUid] = true;\n const offset = boxUid * 4;\n if (this._circleAndRectCollide(\n circle.x,\n circle.y,\n circle.radius,\n bboxes[offset + 0],\n bboxes[offset + 1],\n bboxes[offset + 2],\n bboxes[offset + 3]) &&\n (!predicate || predicate(this.boxKeys[boxUid]))) {\n result.push(true);\n return true;\n }\n }\n }\n }\n\n const circleCell = this.circleCells[cellIndex];\n if (circleCell !== null) {\n const circles = this.circles;\n for (const circleUid of circleCell) {\n if (!seenUids.circle[circleUid]) {\n seenUids.circle[circleUid] = true;\n const offset = circleUid * 3;\n if (this._circlesCollide(\n circles[offset],\n circles[offset + 1],\n circles[offset + 2],\n circle.x,\n circle.y,\n circle.radius) &&\n (!predicate || predicate(this.circleKeys[circleUid]))) {\n result.push(true);\n return true;\n }\n }\n }\n }\n }\n\n _forEachCell(x1: number, y1: number, x2: number, y2: number, fn: any, arg1: any, arg2?: any, predicate?: any) {\n const cx1 = this._convertToXCellCoord(x1);\n const cy1 = this._convertToYCellCoord(y1);\n const cx2 = this._convertToXCellCoord(x2);\n const cy2 = this._convertToYCellCoord(y2);\n\n for (let x = cx1; x <= cx2; x++) {\n for (let y = cy1; y <= cy2; y++) {\n const cellIndex = this.xCellCount * y + x;\n if (fn.call(this, x1, y1, x2, y2, cellIndex, arg1, arg2, predicate)) return;\n }\n }\n }\n\n _convertToXCellCoord(x: number) {\n return Math.max(0, Math.min(this.xCellCount - 1, Math.floor(x * this.xScale)));\n }\n\n _convertToYCellCoord(y: number) {\n return Math.max(0, Math.min(this.yCellCount - 1, Math.floor(y * this.yScale)));\n }\n\n _circlesCollide(x1: number, y1: number, r1: number, x2: number, y2: number, r2: number): boolean {\n const dx = x2 - x1;\n const dy = y2 - y1;\n const bothRadii = r1 + r2;\n return (bothRadii * bothRadii) > (dx * dx + dy * dy);\n }\n\n _circleAndRectCollide(circleX: number, circleY: number, radius: number, x1: number, y1: number, x2: number, y2: number): boolean {\n const halfRectWidth = (x2 - x1) / 2;\n const distX = Math.abs(circleX - (x1 + halfRectWidth));\n if (distX > (halfRectWidth + radius)) {\n return false;\n }\n\n const halfRectHeight = (y2 - y1) / 2;\n const distY = Math.abs(circleY - (y1 + halfRectHeight));\n if (distY > (halfRectHeight + radius)) {\n return false;\n }\n\n if (distX <= halfRectWidth || distY <= halfRectHeight) {\n return true;\n }\n\n const dx = distX - halfRectWidth;\n const dy = distY - halfRectHeight;\n return (dx * dx + dy * dy <= (radius * radius));\n }\n}\n\nexport default GridIndex;\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport {mat4, vec4} from 'gl-matrix';\nimport * as symbolSize from './symbol_size';\nimport {addDynamicAttributes} from '../data/bucket/symbol_bucket';\n\nimport type Painter from '../render/painter';\nimport type Transform from '../geo/transform';\nimport type SymbolBucket from '../data/bucket/symbol_bucket';\nimport type {\n GlyphOffsetArray,\n SymbolLineVertexArray,\n SymbolDynamicLayoutArray\n} from '../data/array_types';\nimport {WritingMode} from '../symbol/shaping';\n\nexport {updateLineLabels, hideGlyphs, getLabelPlaneMatrix, getGlCoordMatrix, project, getPerspectiveRatio, placeFirstAndLastGlyph, placeGlyphAlongLine, xyTransformMat4};\n\n/*\n * # Overview of coordinate spaces\n *\n * ## Tile coordinate spaces\n * Each label has an anchor. Some labels have corresponding line geometries.\n * The points for both anchors and lines are stored in tile units. Each tile has it's own\n * coordinate space going from (0, 0) at the top left to (EXTENT, EXTENT) at the bottom right.\n *\n * ## GL coordinate space\n * At the end of everything, the vertex shader needs to produce a position in GL coordinate space,\n * which is (-1, 1) at the top left and (1, -1) in the bottom right.\n *\n * ## Map pixel coordinate spaces\n * Each tile has a pixel coordinate space. It's just the tile units scaled so that one unit is\n * whatever counts as 1 pixel at the current zoom.\n * This space is used for pitch-alignment=map, rotation-alignment=map\n *\n * ## Rotated map pixel coordinate spaces\n * Like the above, but rotated so axis of the space are aligned with the viewport instead of the tile.\n * This space is used for pitch-alignment=map, rotation-alignment=viewport\n *\n * ## Viewport pixel coordinate space\n * (0, 0) is at the top left of the canvas and (pixelWidth, pixelHeight) is at the bottom right corner\n * of the canvas. This space is used for pitch-alignment=viewport\n *\n *\n * # Vertex projection\n * It goes roughly like this:\n * 1. project the anchor and line from tile units into the correct label coordinate space\n * - map pixel space pitch-alignment=map rotation-alignment=map\n * - rotated map pixel space pitch-alignment=map rotation-alignment=viewport\n * - viewport pixel space pitch-alignment=viewport rotation-alignment=*\n * 2. if the label follows a line, find the point along the line that is the correct distance from the anchor.\n * 3. add the glyph's corner offset to the point from step 3\n * 4. convert from the label coordinate space to gl coordinates\n *\n * For horizontal labels we want to do step 1 in the shader for performance reasons (no cpu work).\n * This is what `u_label_plane_matrix` is used for.\n * For labels aligned with lines we have to steps 1 and 2 on the cpu since we need access to the line geometry.\n * This is what `updateLineLabels(...)` does.\n * Since the conversion is handled on the cpu we just set `u_label_plane_matrix` to an identity matrix.\n *\n * Steps 3 and 4 are done in the shaders for all labels.\n */\n\n/*\n * Returns a matrix for converting from tile units to the correct label coordinate space.\n */\nfunction getLabelPlaneMatrix(posMatrix: mat4,\n pitchWithMap: boolean,\n rotateWithMap: boolean,\n transform: Transform,\n pixelsToTileUnits: number) {\n const m = mat4.create();\n if (pitchWithMap) {\n mat4.scale(m, m, [1 / pixelsToTileUnits, 1 / pixelsToTileUnits, 1]);\n if (!rotateWithMap) {\n mat4.rotateZ(m, m, transform.angle);\n }\n } else {\n mat4.multiply(m, transform.labelPlaneMatrix, posMatrix);\n }\n return m;\n}\n\n/*\n * Returns a matrix for converting from the correct label coordinate space to gl coords.\n */\nfunction getGlCoordMatrix(posMatrix: mat4,\n pitchWithMap: boolean,\n rotateWithMap: boolean,\n transform: Transform,\n pixelsToTileUnits: number) {\n if (pitchWithMap) {\n const m = mat4.clone(posMatrix);\n mat4.scale(m, m, [pixelsToTileUnits, pixelsToTileUnits, 1]);\n if (!rotateWithMap) {\n mat4.rotateZ(m, m, -transform.angle);\n }\n return m;\n } else {\n return transform.glCoordMatrix;\n }\n}\n\nfunction project(point: Point, matrix: mat4) {\n const pos = [point.x, point.y, 0, 1];\n xyTransformMat4(pos, pos, matrix);\n const w = pos[3];\n return {\n point: new Point(pos[0] / w, pos[1] / w),\n signedDistanceFromCamera: w\n };\n}\n\nfunction getPerspectiveRatio(cameraToCenterDistance: number, signedDistanceFromCamera: number): number {\n return 0.5 + 0.5 * (cameraToCenterDistance / signedDistanceFromCamera);\n}\n\nfunction isVisible(anchorPos: [number, number, number, number],\n clippingBuffer: [number, number]) {\n const x = anchorPos[0] / anchorPos[3];\n const y = anchorPos[1] / anchorPos[3];\n const inPaddedViewport = (\n x >= -clippingBuffer[0] &&\n x <= clippingBuffer[0] &&\n y >= -clippingBuffer[1] &&\n y <= clippingBuffer[1]);\n return inPaddedViewport;\n}\n\n/*\n * Update the `dynamicLayoutVertexBuffer` for the buffer with the correct glyph positions for the current map view.\n * This is only run on labels that are aligned with lines. Horizontal labels are handled entirely in the shader.\n */\nfunction updateLineLabels(bucket: SymbolBucket,\n posMatrix: mat4,\n painter: Painter,\n isText: boolean,\n labelPlaneMatrix: mat4,\n glCoordMatrix: mat4,\n pitchWithMap: boolean,\n keepUpright: boolean) {\n\n const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData;\n const partiallyEvaluatedSize = symbolSize.evaluateSizeForZoom(sizeData, painter.transform.zoom);\n\n const clippingBuffer = [256 / painter.width * 2 + 1, 256 / painter.height * 2 + 1];\n\n const dynamicLayoutVertexArray = isText ?\n bucket.text.dynamicLayoutVertexArray :\n bucket.icon.dynamicLayoutVertexArray;\n dynamicLayoutVertexArray.clear();\n\n const lineVertexArray = bucket.lineVertexArray;\n const placedSymbols = isText ? bucket.text.placedSymbolArray : bucket.icon.placedSymbolArray;\n\n const aspectRatio = painter.transform.width / painter.transform.height;\n\n let useVertical = false;\n\n for (let s = 0; s < placedSymbols.length; s++) {\n const symbol: any = placedSymbols.get(s);\n\n // Don't do calculations for vertical glyphs unless the previous symbol was horizontal\n // and we determined that vertical glyphs were necessary.\n // Also don't do calculations for symbols that are collided and fully faded out\n if (symbol.hidden || symbol.writingMode === WritingMode.vertical && !useVertical) {\n hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);\n continue;\n }\n // Awkward... but we're counting on the paired \"vertical\" symbol coming immediately after its horizontal counterpart\n useVertical = false;\n\n const anchorPos = [symbol.anchorX, symbol.anchorY, 0, 1];\n vec4.transformMat4(anchorPos, anchorPos, posMatrix);\n\n // Don't bother calculating the correct point for invisible labels.\n if (!isVisible(anchorPos, clippingBuffer)) {\n hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);\n continue;\n }\n\n const cameraToAnchorDistance = anchorPos[3];\n const perspectiveRatio = getPerspectiveRatio(painter.transform.cameraToCenterDistance, cameraToAnchorDistance);\n\n const fontSize = symbolSize.evaluateSizeForFeature(sizeData, partiallyEvaluatedSize, symbol);\n const pitchScaledFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio;\n\n const tileAnchorPoint = new Point(symbol.anchorX, symbol.anchorY);\n const anchorPoint = project(tileAnchorPoint, labelPlaneMatrix).point;\n const projectionCache = {};\n\n const placeUnflipped: any = placeGlyphsAlongLine(symbol, pitchScaledFontSize, false /*unflipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix,\n bucket.glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio);\n\n useVertical = placeUnflipped.useVertical;\n\n if (placeUnflipped.notEnoughRoom || useVertical ||\n (placeUnflipped.needsFlipping &&\n placeGlyphsAlongLine(symbol, pitchScaledFontSize, true /*flipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix,\n bucket.glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio).notEnoughRoom)) {\n hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);\n }\n }\n\n if (isText) {\n bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray);\n } else {\n bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicLayoutVertexArray);\n }\n}\n\nfunction placeFirstAndLastGlyph(fontScale: number, glyphOffsetArray: GlyphOffsetArray, lineOffsetX: number, lineOffsetY: number, flip: boolean, anchorPoint: Point, tileAnchorPoint: Point, symbol: any, lineVertexArray: SymbolLineVertexArray, labelPlaneMatrix: mat4, projectionCache: any) {\n const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs;\n const lineStartIndex = symbol.lineStartIndex;\n const lineEndIndex = symbol.lineStartIndex + symbol.lineLength;\n\n const firstGlyphOffset = glyphOffsetArray.getoffsetX(symbol.glyphStartIndex);\n const lastGlyphOffset = glyphOffsetArray.getoffsetX(glyphEndIndex - 1);\n\n const firstPlacedGlyph = placeGlyphAlongLine(fontScale * firstGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment,\n lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache);\n if (!firstPlacedGlyph)\n return null;\n\n const lastPlacedGlyph = placeGlyphAlongLine(fontScale * lastGlyphOffset, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment,\n lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache);\n if (!lastPlacedGlyph)\n return null;\n\n return {first: firstPlacedGlyph, last: lastPlacedGlyph};\n}\n\nfunction requiresOrientationChange(writingMode, firstPoint, lastPoint, aspectRatio) {\n if (writingMode === WritingMode.horizontal) {\n // On top of choosing whether to flip, choose whether to render this version of the glyphs or the alternate\n // vertical glyphs. We can't just filter out vertical glyphs in the horizontal range because the horizontal\n // and vertical versions can have slightly different projections which could lead to angles where both or\n // neither showed.\n const rise = Math.abs(lastPoint.y - firstPoint.y);\n const run = Math.abs(lastPoint.x - firstPoint.x) * aspectRatio;\n if (rise > run) {\n return {useVertical: true};\n }\n }\n\n if (writingMode === WritingMode.vertical ? firstPoint.y < lastPoint.y : firstPoint.x > lastPoint.x) {\n // Includes \"horizontalOnly\" case for labels without vertical glyphs\n return {needsFlipping: true};\n }\n\n return null;\n}\n\nfunction placeGlyphsAlongLine(symbol, fontSize, flip, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix, glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio) {\n const fontScale = fontSize / 24;\n const lineOffsetX = symbol.lineOffsetX * fontScale;\n const lineOffsetY = symbol.lineOffsetY * fontScale;\n\n let placedGlyphs;\n if (symbol.numGlyphs > 1) {\n const glyphEndIndex = symbol.glyphStartIndex + symbol.numGlyphs;\n const lineStartIndex = symbol.lineStartIndex;\n const lineEndIndex = symbol.lineStartIndex + symbol.lineLength;\n\n // Place the first and the last glyph in the label first, so we can figure out\n // the overall orientation of the label and determine whether it needs to be flipped in keepUpright mode\n const firstAndLastGlyph = placeFirstAndLastGlyph(fontScale, glyphOffsetArray, lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol, lineVertexArray, labelPlaneMatrix, projectionCache);\n if (!firstAndLastGlyph) {\n return {notEnoughRoom: true};\n }\n const firstPoint = project(firstAndLastGlyph.first.point, glCoordMatrix).point;\n const lastPoint = project(firstAndLastGlyph.last.point, glCoordMatrix).point;\n\n if (keepUpright && !flip) {\n const orientationChange = requiresOrientationChange(symbol.writingMode, firstPoint, lastPoint, aspectRatio);\n if (orientationChange) {\n return orientationChange;\n }\n }\n\n placedGlyphs = [firstAndLastGlyph.first];\n for (let glyphIndex = symbol.glyphStartIndex + 1; glyphIndex < glyphEndIndex - 1; glyphIndex++) {\n // Since first and last glyph fit on the line, we're sure that the rest of the glyphs can be placed\n // $FlowFixMe\n placedGlyphs.push(placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(glyphIndex), lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment,\n lineStartIndex, lineEndIndex, lineVertexArray, labelPlaneMatrix, projectionCache));\n }\n placedGlyphs.push(firstAndLastGlyph.last);\n } else {\n // Only a single glyph to place\n // So, determine whether to flip based on projected angle of the line segment it's on\n if (keepUpright && !flip) {\n const a = project(tileAnchorPoint, posMatrix).point;\n const tileVertexIndex = (symbol.lineStartIndex + symbol.segment + 1);\n // $FlowFixMe\n const tileSegmentEnd = new Point(lineVertexArray.getx(tileVertexIndex), lineVertexArray.gety(tileVertexIndex));\n const projectedVertex = project(tileSegmentEnd, posMatrix);\n // We know the anchor will be in the viewport, but the end of the line segment may be\n // behind the plane of the camera, in which case we can use a point at any arbitrary (closer)\n // point on the segment.\n const b = (projectedVertex.signedDistanceFromCamera > 0) ?\n projectedVertex.point :\n projectTruncatedLineSegment(tileAnchorPoint, tileSegmentEnd, a, 1, posMatrix);\n\n const orientationChange = requiresOrientationChange(symbol.writingMode, a, b, aspectRatio);\n if (orientationChange) {\n return orientationChange;\n }\n }\n // $FlowFixMe\n const singleGlyph = placeGlyphAlongLine(fontScale * glyphOffsetArray.getoffsetX(symbol.glyphStartIndex), lineOffsetX, lineOffsetY, flip, anchorPoint, tileAnchorPoint, symbol.segment,\n symbol.lineStartIndex, symbol.lineStartIndex + symbol.lineLength, lineVertexArray, labelPlaneMatrix, projectionCache);\n if (!singleGlyph)\n return {notEnoughRoom: true};\n\n placedGlyphs = [singleGlyph];\n }\n\n for (const glyph: any of placedGlyphs) {\n addDynamicAttributes(dynamicLayoutVertexArray, glyph.point, glyph.angle);\n }\n return {};\n}\n\nfunction projectTruncatedLineSegment(previousTilePoint: Point, currentTilePoint: Point, previousProjectedPoint: Point, minimumLength: number, projectionMatrix: mat4) {\n // We are assuming \"previousTilePoint\" won't project to a point within one unit of the camera plane\n // If it did, that would mean our label extended all the way out from within the viewport to a (very distant)\n // point near the plane of the camera. We wouldn't be able to render the label anyway once it crossed the\n // plane of the camera.\n const projectedUnitVertex = project(previousTilePoint.add(previousTilePoint.sub(currentTilePoint)._unit()), projectionMatrix).point;\n const projectedUnitSegment = previousProjectedPoint.sub(projectedUnitVertex);\n\n return previousProjectedPoint.add(projectedUnitSegment._mult(minimumLength / projectedUnitSegment.mag()));\n}\n\nfunction placeGlyphAlongLine(offsetX: number,\n lineOffsetX: number,\n lineOffsetY: number,\n flip: boolean,\n anchorPoint: Point,\n tileAnchorPoint: Point,\n anchorSegment: number,\n lineStartIndex: number,\n lineEndIndex: number,\n lineVertexArray: SymbolLineVertexArray,\n labelPlaneMatrix: mat4,\n projectionCache: {[_: number]: Point}) {\n\n const combinedOffsetX = flip ?\n offsetX - lineOffsetX :\n offsetX + lineOffsetX;\n\n let dir = combinedOffsetX > 0 ? 1 : -1;\n\n let angle = 0;\n if (flip) {\n // The label needs to be flipped to keep text upright.\n // Iterate in the reverse direction.\n dir *= -1;\n angle = Math.PI;\n }\n\n if (dir < 0) angle += Math.PI;\n\n let currentIndex = dir > 0 ?\n lineStartIndex + anchorSegment :\n lineStartIndex + anchorSegment + 1;\n\n let current = anchorPoint;\n let prev = anchorPoint;\n let distanceToPrev = 0;\n let currentSegmentDistance = 0;\n const absOffsetX = Math.abs(combinedOffsetX);\n const pathVertices = [];\n\n while (distanceToPrev + currentSegmentDistance <= absOffsetX) {\n currentIndex += dir;\n\n // offset does not fit on the projected line\n if (currentIndex < lineStartIndex || currentIndex >= lineEndIndex)\n return null;\n\n prev = current;\n pathVertices.push(current);\n\n current = projectionCache[currentIndex];\n if (current === undefined) {\n const currentVertex = new Point(lineVertexArray.getx(currentIndex), lineVertexArray.gety(currentIndex));\n const projection = project(currentVertex, labelPlaneMatrix);\n if (projection.signedDistanceFromCamera > 0) {\n current = projectionCache[currentIndex] = projection.point;\n } else {\n // The vertex is behind the plane of the camera, so we can't project it\n // Instead, we'll create a vertex along the line that's far enough to include the glyph\n const previousLineVertexIndex = currentIndex - dir;\n const previousTilePoint = distanceToPrev === 0 ?\n tileAnchorPoint :\n new Point(lineVertexArray.getx(previousLineVertexIndex), lineVertexArray.gety(previousLineVertexIndex));\n // Don't cache because the new vertex might not be far enough out for future glyphs on the same segment\n current = projectTruncatedLineSegment(previousTilePoint, currentVertex, prev, absOffsetX - distanceToPrev + 1, labelPlaneMatrix);\n }\n }\n\n distanceToPrev += currentSegmentDistance;\n currentSegmentDistance = prev.dist(current);\n }\n\n // The point is on the current segment. Interpolate to find it.\n const segmentInterpolationT = (absOffsetX - distanceToPrev) / currentSegmentDistance;\n const prevToCurrent = current.sub(prev);\n const p = prevToCurrent.mult(segmentInterpolationT)._add(prev);\n\n // offset the point from the line to text-offset and icon-offset\n p._add(prevToCurrent._unit()._perp()._mult(lineOffsetY * dir));\n\n const segmentAngle = angle + Math.atan2(current.y - prev.y, current.x - prev.x);\n\n pathVertices.push(p);\n\n return {\n point: p,\n angle: segmentAngle,\n path: pathVertices\n };\n}\n\nconst hiddenGlyphAttributes = new Float32Array([-Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0, -Infinity, -Infinity, 0]);\n\n// Hide them by moving them offscreen. We still need to add them to the buffer\n// because the dynamic buffer is paired with a static buffer that doesn't get updated.\nfunction hideGlyphs(num: number, dynamicLayoutVertexArray: SymbolDynamicLayoutArray) {\n for (let i = 0; i < num; i++) {\n const offset = dynamicLayoutVertexArray.length;\n dynamicLayoutVertexArray.resize(offset + 4);\n // Since all hidden glyphs have the same attributes, we can build up the array faster with a single call to Float32Array.set\n // for each set of four vertices, instead of calling addDynamicAttributes for each vertex.\n dynamicLayoutVertexArray.float32.set(hiddenGlyphAttributes, offset * 3);\n }\n}\n\n// For line label layout, we're not using z output and our w input is always 1\n// This custom matrix transformation ignores those components to make projection faster\nfunction xyTransformMat4(out: vec4, a: vec4, m: mat4) {\n const x = a[0], y = a[1];\n out[0] = m[0] * x + m[4] * y + m[12];\n out[1] = m[1] * x + m[5] * y + m[13];\n out[3] = m[3] * x + m[7] * y + m[15];\n return out;\n}\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\nimport clipLine from './clip_line';\nimport PathInterpolator from './path_interpolator';\n\nimport * as intersectionTests from '../util/intersection_tests';\nimport Grid from './grid_index';\nimport {mat4} from 'gl-matrix';\nimport ONE_EM from '../symbol/one_em';\nimport assert from 'assert';\n\nimport * as projection from '../symbol/projection';\n\nimport type Transform from '../geo/transform';\nimport type {SingleCollisionBox} from '../data/bucket/symbol_bucket';\nimport type {\n GlyphOffsetArray,\n SymbolLineVertexArray\n} from '../data/array_types';\n\n// When a symbol crosses the edge that causes it to be included in\n// collision detection, it will cause changes in the symbols around\n// it. This constant specifies how many pixels to pad the edge of\n// the viewport for collision detection so that the bulk of the changes\n// occur offscreen. Making this constant greater increases label\n// stability, but it's expensive.\nconst viewportPadding = 100;\n\n/**\n * A collision index used to prevent symbols from overlapping. It keep tracks of\n * where previous symbols have been placed and is used to check if a new\n * symbol overlaps with any previously added symbols.\n *\n * There are two steps to insertion: first placeCollisionBox/Circles checks if\n * there's room for a symbol, then insertCollisionBox/Circles actually puts the\n * symbol in the index. The two step process allows paired symbols to be inserted\n * together even if they overlap.\n *\n * @private\n */\nclass CollisionIndex {\n grid: Grid;\n ignoredGrid: Grid;\n transform: Transform;\n pitchfactor: number;\n screenRightBoundary: number;\n screenBottomBoundary: number;\n gridRightBoundary: number;\n gridBottomBoundary: number;\n\n constructor(\n transform: Transform,\n grid: Grid = new Grid(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25),\n ignoredGrid: Grid = new Grid(transform.width + 2 * viewportPadding, transform.height + 2 * viewportPadding, 25)\n ) {\n this.transform = transform;\n\n this.grid = grid;\n this.ignoredGrid = ignoredGrid;\n this.pitchfactor = Math.cos(transform._pitch) * transform.cameraToCenterDistance;\n\n this.screenRightBoundary = transform.width + viewportPadding;\n this.screenBottomBoundary = transform.height + viewportPadding;\n this.gridRightBoundary = transform.width + 2 * viewportPadding;\n this.gridBottomBoundary = transform.height + 2 * viewportPadding;\n }\n\n placeCollisionBox(collisionBox: SingleCollisionBox, allowOverlap: boolean, textPixelRatio: number, posMatrix: mat4, collisionGroupPredicate?: any): { box: Array, offscreen: boolean } {\n const projectedPoint = this.projectAndGetPerspectiveRatio(posMatrix, collisionBox.anchorPointX, collisionBox.anchorPointY);\n const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio;\n const tlX = collisionBox.x1 * tileToViewport + projectedPoint.point.x;\n const tlY = collisionBox.y1 * tileToViewport + projectedPoint.point.y;\n const brX = collisionBox.x2 * tileToViewport + projectedPoint.point.x;\n const brY = collisionBox.y2 * tileToViewport + projectedPoint.point.y;\n\n if (!this.isInsideGrid(tlX, tlY, brX, brY) ||\n (!allowOverlap && this.grid.hitTest(tlX, tlY, brX, brY, collisionGroupPredicate))) {\n return {\n box: [],\n offscreen: false\n };\n }\n\n return {\n box: [tlX, tlY, brX, brY],\n offscreen: this.isOffscreen(tlX, tlY, brX, brY)\n };\n }\n\n placeCollisionCircles(allowOverlap: boolean,\n symbol: any,\n lineVertexArray: SymbolLineVertexArray,\n glyphOffsetArray: GlyphOffsetArray,\n fontSize: number,\n posMatrix: mat4,\n labelPlaneMatrix: mat4,\n labelToScreenMatrix?: mat4,\n showCollisionCircles: boolean,\n pitchWithMap: boolean,\n collisionGroupPredicate?: any,\n circlePixelDiameter: number,\n textPixelPadding: number): { circles: Array, offscreen: boolean, collisionDetected: boolean } {\n const placedCollisionCircles = [];\n\n const tileUnitAnchorPoint = new Point(symbol.anchorX, symbol.anchorY);\n const screenAnchorPoint = projection.project(tileUnitAnchorPoint, posMatrix);\n const perspectiveRatio = projection.getPerspectiveRatio(this.transform.cameraToCenterDistance, screenAnchorPoint.signedDistanceFromCamera);\n const labelPlaneFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio;\n const labelPlaneFontScale = labelPlaneFontSize / ONE_EM;\n\n const labelPlaneAnchorPoint = projection.project(tileUnitAnchorPoint, labelPlaneMatrix).point;\n\n const projectionCache = {};\n const lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale;\n const lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale;\n\n const firstAndLastGlyph = projection.placeFirstAndLastGlyph(\n labelPlaneFontScale,\n glyphOffsetArray,\n lineOffsetX,\n lineOffsetY,\n /*flip*/ false,\n labelPlaneAnchorPoint,\n tileUnitAnchorPoint,\n symbol,\n lineVertexArray,\n labelPlaneMatrix,\n projectionCache);\n\n let collisionDetected = false;\n let inGrid = false;\n let entirelyOffscreen = true;\n\n if (firstAndLastGlyph) {\n const radius = circlePixelDiameter * 0.5 * perspectiveRatio + textPixelPadding;\n const screenPlaneMin = new Point(-viewportPadding, -viewportPadding);\n const screenPlaneMax = new Point(this.screenRightBoundary, this.screenBottomBoundary);\n const interpolator = new PathInterpolator();\n\n // Construct a projected path from projected line vertices. Anchor points are ignored and removed\n const first = firstAndLastGlyph.first;\n const last = firstAndLastGlyph.last;\n\n let projectedPath = [];\n for (let i = first.path.length - 1; i >= 1; i--) {\n projectedPath.push(first.path[i]);\n }\n for (let i = 1; i < last.path.length; i++) {\n projectedPath.push(last.path[i]);\n }\n assert(projectedPath.length >= 2);\n\n // Tolerate a slightly longer distance than one diameter between two adjacent circles\n const circleDist = radius * 2.5;\n\n // The path might need to be converted into screen space if a pitched map is used as the label space\n if (labelToScreenMatrix) {\n const screenSpacePath = projectedPath.map(p => projection.project(p, labelToScreenMatrix));\n\n // Do not try to place collision circles if even of the points is behind the camera.\n // This is a plausible scenario with big camera pitch angles\n if (screenSpacePath.some(point => point.signedDistanceFromCamera <= 0)) {\n projectedPath = [];\n } else {\n projectedPath = screenSpacePath.map(p => p.point);\n }\n }\n\n let segments = [];\n\n if (projectedPath.length > 0) {\n // Quickly check if the path is fully inside or outside of the padded collision region.\n // For overlapping paths we'll only create collision circles for the visible segments\n const minPoint = projectedPath[0].clone();\n const maxPoint = projectedPath[0].clone();\n\n for (let i = 1; i < projectedPath.length; i++) {\n minPoint.x = Math.min(minPoint.x, projectedPath[i].x);\n minPoint.y = Math.min(minPoint.y, projectedPath[i].y);\n maxPoint.x = Math.max(maxPoint.x, projectedPath[i].x);\n maxPoint.y = Math.max(maxPoint.y, projectedPath[i].y);\n }\n\n if (minPoint.x >= screenPlaneMin.x && maxPoint.x <= screenPlaneMax.x &&\n minPoint.y >= screenPlaneMin.y && maxPoint.y <= screenPlaneMax.y) {\n // Quad fully visible\n segments = [projectedPath];\n } else if (maxPoint.x < screenPlaneMin.x || minPoint.x > screenPlaneMax.x ||\n maxPoint.y < screenPlaneMin.y || minPoint.y > screenPlaneMax.y) {\n // Not visible\n segments = [];\n } else {\n segments = clipLine([projectedPath], screenPlaneMin.x, screenPlaneMin.y, screenPlaneMax.x, screenPlaneMax.y);\n }\n }\n\n for (const seg of segments) {\n // interpolate positions for collision circles. Add a small padding to both ends of the segment\n assert(seg.length > 0);\n interpolator.reset(seg, radius * 0.25);\n\n let numCircles = 0;\n\n if (interpolator.length <= 0.5 * radius) {\n numCircles = 1;\n } else {\n numCircles = Math.ceil(interpolator.paddedLength / circleDist) + 1;\n }\n\n for (let i = 0; i < numCircles; i++) {\n const t = i / Math.max(numCircles - 1, 1);\n const circlePosition = interpolator.lerp(t);\n\n // add viewport padding to the position and perform initial collision check\n const centerX = circlePosition.x + viewportPadding;\n const centerY = circlePosition.y + viewportPadding;\n\n placedCollisionCircles.push(centerX, centerY, radius, 0);\n\n const x1 = centerX - radius;\n const y1 = centerY - radius;\n const x2 = centerX + radius;\n const y2 = centerY + radius;\n\n entirelyOffscreen = entirelyOffscreen && this.isOffscreen(x1, y1, x2, y2);\n inGrid = inGrid || this.isInsideGrid(x1, y1, x2, y2);\n\n if (!allowOverlap) {\n if (this.grid.hitTestCircle(centerX, centerY, radius, collisionGroupPredicate)) {\n // Don't early exit if we're showing the debug circles because we still want to calculate\n // which circles are in use\n collisionDetected = true;\n if (!showCollisionCircles) {\n return {\n circles: [],\n offscreen: false,\n collisionDetected\n };\n }\n }\n }\n }\n }\n }\n\n return {\n circles: ((!showCollisionCircles && collisionDetected) || !inGrid) ? [] : placedCollisionCircles,\n offscreen: entirelyOffscreen,\n collisionDetected\n };\n }\n\n /**\n * Because the geometries in the CollisionIndex are an approximation of the shape of\n * symbols on the map, we use the CollisionIndex to look up the symbol part of\n * `queryRenderedFeatures`.\n *\n * @private\n */\n queryRenderedSymbols(viewportQueryGeometry: Array) {\n if (viewportQueryGeometry.length === 0 || (this.grid.keysLength() === 0 && this.ignoredGrid.keysLength() === 0)) {\n return {};\n }\n\n const query = [];\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const point of viewportQueryGeometry) {\n const gridPoint = new Point(point.x + viewportPadding, point.y + viewportPadding);\n minX = Math.min(minX, gridPoint.x);\n minY = Math.min(minY, gridPoint.y);\n maxX = Math.max(maxX, gridPoint.x);\n maxY = Math.max(maxY, gridPoint.y);\n query.push(gridPoint);\n }\n\n const features = this.grid.query(minX, minY, maxX, maxY)\n .concat(this.ignoredGrid.query(minX, minY, maxX, maxY));\n\n const seenFeatures = {};\n const result = {};\n\n for (const feature of features) {\n const featureKey = feature.key;\n // Skip already seen features.\n if (seenFeatures[featureKey.bucketInstanceId] === undefined) {\n seenFeatures[featureKey.bucketInstanceId] = {};\n }\n if (seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex]) {\n continue;\n }\n\n // Check if query intersects with the feature box\n // \"Collision Circles\" for line labels are treated as boxes here\n // Since there's no actual collision taking place, the circle vs. square\n // distinction doesn't matter as much, and box geometry is easier\n // to work with.\n const bbox = [\n new Point(feature.x1, feature.y1),\n new Point(feature.x2, feature.y1),\n new Point(feature.x2, feature.y2),\n new Point(feature.x1, feature.y2)\n ];\n if (!intersectionTests.polygonIntersectsPolygon(query, bbox)) {\n continue;\n }\n\n seenFeatures[featureKey.bucketInstanceId][featureKey.featureIndex] = true;\n if (result[featureKey.bucketInstanceId] === undefined) {\n result[featureKey.bucketInstanceId] = [];\n }\n result[featureKey.bucketInstanceId].push(featureKey.featureIndex);\n }\n\n return result;\n }\n\n insertCollisionBox(collisionBox: Array, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number) {\n const grid = ignorePlacement ? this.ignoredGrid : this.grid;\n\n const key = {bucketInstanceId, featureIndex, collisionGroupID};\n grid.insert(key, collisionBox[0], collisionBox[1], collisionBox[2], collisionBox[3]);\n }\n\n insertCollisionCircles(collisionCircles: Array, ignorePlacement: boolean, bucketInstanceId: number, featureIndex: number, collisionGroupID: number) {\n const grid = ignorePlacement ? this.ignoredGrid : this.grid;\n\n const key = {bucketInstanceId, featureIndex, collisionGroupID};\n for (let k = 0; k < collisionCircles.length; k += 4) {\n grid.insertCircle(key, collisionCircles[k], collisionCircles[k + 1], collisionCircles[k + 2]);\n }\n }\n\n projectAndGetPerspectiveRatio(posMatrix: mat4, x: number, y: number) {\n const p = [x, y, 0, 1];\n projection.xyTransformMat4(p, p, posMatrix);\n const a = new Point(\n (((p[0] / p[3] + 1) / 2) * this.transform.width) + viewportPadding,\n (((-p[1] / p[3] + 1) / 2) * this.transform.height) + viewportPadding\n );\n return {\n point: a,\n // See perspective ratio comment in symbol_sdf.vertex\n // We're doing collision detection in viewport space so we need\n // to scale down boxes in the distance\n perspectiveRatio: 0.5 + 0.5 * (this.transform.cameraToCenterDistance / p[3])\n };\n }\n\n isOffscreen(x1: number, y1: number, x2: number, y2: number) {\n return x2 < viewportPadding || x1 >= this.screenRightBoundary || y2 < viewportPadding || y1 > this.screenBottomBoundary;\n }\n\n isInsideGrid(x1: number, y1: number, x2: number, y2: number) {\n return x2 >= 0 && x1 < this.gridRightBoundary && y2 >= 0 && y1 < this.gridBottomBoundary;\n }\n\n /*\n * Returns a matrix for transforming collision shapes to viewport coordinate space.\n * Use this function to render e.g. collision circles on the screen.\n * example transformation: clipPos = glCoordMatrix * viewportMatrix * circle_pos\n */\n getViewportMatrix(): mat4 {\n const m = mat4.identity([]);\n mat4.translate(m, m, [-viewportPadding, -viewportPadding, 0.0]);\n return m;\n }\n}\n\nexport default CollisionIndex;\n","// @flow\n\nimport EXTENT from '../data/extent';\n\nimport type {OverscaledTileID} from './tile_id';\n\n/**\n * Converts a pixel value at a the given zoom level to tile units.\n *\n * The shaders mostly calculate everything in tile units so style\n * properties need to be converted from pixels to tile units using this.\n *\n * For example, a translation by 30 pixels at zoom 6.5 will be a\n * translation by pixelsToTileUnits(30, 6.5) tile units.\n *\n * @returns value in tile units\n * @private\n */\nexport default function(tile: {tileID: OverscaledTileID, tileSize: number}, pixelValue: number, z: number): number {\n return pixelValue * (EXTENT / (tile.tileSize * Math.pow(2, z - tile.tileID.overscaledZ)));\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 CollisionIndex from './collision_index';\nimport EXTENT from '../data/extent';\nimport * as symbolSize from './symbol_size';\nimport * as projection from './projection';\nimport {getAnchorJustification, evaluateVariableOffset} from './symbol_layout';\nimport {getAnchorAlignment, WritingMode} from './shaping';\nimport {mat4} from 'gl-matrix';\nimport assert from 'assert';\nimport pixelsToTileUnits from '../source/pixels_to_tile_units';\nimport Point from '@mapbox/point-geometry';\nimport type Transform from '../geo/transform';\nimport type StyleLayer from '../style/style_layer';\n\nimport type Tile from '../source/tile';\nimport type SymbolBucket, {CollisionArrays, SingleCollisionBox} from '../data/bucket/symbol_bucket';\nimport type {CollisionBoxArray, CollisionVertexArray, SymbolInstance} from '../data/array_types';\nimport type FeatureIndex from '../data/feature_index';\nimport type {OverscaledTileID} from '../source/tile_id';\nimport type {TextAnchor} from './symbol_layout';\n\nclass OpacityState {\n opacity: number;\n placed: boolean;\n constructor(prevState: ?OpacityState, increment: number, placed: boolean, skipFade: ?boolean) {\n if (prevState) {\n this.opacity = Math.max(0, Math.min(1, prevState.opacity + (prevState.placed ? increment : -increment)));\n } else {\n this.opacity = (skipFade && placed) ? 1 : 0;\n }\n this.placed = placed;\n }\n isHidden() {\n return this.opacity === 0 && !this.placed;\n }\n}\n\nclass JointOpacityState {\n text: OpacityState;\n icon: OpacityState;\n constructor(prevState: ?JointOpacityState, increment: number, placedText: boolean, placedIcon: boolean, skipFade: ?boolean) {\n this.text = new OpacityState(prevState ? prevState.text : null, increment, placedText, skipFade);\n this.icon = new OpacityState(prevState ? prevState.icon : null, increment, placedIcon, skipFade);\n }\n isHidden() {\n return this.text.isHidden() && this.icon.isHidden();\n }\n}\n\nclass JointPlacement {\n text: boolean;\n icon: boolean;\n // skipFade = outside viewport, but within CollisionIndex::viewportPadding px of the edge\n // Because these symbols aren't onscreen yet, we can skip the \"fade in\" animation,\n // and if a subsequent viewport change brings them into view, they'll be fully\n // visible right away.\n skipFade: boolean;\n constructor(text: boolean, icon: boolean, skipFade: boolean) {\n this.text = text;\n this.icon = icon;\n this.skipFade = skipFade;\n }\n}\n\nclass CollisionCircleArray {\n // Stores collision circles and placement matrices of a bucket for debug rendering.\n invProjMatrix: mat4;\n viewportMatrix: mat4;\n circles: Array;\n\n constructor() {\n this.invProjMatrix = mat4.create();\n this.viewportMatrix = mat4.create();\n this.circles = [];\n }\n}\n\nexport class RetainedQueryData {\n bucketInstanceId: number;\n featureIndex: FeatureIndex;\n sourceLayerIndex: number;\n bucketIndex: number;\n tileID: OverscaledTileID;\n featureSortOrder: ?Array\n constructor(bucketInstanceId: number,\n featureIndex: FeatureIndex,\n sourceLayerIndex: number,\n bucketIndex: number,\n tileID: OverscaledTileID) {\n this.bucketInstanceId = bucketInstanceId;\n this.featureIndex = featureIndex;\n this.sourceLayerIndex = sourceLayerIndex;\n this.bucketIndex = bucketIndex;\n this.tileID = tileID;\n }\n}\n\ntype CollisionGroup = { ID: number, predicate?: any };\n\nclass CollisionGroups {\n collisionGroups: {[groupName: string]: CollisionGroup};\n maxGroupID: number;\n crossSourceCollisions: boolean;\n\n constructor(crossSourceCollisions: boolean) {\n this.crossSourceCollisions = crossSourceCollisions;\n this.maxGroupID = 0;\n this.collisionGroups = {};\n }\n\n get(sourceID: string) {\n // The predicate/groupID mechanism allows for arbitrary grouping,\n // but the current interface defines one source == one group when\n // crossSourceCollisions == true.\n if (!this.crossSourceCollisions) {\n if (!this.collisionGroups[sourceID]) {\n const nextGroupID = ++this.maxGroupID;\n this.collisionGroups[sourceID] = {\n ID: nextGroupID,\n predicate: (key) => {\n return key.collisionGroupID === nextGroupID;\n }\n };\n }\n return this.collisionGroups[sourceID];\n } else {\n return {ID: 0, predicate: null};\n }\n }\n}\n\nfunction calculateVariableLayoutShift(anchor: TextAnchor, width: number, height: number, textOffset: [number, number], textBoxScale: number): Point {\n const {horizontalAlign, verticalAlign} = getAnchorAlignment(anchor);\n const shiftX = -(horizontalAlign - 0.5) * width;\n const shiftY = -(verticalAlign - 0.5) * height;\n const offset = evaluateVariableOffset(anchor, textOffset);\n return new Point(\n shiftX + offset[0] * textBoxScale,\n shiftY + offset[1] * textBoxScale\n );\n}\n\nfunction shiftVariableCollisionBox(collisionBox: SingleCollisionBox,\n shiftX: number, shiftY: number,\n rotateWithMap: boolean, pitchWithMap: boolean,\n angle: number) {\n const {x1, x2, y1, y2, anchorPointX, anchorPointY} = collisionBox;\n const rotatedOffset = new Point(shiftX, shiftY);\n if (rotateWithMap) {\n rotatedOffset._rotate(pitchWithMap ? angle : -angle);\n }\n return {\n x1: x1 + rotatedOffset.x,\n y1: y1 + rotatedOffset.y,\n x2: x2 + rotatedOffset.x,\n y2: y2 + rotatedOffset.y,\n // symbol anchor point stays the same regardless of text-anchor\n anchorPointX,\n anchorPointY\n };\n}\n\nexport type VariableOffset = {\n textOffset: [number, number],\n width: number,\n height: number,\n anchor: TextAnchor,\n textBoxScale: number,\n prevAnchor?: TextAnchor\n};\n\ntype TileLayerParameters = {\n bucket: SymbolBucket,\n layout: any,\n posMatrix: mat4,\n textLabelPlaneMatrix: mat4,\n labelToScreenMatrix: mat4,\n scale: number,\n textPixelRatio: number,\n holdingForFade: boolean,\n collisionBoxArray: ?CollisionBoxArray,\n partiallyEvaluatedTextSize: any,\n collisionGroup: any\n};\n\nexport type BucketPart = {\n sortKey?: number | void,\n symbolInstanceStart: number,\n symbolInstanceEnd: number,\n parameters: TileLayerParameters\n};\n\nexport type CrossTileID = string | number;\n\nexport class Placement {\n transform: Transform;\n collisionIndex: CollisionIndex;\n placements: { [_: CrossTileID]: JointPlacement };\n opacities: { [_: CrossTileID]: JointOpacityState };\n variableOffsets: {[_: CrossTileID]: VariableOffset };\n placedOrientations: {[_: CrossTileID]: number };\n commitTime: number;\n prevZoomAdjustment: number;\n lastPlacementChangeTime: number;\n stale: boolean;\n fadeDuration: number;\n retainedQueryData: {[_: number]: RetainedQueryData};\n collisionGroups: CollisionGroups;\n prevPlacement: ?Placement;\n zoomAtLastRecencyCheck: number;\n collisionCircleArrays: {[any]: CollisionCircleArray};\n\n constructor(transform: Transform, fadeDuration: number, crossSourceCollisions: boolean, prevPlacement?: Placement) {\n this.transform = transform.clone();\n this.collisionIndex = new CollisionIndex(this.transform);\n this.placements = {};\n this.opacities = {};\n this.variableOffsets = {};\n this.stale = false;\n this.commitTime = 0;\n this.fadeDuration = fadeDuration;\n this.retainedQueryData = {};\n this.collisionGroups = new CollisionGroups(crossSourceCollisions);\n this.collisionCircleArrays = {};\n\n this.prevPlacement = prevPlacement;\n if (prevPlacement) {\n prevPlacement.prevPlacement = undefined; // Only hold on to one placement back\n }\n\n this.placedOrientations = {};\n }\n\n getBucketParts(results: Array, styleLayer: StyleLayer, tile: Tile, sortAcrossTiles: boolean) {\n const symbolBucket = ((tile.getBucket(styleLayer): any): SymbolBucket);\n const bucketFeatureIndex = tile.latestFeatureIndex;\n if (!symbolBucket || !bucketFeatureIndex || styleLayer.id !== symbolBucket.layerIds[0])\n return;\n\n const collisionBoxArray = tile.collisionBoxArray;\n\n const layout = symbolBucket.layers[0].layout;\n\n const scale = Math.pow(2, this.transform.zoom - tile.tileID.overscaledZ);\n const textPixelRatio = tile.tileSize / EXTENT;\n\n const posMatrix = this.transform.calculatePosMatrix(tile.tileID.toUnwrapped());\n\n const pitchWithMap = layout.get('text-pitch-alignment') === 'map';\n const rotateWithMap = layout.get('text-rotation-alignment') === 'map';\n const pixelsToTiles = pixelsToTileUnits(tile, 1, this.transform.zoom);\n\n const textLabelPlaneMatrix = projection.getLabelPlaneMatrix(posMatrix,\n pitchWithMap,\n rotateWithMap,\n this.transform,\n pixelsToTiles);\n\n let labelToScreenMatrix = null;\n\n if (pitchWithMap) {\n const glMatrix = projection.getGlCoordMatrix(\n posMatrix,\n pitchWithMap,\n rotateWithMap,\n this.transform,\n pixelsToTiles);\n\n labelToScreenMatrix = mat4.multiply([], this.transform.labelPlaneMatrix, glMatrix);\n }\n\n // As long as this placement lives, we have to hold onto this bucket's\n // matching FeatureIndex/data for querying purposes\n this.retainedQueryData[symbolBucket.bucketInstanceId] = new RetainedQueryData(\n symbolBucket.bucketInstanceId,\n bucketFeatureIndex,\n symbolBucket.sourceLayerIndex,\n symbolBucket.index,\n tile.tileID\n );\n\n const parameters = {\n bucket: symbolBucket,\n layout,\n posMatrix,\n textLabelPlaneMatrix,\n labelToScreenMatrix,\n scale,\n textPixelRatio,\n holdingForFade: tile.holdingForFade(),\n collisionBoxArray,\n partiallyEvaluatedTextSize: symbolSize.evaluateSizeForZoom(symbolBucket.textSizeData, this.transform.zoom),\n collisionGroup: this.collisionGroups.get(symbolBucket.sourceID)\n };\n\n if (sortAcrossTiles) {\n for (const range of symbolBucket.sortKeyRanges) {\n const {sortKey, symbolInstanceStart, symbolInstanceEnd} = range;\n results.push({sortKey, symbolInstanceStart, symbolInstanceEnd, parameters});\n }\n } else {\n results.push({\n symbolInstanceStart: 0,\n symbolInstanceEnd: symbolBucket.symbolInstances.length,\n parameters\n });\n }\n }\n\n attemptAnchorPlacement(anchor: TextAnchor, textBox: SingleCollisionBox, width: number, height: number,\n textBoxScale: number, rotateWithMap: boolean,\n pitchWithMap: boolean, textPixelRatio: number, posMatrix: mat4, collisionGroup: CollisionGroup,\n textAllowOverlap: boolean, symbolInstance: SymbolInstance, bucket: SymbolBucket, orientation: number, iconBox: ?SingleCollisionBox): ?{ shift: Point, placedGlyphBoxes: { box: Array, offscreen: boolean } } {\n\n const textOffset = [symbolInstance.textOffset0, symbolInstance.textOffset1];\n const shift = calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale);\n\n const placedGlyphBoxes = this.collisionIndex.placeCollisionBox(\n shiftVariableCollisionBox(\n textBox, shift.x, shift.y,\n rotateWithMap, pitchWithMap, this.transform.angle),\n textAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate);\n\n if (iconBox) {\n const placedIconBoxes = this.collisionIndex.placeCollisionBox(\n shiftVariableCollisionBox(\n iconBox, shift.x, shift.y,\n rotateWithMap, pitchWithMap, this.transform.angle),\n textAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate);\n if (placedIconBoxes.box.length === 0) return;\n }\n\n if (placedGlyphBoxes.box.length > 0) {\n let prevAnchor;\n // If this label was placed in the previous placement, record the anchor position\n // to allow us to animate the transition\n if (this.prevPlacement &&\n this.prevPlacement.variableOffsets[symbolInstance.crossTileID] &&\n this.prevPlacement.placements[symbolInstance.crossTileID] &&\n this.prevPlacement.placements[symbolInstance.crossTileID].text) {\n prevAnchor = this.prevPlacement.variableOffsets[symbolInstance.crossTileID].anchor;\n }\n assert(symbolInstance.crossTileID !== 0);\n this.variableOffsets[symbolInstance.crossTileID] = {\n textOffset,\n width,\n height,\n anchor,\n textBoxScale,\n prevAnchor\n };\n this.markUsedJustification(bucket, anchor, symbolInstance, orientation);\n\n if (bucket.allowVerticalPlacement) {\n this.markUsedOrientation(bucket, orientation, symbolInstance);\n this.placedOrientations[symbolInstance.crossTileID] = orientation;\n }\n\n return {shift, placedGlyphBoxes};\n }\n }\n\n placeLayerBucketPart(bucketPart: Object, seenCrossTileIDs: { [string | number]: boolean }, showCollisionBoxes: boolean) {\n\n const {\n bucket,\n layout,\n posMatrix,\n textLabelPlaneMatrix,\n labelToScreenMatrix,\n textPixelRatio,\n holdingForFade,\n collisionBoxArray,\n partiallyEvaluatedTextSize,\n collisionGroup\n } = bucketPart.parameters;\n\n const textOptional = layout.get('text-optional');\n const iconOptional = layout.get('icon-optional');\n const textAllowOverlap = layout.get('text-allow-overlap');\n const iconAllowOverlap = layout.get('icon-allow-overlap');\n const rotateWithMap = layout.get('text-rotation-alignment') === 'map';\n const pitchWithMap = layout.get('text-pitch-alignment') === 'map';\n const hasIconTextFit = layout.get('icon-text-fit') !== 'none';\n const zOrderByViewportY = layout.get('symbol-z-order') === 'viewport-y';\n\n // This logic is similar to the \"defaultOpacityState\" logic below in updateBucketOpacities\n // If we know a symbol is always supposed to show, force it to be marked visible even if\n // it wasn't placed into the collision index (because some or all of it was outside the range\n // of the collision grid).\n // There is a subtle edge case here we're accepting:\n // Symbol A has text-allow-overlap: true, icon-allow-overlap: true, icon-optional: false\n // A's icon is outside the grid, so doesn't get placed\n // A's text would be inside grid, but doesn't get placed because of icon-optional: false\n // We still show A because of the allow-overlap settings.\n // Symbol B has allow-overlap: false, and gets placed where A's text would be\n // On panning in, there is a short period when Symbol B and Symbol A will overlap\n // This is the reverse of our normal policy of \"fade in on pan\", but should look like any other\n // collision and hopefully not be too noticeable.\n // See https://github.com/mapbox/mapbox-gl-js/issues/7172\n const alwaysShowText = textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || iconOptional);\n const alwaysShowIcon = iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || textOptional);\n\n if (!bucket.collisionArrays && collisionBoxArray) {\n bucket.deserializeCollisionBoxes(collisionBoxArray);\n }\n\n const placeSymbol = (symbolInstance: SymbolInstance, collisionArrays: CollisionArrays) => {\n if (seenCrossTileIDs[symbolInstance.crossTileID]) return;\n if (holdingForFade) {\n // Mark all symbols from this tile as \"not placed\", but don't add to seenCrossTileIDs, because we don't\n // know yet if we have a duplicate in a parent tile that _should_ be placed.\n this.placements[symbolInstance.crossTileID] = new JointPlacement(false, false, false);\n return;\n }\n\n let placeText = false;\n let placeIcon = false;\n let offscreen = true;\n let shift = null;\n\n let placed = {box: null, offscreen: null};\n let placedVerticalText = {box: null, offscreen: null};\n\n let placedGlyphBoxes = null;\n let placedGlyphCircles = null;\n let placedIconBoxes = null;\n let textFeatureIndex = 0;\n let verticalTextFeatureIndex = 0;\n let iconFeatureIndex = 0;\n\n if (collisionArrays.textFeatureIndex) {\n textFeatureIndex = collisionArrays.textFeatureIndex;\n } else if (symbolInstance.useRuntimeCollisionCircles) {\n textFeatureIndex = symbolInstance.featureIndex;\n }\n if (collisionArrays.verticalTextFeatureIndex) {\n verticalTextFeatureIndex = collisionArrays.verticalTextFeatureIndex;\n }\n\n const textBox = collisionArrays.textBox;\n if (textBox) {\n\n const updatePreviousOrientationIfNotPlaced = (isPlaced) => {\n let previousOrientation = WritingMode.horizontal;\n if (bucket.allowVerticalPlacement && !isPlaced && this.prevPlacement) {\n const prevPlacedOrientation = this.prevPlacement.placedOrientations[symbolInstance.crossTileID];\n if (prevPlacedOrientation) {\n this.placedOrientations[symbolInstance.crossTileID] = prevPlacedOrientation;\n previousOrientation = prevPlacedOrientation;\n this.markUsedOrientation(bucket, previousOrientation, symbolInstance);\n }\n }\n return previousOrientation;\n };\n\n const placeTextForPlacementModes = (placeHorizontalFn, placeVerticalFn) => {\n if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && collisionArrays.verticalTextBox) {\n for (const placementMode of bucket.writingModes) {\n if (placementMode === WritingMode.vertical) {\n placed = placeVerticalFn();\n placedVerticalText = placed;\n } else {\n placed = placeHorizontalFn();\n }\n if (placed && placed.box && placed.box.length) break;\n }\n } else {\n placed = placeHorizontalFn();\n }\n };\n\n if (!layout.get('text-variable-anchor')) {\n const placeBox = (collisionTextBox, orientation) => {\n const placedFeature = this.collisionIndex.placeCollisionBox(collisionTextBox, textAllowOverlap,\n textPixelRatio, posMatrix, collisionGroup.predicate);\n if (placedFeature && placedFeature.box && placedFeature.box.length) {\n this.markUsedOrientation(bucket, orientation, symbolInstance);\n this.placedOrientations[symbolInstance.crossTileID] = orientation;\n }\n return placedFeature;\n };\n\n const placeHorizontal = () => {\n return placeBox(textBox, WritingMode.horizontal);\n };\n\n const placeVertical = () => {\n const verticalTextBox = collisionArrays.verticalTextBox;\n if (bucket.allowVerticalPlacement && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) {\n return placeBox(verticalTextBox, WritingMode.vertical);\n }\n return {box: null, offscreen: null};\n };\n\n placeTextForPlacementModes(placeHorizontal, placeVertical);\n updatePreviousOrientationIfNotPlaced(placed && placed.box && placed.box.length);\n\n } else {\n let anchors = layout.get('text-variable-anchor');\n\n // If this symbol was in the last placement, shift the previously used\n // anchor to the front of the anchor list, only if the previous anchor\n // is still in the anchor list\n if (this.prevPlacement && this.prevPlacement.variableOffsets[symbolInstance.crossTileID]) {\n const prevOffsets = this.prevPlacement.variableOffsets[symbolInstance.crossTileID];\n if (anchors.indexOf(prevOffsets.anchor) > 0) {\n anchors = anchors.filter(anchor => anchor !== prevOffsets.anchor);\n anchors.unshift(prevOffsets.anchor);\n }\n }\n\n const placeBoxForVariableAnchors = (collisionTextBox, collisionIconBox, orientation) => {\n const width = collisionTextBox.x2 - collisionTextBox.x1;\n const height = collisionTextBox.y2 - collisionTextBox.y1;\n const textBoxScale = symbolInstance.textBoxScale;\n\n const variableIconBox = hasIconTextFit && !iconAllowOverlap ? collisionIconBox : null;\n\n let placedBox: ?{ box: Array, offscreen: boolean } = {box: [], offscreen: false};\n const placementAttempts = textAllowOverlap ? anchors.length * 2 : anchors.length;\n for (let i = 0; i < placementAttempts; ++i) {\n const anchor = anchors[i % anchors.length];\n const allowOverlap = (i >= anchors.length);\n const result = this.attemptAnchorPlacement(\n anchor, collisionTextBox, width, height,\n textBoxScale, rotateWithMap, pitchWithMap, textPixelRatio, posMatrix,\n collisionGroup, allowOverlap, symbolInstance, bucket, orientation, variableIconBox);\n\n if (result) {\n placedBox = result.placedGlyphBoxes;\n if (placedBox && placedBox.box && placedBox.box.length) {\n placeText = true;\n shift = result.shift;\n break;\n }\n }\n }\n\n return placedBox;\n };\n\n const placeHorizontal = () => {\n return placeBoxForVariableAnchors(textBox, collisionArrays.iconBox, WritingMode.horizontal);\n };\n\n const placeVertical = () => {\n const verticalTextBox = collisionArrays.verticalTextBox;\n const wasPlaced = placed && placed.box && placed.box.length;\n if (bucket.allowVerticalPlacement && !wasPlaced && symbolInstance.numVerticalGlyphVertices > 0 && verticalTextBox) {\n return placeBoxForVariableAnchors(verticalTextBox, collisionArrays.verticalIconBox, WritingMode.vertical);\n }\n return {box: null, offscreen: null};\n };\n\n placeTextForPlacementModes(placeHorizontal, placeVertical);\n\n if (placed) {\n placeText = placed.box;\n offscreen = placed.offscreen;\n }\n\n const prevOrientation = updatePreviousOrientationIfNotPlaced(placed && placed.box);\n\n // If we didn't get placed, we still need to copy our position from the last placement for\n // fade animations\n if (!placeText && this.prevPlacement) {\n const prevOffset = this.prevPlacement.variableOffsets[symbolInstance.crossTileID];\n if (prevOffset) {\n this.variableOffsets[symbolInstance.crossTileID] = prevOffset;\n this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, prevOrientation);\n }\n }\n\n }\n }\n\n placedGlyphBoxes = placed;\n placeText = placedGlyphBoxes && placedGlyphBoxes.box && placedGlyphBoxes.box.length > 0;\n\n offscreen = placedGlyphBoxes && placedGlyphBoxes.offscreen;\n\n if (symbolInstance.useRuntimeCollisionCircles) {\n const placedSymbol = bucket.text.placedSymbolArray.get(symbolInstance.centerJustifiedTextSymbolIndex);\n const fontSize = symbolSize.evaluateSizeForFeature(bucket.textSizeData, partiallyEvaluatedTextSize, placedSymbol);\n\n const textPixelPadding = layout.get('text-padding');\n const circlePixelDiameter = symbolInstance.collisionCircleDiameter;\n\n placedGlyphCircles = this.collisionIndex.placeCollisionCircles(textAllowOverlap,\n placedSymbol,\n bucket.lineVertexArray,\n bucket.glyphOffsetArray,\n fontSize,\n posMatrix,\n textLabelPlaneMatrix,\n labelToScreenMatrix,\n showCollisionBoxes,\n pitchWithMap,\n collisionGroup.predicate,\n circlePixelDiameter,\n textPixelPadding);\n\n assert(!placedGlyphCircles.circles.length || (!placedGlyphCircles.collisionDetected || showCollisionBoxes));\n // If text-allow-overlap is set, force \"placedCircles\" to true\n // In theory there should always be at least one circle placed\n // in this case, but for now quirks in text-anchor\n // and text-offset may prevent that from being true.\n placeText = textAllowOverlap || (placedGlyphCircles.circles.length > 0 && !placedGlyphCircles.collisionDetected);\n offscreen = offscreen && placedGlyphCircles.offscreen;\n }\n\n if (collisionArrays.iconFeatureIndex) {\n iconFeatureIndex = collisionArrays.iconFeatureIndex;\n }\n\n if (collisionArrays.iconBox) {\n\n const placeIconFeature = iconBox => {\n const shiftedIconBox = hasIconTextFit && shift ?\n shiftVariableCollisionBox(\n iconBox, shift.x, shift.y,\n rotateWithMap, pitchWithMap, this.transform.angle) :\n iconBox;\n return this.collisionIndex.placeCollisionBox(shiftedIconBox,\n iconAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate);\n };\n\n if (placedVerticalText && placedVerticalText.box && placedVerticalText.box.length && collisionArrays.verticalIconBox) {\n placedIconBoxes = placeIconFeature(collisionArrays.verticalIconBox);\n placeIcon = placedIconBoxes.box.length > 0;\n } else {\n placedIconBoxes = placeIconFeature(collisionArrays.iconBox);\n placeIcon = placedIconBoxes.box.length > 0;\n }\n offscreen = offscreen && placedIconBoxes.offscreen;\n }\n\n const iconWithoutText = textOptional ||\n (symbolInstance.numHorizontalGlyphVertices === 0 && symbolInstance.numVerticalGlyphVertices === 0);\n const textWithoutIcon = iconOptional || symbolInstance.numIconVertices === 0;\n\n // Combine the scales for icons and text.\n if (!iconWithoutText && !textWithoutIcon) {\n placeIcon = placeText = placeIcon && placeText;\n } else if (!textWithoutIcon) {\n placeText = placeIcon && placeText;\n } else if (!iconWithoutText) {\n placeIcon = placeIcon && placeText;\n }\n\n if (placeText && placedGlyphBoxes && placedGlyphBoxes.box) {\n if (placedVerticalText && placedVerticalText.box && verticalTextFeatureIndex) {\n this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, layout.get('text-ignore-placement'),\n bucket.bucketInstanceId, verticalTextFeatureIndex, collisionGroup.ID);\n } else {\n this.collisionIndex.insertCollisionBox(placedGlyphBoxes.box, layout.get('text-ignore-placement'),\n bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID);\n }\n\n }\n if (placeIcon && placedIconBoxes) {\n this.collisionIndex.insertCollisionBox(placedIconBoxes.box, layout.get('icon-ignore-placement'),\n bucket.bucketInstanceId, iconFeatureIndex, collisionGroup.ID);\n }\n if (placedGlyphCircles) {\n if (placeText) {\n this.collisionIndex.insertCollisionCircles(placedGlyphCircles.circles, layout.get('text-ignore-placement'),\n bucket.bucketInstanceId, textFeatureIndex, collisionGroup.ID);\n }\n\n if (showCollisionBoxes) {\n const id = bucket.bucketInstanceId;\n let circleArray = this.collisionCircleArrays[id];\n\n // Group collision circles together by bucket. Circles can't be pushed forward for rendering yet as the symbol placement\n // for a bucket is not guaranteed to be complete before the commit-function has been called\n if (circleArray === undefined)\n circleArray = this.collisionCircleArrays[id] = new CollisionCircleArray();\n\n for (let i = 0; i < placedGlyphCircles.circles.length; i += 4) {\n circleArray.circles.push(placedGlyphCircles.circles[i + 0]); // x\n circleArray.circles.push(placedGlyphCircles.circles[i + 1]); // y\n circleArray.circles.push(placedGlyphCircles.circles[i + 2]); // radius\n circleArray.circles.push(placedGlyphCircles.collisionDetected ? 1 : 0); // collisionDetected-flag\n }\n }\n }\n\n assert(symbolInstance.crossTileID !== 0);\n assert(bucket.bucketInstanceId !== 0);\n\n this.placements[symbolInstance.crossTileID] = new JointPlacement(placeText || alwaysShowText, placeIcon || alwaysShowIcon, offscreen || bucket.justReloaded);\n seenCrossTileIDs[symbolInstance.crossTileID] = true;\n };\n\n if (zOrderByViewportY) {\n assert(bucketPart.symbolInstanceStart === 0);\n const symbolIndexes = bucket.getSortedSymbolIndexes(this.transform.angle);\n for (let i = symbolIndexes.length - 1; i >= 0; --i) {\n const symbolIndex = symbolIndexes[i];\n placeSymbol(bucket.symbolInstances.get(symbolIndex), bucket.collisionArrays[symbolIndex]);\n }\n } else {\n for (let i = bucketPart.symbolInstanceStart; i < bucketPart.symbolInstanceEnd; i++) {\n placeSymbol(bucket.symbolInstances.get(i), bucket.collisionArrays[i]);\n }\n }\n\n if (showCollisionBoxes && bucket.bucketInstanceId in this.collisionCircleArrays) {\n const circleArray = this.collisionCircleArrays[bucket.bucketInstanceId];\n\n // Store viewport and inverse projection matrices per bucket\n mat4.invert(circleArray.invProjMatrix, posMatrix);\n circleArray.viewportMatrix = this.collisionIndex.getViewportMatrix();\n }\n\n bucket.justReloaded = false;\n }\n\n markUsedJustification(bucket: SymbolBucket, placedAnchor: TextAnchor, symbolInstance: SymbolInstance, orientation: number) {\n const justifications = {\n \"left\": symbolInstance.leftJustifiedTextSymbolIndex,\n \"center\": symbolInstance.centerJustifiedTextSymbolIndex,\n \"right\": symbolInstance.rightJustifiedTextSymbolIndex\n };\n\n let autoIndex;\n if (orientation === WritingMode.vertical) {\n autoIndex = symbolInstance.verticalPlacedTextSymbolIndex;\n } else {\n autoIndex = justifications[getAnchorJustification(placedAnchor)];\n }\n\n const indexes = [\n symbolInstance.leftJustifiedTextSymbolIndex,\n symbolInstance.centerJustifiedTextSymbolIndex,\n symbolInstance.rightJustifiedTextSymbolIndex,\n symbolInstance.verticalPlacedTextSymbolIndex\n ];\n\n for (const index of indexes) {\n if (index >= 0) {\n if (autoIndex >= 0 && index !== autoIndex) {\n // There are multiple justifications and this one isn't it: shift offscreen\n bucket.text.placedSymbolArray.get(index).crossTileID = 0;\n } else {\n // Either this is the chosen justification or the justification is hardwired: use this one\n bucket.text.placedSymbolArray.get(index).crossTileID = symbolInstance.crossTileID;\n }\n }\n }\n }\n\n markUsedOrientation(bucket: SymbolBucket, orientation: number, symbolInstance: SymbolInstance) {\n const horizontal = (orientation === WritingMode.horizontal || orientation === WritingMode.horizontalOnly) ? orientation : 0;\n const vertical = orientation === WritingMode.vertical ? orientation : 0;\n\n const horizontalIndexes = [\n symbolInstance.leftJustifiedTextSymbolIndex,\n symbolInstance.centerJustifiedTextSymbolIndex,\n symbolInstance.rightJustifiedTextSymbolIndex\n ];\n\n for (const index of horizontalIndexes) {\n bucket.text.placedSymbolArray.get(index).placedOrientation = horizontal;\n }\n\n if (symbolInstance.verticalPlacedTextSymbolIndex) {\n bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).placedOrientation = vertical;\n }\n }\n\n commit(now: number): void {\n this.commitTime = now;\n this.zoomAtLastRecencyCheck = this.transform.zoom;\n\n const prevPlacement = this.prevPlacement;\n let placementChanged = false;\n\n this.prevZoomAdjustment = prevPlacement ? prevPlacement.zoomAdjustment(this.transform.zoom) : 0;\n const increment = prevPlacement ? prevPlacement.symbolFadeChange(now) : 1;\n\n const prevOpacities = prevPlacement ? prevPlacement.opacities : {};\n const prevOffsets = prevPlacement ? prevPlacement.variableOffsets : {};\n const prevOrientations = prevPlacement ? prevPlacement.placedOrientations : {};\n\n // add the opacities from the current placement, and copy their current values from the previous placement\n for (const crossTileID in this.placements) {\n const jointPlacement = this.placements[crossTileID];\n const prevOpacity = prevOpacities[crossTileID];\n if (prevOpacity) {\n this.opacities[crossTileID] = new JointOpacityState(prevOpacity, increment, jointPlacement.text, jointPlacement.icon);\n placementChanged = placementChanged ||\n jointPlacement.text !== prevOpacity.text.placed ||\n jointPlacement.icon !== prevOpacity.icon.placed;\n } else {\n this.opacities[crossTileID] = new JointOpacityState(null, increment, jointPlacement.text, jointPlacement.icon, jointPlacement.skipFade);\n placementChanged = placementChanged || jointPlacement.text || jointPlacement.icon;\n }\n }\n\n // copy and update values from the previous placement that aren't in the current placement but haven't finished fading\n for (const crossTileID in prevOpacities) {\n const prevOpacity = prevOpacities[crossTileID];\n if (!this.opacities[crossTileID]) {\n const jointOpacity = new JointOpacityState(prevOpacity, increment, false, false);\n if (!jointOpacity.isHidden()) {\n this.opacities[crossTileID] = jointOpacity;\n placementChanged = placementChanged || prevOpacity.text.placed || prevOpacity.icon.placed;\n }\n }\n }\n for (const crossTileID in prevOffsets) {\n if (!this.variableOffsets[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) {\n this.variableOffsets[crossTileID] = prevOffsets[crossTileID];\n }\n }\n\n for (const crossTileID in prevOrientations) {\n if (!this.placedOrientations[crossTileID] && this.opacities[crossTileID] && !this.opacities[crossTileID].isHidden()) {\n this.placedOrientations[crossTileID] = prevOrientations[crossTileID];\n }\n }\n\n // this.lastPlacementChangeTime is the time of the last commit() that\n // resulted in a placement change -- in other words, the start time of\n // the last symbol fade animation\n assert(!prevPlacement || prevPlacement.lastPlacementChangeTime !== undefined);\n if (placementChanged) {\n this.lastPlacementChangeTime = now;\n } else if (typeof this.lastPlacementChangeTime !== 'number') {\n this.lastPlacementChangeTime = prevPlacement ? prevPlacement.lastPlacementChangeTime : now;\n }\n }\n\n updateLayerOpacities(styleLayer: StyleLayer, tiles: Array) {\n const seenCrossTileIDs = {};\n for (const tile of tiles) {\n const symbolBucket = ((tile.getBucket(styleLayer): any): SymbolBucket);\n if (symbolBucket && tile.latestFeatureIndex && styleLayer.id === symbolBucket.layerIds[0]) {\n this.updateBucketOpacities(symbolBucket, seenCrossTileIDs, tile.collisionBoxArray);\n }\n }\n }\n\n updateBucketOpacities(bucket: SymbolBucket, seenCrossTileIDs: { [string | number]: boolean }, collisionBoxArray: ?CollisionBoxArray) {\n if (bucket.hasTextData()) bucket.text.opacityVertexArray.clear();\n if (bucket.hasIconData()) bucket.icon.opacityVertexArray.clear();\n if (bucket.hasIconCollisionBoxData()) bucket.iconCollisionBox.collisionVertexArray.clear();\n if (bucket.hasTextCollisionBoxData()) bucket.textCollisionBox.collisionVertexArray.clear();\n\n const layout = bucket.layers[0].layout;\n const duplicateOpacityState = new JointOpacityState(null, 0, false, false, true);\n const textAllowOverlap = layout.get('text-allow-overlap');\n const iconAllowOverlap = layout.get('icon-allow-overlap');\n const variablePlacement = layout.get('text-variable-anchor');\n const rotateWithMap = layout.get('text-rotation-alignment') === 'map';\n const pitchWithMap = layout.get('text-pitch-alignment') === 'map';\n const hasIconTextFit = layout.get('icon-text-fit') !== 'none';\n // If allow-overlap is true, we can show symbols before placement runs on them\n // But we have to wait for placement if we potentially depend on a paired icon/text\n // with allow-overlap: false.\n // See https://github.com/mapbox/mapbox-gl-js/issues/7032\n const defaultOpacityState = new JointOpacityState(null, 0,\n textAllowOverlap && (iconAllowOverlap || !bucket.hasIconData() || layout.get('icon-optional')),\n iconAllowOverlap && (textAllowOverlap || !bucket.hasTextData() || layout.get('text-optional')),\n true);\n\n if (!bucket.collisionArrays && collisionBoxArray && ((bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()))) {\n bucket.deserializeCollisionBoxes(collisionBoxArray);\n }\n\n const addOpacities = (iconOrText, numVertices: number, opacity: number) => {\n for (let i = 0; i < numVertices / 4; i++) {\n iconOrText.opacityVertexArray.emplaceBack(opacity);\n }\n };\n\n for (let s = 0; s < bucket.symbolInstances.length; s++) {\n const symbolInstance = bucket.symbolInstances.get(s);\n const {\n numHorizontalGlyphVertices,\n numVerticalGlyphVertices,\n crossTileID\n } = symbolInstance;\n\n const isDuplicate = seenCrossTileIDs[crossTileID];\n\n let opacityState = this.opacities[crossTileID];\n if (isDuplicate) {\n opacityState = duplicateOpacityState;\n } else if (!opacityState) {\n opacityState = defaultOpacityState;\n // store the state so that future placements use it as a starting point\n this.opacities[crossTileID] = opacityState;\n }\n\n seenCrossTileIDs[crossTileID] = true;\n\n const hasText = numHorizontalGlyphVertices > 0 || numVerticalGlyphVertices > 0;\n const hasIcon = symbolInstance.numIconVertices > 0;\n\n const placedOrientation = this.placedOrientations[symbolInstance.crossTileID];\n const horizontalHidden = placedOrientation === WritingMode.vertical;\n const verticalHidden = placedOrientation === WritingMode.horizontal || placedOrientation === WritingMode.horizontalOnly;\n\n if (hasText) {\n const packedOpacity = packOpacity(opacityState.text);\n // Vertical text fades in/out on collision the same way as corresponding\n // horizontal text. Switch between vertical/horizontal should be instantaneous\n const horizontalOpacity = horizontalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity;\n addOpacities(bucket.text, numHorizontalGlyphVertices, horizontalOpacity);\n const verticalOpacity = verticalHidden ? PACKED_HIDDEN_OPACITY : packedOpacity;\n addOpacities(bucket.text, numVerticalGlyphVertices, verticalOpacity);\n\n // If this label is completely faded, mark it so that we don't have to calculate\n // its position at render time. If this layer has variable placement, shift the various\n // symbol instances appropriately so that symbols from buckets that have yet to be placed\n // offset appropriately.\n const symbolHidden = opacityState.text.isHidden();\n [\n symbolInstance.rightJustifiedTextSymbolIndex,\n symbolInstance.centerJustifiedTextSymbolIndex,\n symbolInstance.leftJustifiedTextSymbolIndex\n ].forEach(index => {\n if (index >= 0) {\n bucket.text.placedSymbolArray.get(index).hidden = symbolHidden || horizontalHidden ? 1 : 0;\n }\n });\n\n if (symbolInstance.verticalPlacedTextSymbolIndex >= 0) {\n bucket.text.placedSymbolArray.get(symbolInstance.verticalPlacedTextSymbolIndex).hidden = symbolHidden || verticalHidden ? 1 : 0;\n }\n\n const prevOffset = this.variableOffsets[symbolInstance.crossTileID];\n if (prevOffset) {\n this.markUsedJustification(bucket, prevOffset.anchor, symbolInstance, placedOrientation);\n }\n\n const prevOrientation = this.placedOrientations[symbolInstance.crossTileID];\n if (prevOrientation) {\n this.markUsedJustification(bucket, 'left', symbolInstance, prevOrientation);\n this.markUsedOrientation(bucket, prevOrientation, symbolInstance);\n }\n }\n\n if (hasIcon) {\n const packedOpacity = packOpacity(opacityState.icon);\n\n const useHorizontal = !(hasIconTextFit && symbolInstance.verticalPlacedIconSymbolIndex && horizontalHidden);\n\n if (symbolInstance.placedIconSymbolIndex >= 0) {\n const horizontalOpacity = useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY;\n addOpacities(bucket.icon, symbolInstance.numIconVertices, horizontalOpacity);\n bucket.icon.placedSymbolArray.get(symbolInstance.placedIconSymbolIndex).hidden =\n (opacityState.icon.isHidden(): any);\n }\n\n if (symbolInstance.verticalPlacedIconSymbolIndex >= 0) {\n const verticalOpacity = !useHorizontal ? packedOpacity : PACKED_HIDDEN_OPACITY;\n addOpacities(bucket.icon, symbolInstance.numVerticalIconVertices, verticalOpacity);\n bucket.icon.placedSymbolArray.get(symbolInstance.verticalPlacedIconSymbolIndex).hidden =\n (opacityState.icon.isHidden(): any);\n }\n }\n\n if (bucket.hasIconCollisionBoxData() || bucket.hasTextCollisionBoxData()) {\n const collisionArrays = bucket.collisionArrays[s];\n if (collisionArrays) {\n let shift = new Point(0, 0);\n if (collisionArrays.textBox || collisionArrays.verticalTextBox) {\n let used = true;\n if (variablePlacement) {\n const variableOffset = this.variableOffsets[crossTileID];\n if (variableOffset) {\n // This will show either the currently placed position or the last\n // successfully placed position (so you can visualize what collision\n // just made the symbol disappear, and the most likely place for the\n // symbol to come back)\n shift = calculateVariableLayoutShift(variableOffset.anchor,\n variableOffset.width,\n variableOffset.height,\n variableOffset.textOffset,\n variableOffset.textBoxScale);\n if (rotateWithMap) {\n shift._rotate(pitchWithMap ? this.transform.angle : -this.transform.angle);\n }\n } else {\n // No offset -> this symbol hasn't been placed since coming on-screen\n // No single box is particularly meaningful and all of them would be too noisy\n // Use the center box just to show something's there, but mark it \"not used\"\n used = false;\n }\n }\n\n if (collisionArrays.textBox) {\n updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || horizontalHidden, shift.x, shift.y);\n }\n if (collisionArrays.verticalTextBox) {\n updateCollisionVertices(bucket.textCollisionBox.collisionVertexArray, opacityState.text.placed, !used || verticalHidden, shift.x, shift.y);\n }\n }\n\n const verticalIconUsed = Boolean(!verticalHidden && collisionArrays.verticalIconBox);\n\n if (collisionArrays.iconBox) {\n updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, verticalIconUsed,\n hasIconTextFit ? shift.x : 0,\n hasIconTextFit ? shift.y : 0);\n }\n\n if (collisionArrays.verticalIconBox) {\n updateCollisionVertices(bucket.iconCollisionBox.collisionVertexArray, opacityState.icon.placed, !verticalIconUsed,\n hasIconTextFit ? shift.x : 0,\n hasIconTextFit ? shift.y : 0);\n }\n }\n }\n }\n\n bucket.sortFeatures(this.transform.angle);\n if (this.retainedQueryData[bucket.bucketInstanceId]) {\n this.retainedQueryData[bucket.bucketInstanceId].featureSortOrder = bucket.featureSortOrder;\n }\n\n if (bucket.hasTextData() && bucket.text.opacityVertexBuffer) {\n bucket.text.opacityVertexBuffer.updateData(bucket.text.opacityVertexArray);\n }\n if (bucket.hasIconData() && bucket.icon.opacityVertexBuffer) {\n bucket.icon.opacityVertexBuffer.updateData(bucket.icon.opacityVertexArray);\n }\n if (bucket.hasIconCollisionBoxData() && bucket.iconCollisionBox.collisionVertexBuffer) {\n bucket.iconCollisionBox.collisionVertexBuffer.updateData(bucket.iconCollisionBox.collisionVertexArray);\n }\n if (bucket.hasTextCollisionBoxData() && bucket.textCollisionBox.collisionVertexBuffer) {\n bucket.textCollisionBox.collisionVertexBuffer.updateData(bucket.textCollisionBox.collisionVertexArray);\n }\n\n assert(bucket.text.opacityVertexArray.length === bucket.text.layoutVertexArray.length / 4);\n assert(bucket.icon.opacityVertexArray.length === bucket.icon.layoutVertexArray.length / 4);\n\n // Push generated collision circles to the bucket for debug rendering\n if (bucket.bucketInstanceId in this.collisionCircleArrays) {\n const instance = this.collisionCircleArrays[bucket.bucketInstanceId];\n\n bucket.placementInvProjMatrix = instance.invProjMatrix;\n bucket.placementViewportMatrix = instance.viewportMatrix;\n bucket.collisionCircleArray = instance.circles;\n\n delete this.collisionCircleArrays[bucket.bucketInstanceId];\n }\n }\n\n symbolFadeChange(now: number) {\n return this.fadeDuration === 0 ?\n 1 :\n ((now - this.commitTime) / this.fadeDuration + this.prevZoomAdjustment);\n }\n\n zoomAdjustment(zoom: number) {\n // When zooming out quickly, labels can overlap each other. This\n // adjustment is used to reduce the interval between placement calculations\n // and to reduce the fade duration when zooming out quickly. Discovering the\n // collisions more quickly and fading them more quickly reduces the unwanted effect.\n return Math.max(0, (this.transform.zoom - zoom) / 1.5);\n }\n\n hasTransitions(now: number) {\n return this.stale ||\n now - this.lastPlacementChangeTime < this.fadeDuration;\n }\n\n stillRecent(now: number, zoom: number) {\n // The adjustment makes placement more frequent when zooming.\n // This condition applies the adjustment only after the map has\n // stopped zooming. This avoids adding extra jank while zooming.\n const durationAdjustment = this.zoomAtLastRecencyCheck === zoom ?\n (1 - this.zoomAdjustment(zoom)) :\n 1;\n this.zoomAtLastRecencyCheck = zoom;\n\n return this.commitTime + this.fadeDuration * durationAdjustment > now;\n }\n\n setStale() {\n this.stale = true;\n }\n}\n\nfunction updateCollisionVertices(collisionVertexArray: CollisionVertexArray, placed: boolean, notUsed: boolean | number, shiftX?: number, shiftY?: number) {\n collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);\n collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);\n collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);\n collisionVertexArray.emplaceBack(placed ? 1 : 0, notUsed ? 1 : 0, shiftX || 0, shiftY || 0);\n}\n\n// All four vertices for a glyph will have the same opacity state\n// So we pack the opacity into a uint8, and then repeat it four times\n// to make a single uint32 that we can upload for each glyph in the\n// label.\nconst shift25 = Math.pow(2, 25);\nconst shift24 = Math.pow(2, 24);\nconst shift17 = Math.pow(2, 17);\nconst shift16 = Math.pow(2, 16);\nconst shift9 = Math.pow(2, 9);\nconst shift8 = Math.pow(2, 8);\nconst shift1 = Math.pow(2, 1);\nfunction packOpacity(opacityState: OpacityState): number {\n if (opacityState.opacity === 0 && !opacityState.placed) {\n return 0;\n } else if (opacityState.opacity === 1 && opacityState.placed) {\n return 4294967295;\n }\n const targetBit = opacityState.placed ? 1 : 0;\n const opacityBits = Math.floor(opacityState.opacity * 127);\n return opacityBits * shift25 + targetBit * shift24 +\n opacityBits * shift17 + targetBit * shift16 +\n opacityBits * shift9 + targetBit * shift8 +\n opacityBits * shift1 + targetBit;\n}\n\nconst PACKED_HIDDEN_OPACITY = 0;\n","// @flow\n\nimport browser from '../util/browser';\n\nimport {Placement} from '../symbol/placement';\n\nimport type Transform from '../geo/transform';\nimport type StyleLayer from './style_layer';\nimport type SymbolStyleLayer from './style_layer/symbol_style_layer';\nimport type Tile from '../source/tile';\nimport type {BucketPart} from '../symbol/placement';\n\nclass LayerPlacement {\n _sortAcrossTiles: boolean;\n _currentTileIndex: number;\n _currentPartIndex: number;\n _seenCrossTileIDs: { [string | number]: boolean };\n _bucketParts: Array;\n\n constructor(styleLayer: SymbolStyleLayer) {\n this._sortAcrossTiles = styleLayer.layout.get('symbol-z-order') !== 'viewport-y' &&\n styleLayer.layout.get('symbol-sort-key').constantOr(1) !== undefined;\n\n this._currentTileIndex = 0;\n this._currentPartIndex = 0;\n this._seenCrossTileIDs = {};\n this._bucketParts = [];\n }\n\n continuePlacement(tiles: Array, placement: Placement, showCollisionBoxes: boolean, styleLayer: StyleLayer, shouldPausePlacement: () => boolean) {\n\n const bucketParts = this._bucketParts;\n\n while (this._currentTileIndex < tiles.length) {\n const tile = tiles[this._currentTileIndex];\n placement.getBucketParts(bucketParts, styleLayer, tile, this._sortAcrossTiles);\n\n this._currentTileIndex++;\n if (shouldPausePlacement()) {\n return true;\n }\n }\n\n if (this._sortAcrossTiles) {\n this._sortAcrossTiles = false;\n bucketParts.sort((a, b) => ((a.sortKey: any): number) - ((b.sortKey: any): number));\n }\n\n while (this._currentPartIndex < bucketParts.length) {\n const bucketPart = bucketParts[this._currentPartIndex];\n placement.placeLayerBucketPart(bucketPart, this._seenCrossTileIDs, showCollisionBoxes);\n\n this._currentPartIndex++;\n if (shouldPausePlacement()) {\n return true;\n }\n }\n return false;\n }\n}\n\nclass PauseablePlacement {\n placement: Placement;\n _done: boolean;\n _currentPlacementIndex: number;\n _forceFullPlacement: boolean;\n _showCollisionBoxes: boolean;\n _inProgressLayer: ?LayerPlacement;\n\n constructor(transform: Transform, order: Array,\n forceFullPlacement: boolean,\n showCollisionBoxes: boolean,\n fadeDuration: number,\n crossSourceCollisions: boolean,\n prevPlacement?: Placement) {\n\n this.placement = new Placement(transform, fadeDuration, crossSourceCollisions, prevPlacement);\n this._currentPlacementIndex = order.length - 1;\n this._forceFullPlacement = forceFullPlacement;\n this._showCollisionBoxes = showCollisionBoxes;\n this._done = false;\n }\n\n isDone(): boolean {\n return this._done;\n }\n\n continuePlacement(order: Array, layers: {[_: string]: StyleLayer}, layerTiles: {[_: string]: Array}) {\n const startTime = browser.now();\n\n const shouldPausePlacement = () => {\n const elapsedTime = browser.now() - startTime;\n return this._forceFullPlacement ? false : elapsedTime > 2;\n };\n\n while (this._currentPlacementIndex >= 0) {\n const layerId = order[this._currentPlacementIndex];\n const layer = layers[layerId];\n const placementZoom = this.placement.collisionIndex.transform.zoom;\n if (layer.type === 'symbol' &&\n (!layer.minzoom || layer.minzoom <= placementZoom) &&\n (!layer.maxzoom || layer.maxzoom > placementZoom)) {\n\n if (!this._inProgressLayer) {\n this._inProgressLayer = new LayerPlacement(((layer: any): SymbolStyleLayer));\n }\n\n const pausePlacement = this._inProgressLayer.continuePlacement(layerTiles[layer.source], this.placement, this._showCollisionBoxes, layer, shouldPausePlacement);\n\n if (pausePlacement) {\n // We didn't finish placing all layers within 2ms,\n // but we can keep rendering with a partial placement\n // We'll resume here on the next frame\n return;\n }\n\n delete this._inProgressLayer;\n }\n\n this._currentPlacementIndex--;\n }\n\n this._done = true;\n }\n\n commit(now: number) {\n this.placement.commit(now);\n return this.placement;\n }\n}\n\nexport default PauseablePlacement;\n","// @flow\n\nimport EXTENT from '../data/extent';\n\nimport {SymbolInstanceArray} from '../data/array_types';\n\nimport type {SymbolInstance} from '../data/array_types';\nimport type {OverscaledTileID} from '../source/tile_id';\nimport type SymbolBucket from '../data/bucket/symbol_bucket';\nimport type StyleLayer from '../style/style_layer';\nimport type Tile from '../source/tile';\n\n/*\n The CrossTileSymbolIndex generally works on the assumption that\n a conceptual \"unique symbol\" can be identified by the text of\n the label combined with the anchor point. The goal is to assign\n these conceptual \"unique symbols\" a shared crossTileID that can be\n used by Placement to keep fading opacity states consistent and to\n deduplicate labels.\n\n The CrossTileSymbolIndex indexes all the current symbol instances and\n their crossTileIDs. When a symbol bucket gets added or updated, the\n index assigns a crossTileID to each of it's symbol instances by either\n matching it with an existing id or assigning a new one.\n*/\n\n// Round anchor positions to roughly 4 pixel grid\nconst roundingFactor = 512 / EXTENT / 2;\n\nclass TileLayerIndex {\n tileID: OverscaledTileID;\n indexedSymbolInstances: {[_: number]: Array<{\n crossTileID: number,\n coord: {\n x: number,\n y: number\n }\n }>};\n bucketInstanceId: number;\n\n constructor(tileID: OverscaledTileID, symbolInstances: SymbolInstanceArray, bucketInstanceId: number) {\n this.tileID = tileID;\n this.indexedSymbolInstances = {};\n this.bucketInstanceId = bucketInstanceId;\n\n for (let i = 0; i < symbolInstances.length; i++) {\n const symbolInstance = symbolInstances.get(i);\n const key = symbolInstance.key;\n if (!this.indexedSymbolInstances[key]) {\n this.indexedSymbolInstances[key] = [];\n }\n // This tile may have multiple symbol instances with the same key\n // Store each one along with its coordinates\n this.indexedSymbolInstances[key].push({\n crossTileID: symbolInstance.crossTileID,\n coord: this.getScaledCoordinates(symbolInstance, tileID)\n });\n }\n }\n\n // Converts the coordinates of the input symbol instance into coordinates that be can compared\n // against other symbols in this index. Coordinates are:\n // (1) world-based (so after conversion the source tile is irrelevant)\n // (2) converted to the z-scale of this TileLayerIndex\n // (3) down-sampled by \"roundingFactor\" from tile coordinate precision in order to be\n // more tolerant of small differences between tiles.\n getScaledCoordinates(symbolInstance: SymbolInstance, childTileID: OverscaledTileID) {\n const zDifference = childTileID.canonical.z - this.tileID.canonical.z;\n const scale = roundingFactor / Math.pow(2, zDifference);\n return {\n x: Math.floor((childTileID.canonical.x * EXTENT + symbolInstance.anchorX) * scale),\n y: Math.floor((childTileID.canonical.y * EXTENT + symbolInstance.anchorY) * scale)\n };\n }\n\n findMatches(symbolInstances: SymbolInstanceArray, newTileID: OverscaledTileID, zoomCrossTileIDs: {[crossTileID: number]: boolean}) {\n const tolerance = this.tileID.canonical.z < newTileID.canonical.z ? 1 : Math.pow(2, this.tileID.canonical.z - newTileID.canonical.z);\n\n for (let i = 0; i < symbolInstances.length; i++) {\n const symbolInstance = symbolInstances.get(i);\n if (symbolInstance.crossTileID) {\n // already has a match, skip\n continue;\n }\n\n const indexedInstances = this.indexedSymbolInstances[symbolInstance.key];\n if (!indexedInstances) {\n // No symbol with this key in this bucket\n continue;\n }\n\n const scaledSymbolCoord = this.getScaledCoordinates(symbolInstance, newTileID);\n\n for (const thisTileSymbol of indexedInstances) {\n // Return any symbol with the same keys whose coordinates are within 1\n // grid unit. (with a 4px grid, this covers a 12px by 12px area)\n if (Math.abs(thisTileSymbol.coord.x - scaledSymbolCoord.x) <= tolerance &&\n Math.abs(thisTileSymbol.coord.y - scaledSymbolCoord.y) <= tolerance &&\n !zoomCrossTileIDs[thisTileSymbol.crossTileID]) {\n // Once we've marked ourselves duplicate against this parent symbol,\n // don't let any other symbols at the same zoom level duplicate against\n // the same parent (see issue #5993)\n zoomCrossTileIDs[thisTileSymbol.crossTileID] = true;\n symbolInstance.crossTileID = thisTileSymbol.crossTileID;\n break;\n }\n }\n }\n }\n}\n\nclass CrossTileIDs {\n maxCrossTileID: number;\n constructor() {\n this.maxCrossTileID = 0;\n }\n generate() {\n return ++this.maxCrossTileID;\n }\n}\n\nclass CrossTileSymbolLayerIndex {\n indexes: {[zoom: string | number]: {[tileId: string | number]: TileLayerIndex}};\n usedCrossTileIDs: {[zoom: string | number]: {[crossTileID: number]: boolean}};\n lng: number;\n\n constructor() {\n this.indexes = {};\n this.usedCrossTileIDs = {};\n this.lng = 0;\n }\n\n /*\n * Sometimes when a user pans across the antimeridian the longitude value gets wrapped.\n * To prevent labels from flashing out and in we adjust the tileID values in the indexes\n * so that they match the new wrapped version of the map.\n */\n handleWrapJump(lng: number) {\n const wrapDelta = Math.round((lng - this.lng) / 360);\n if (wrapDelta !== 0) {\n for (const zoom in this.indexes) {\n const zoomIndexes = this.indexes[zoom];\n const newZoomIndex = {};\n for (const key in zoomIndexes) {\n // change the tileID's wrap and add it to a new index\n const index = zoomIndexes[key];\n index.tileID = index.tileID.unwrapTo(index.tileID.wrap + wrapDelta);\n newZoomIndex[index.tileID.key] = index;\n }\n this.indexes[zoom] = newZoomIndex;\n }\n }\n this.lng = lng;\n }\n\n addBucket(tileID: OverscaledTileID, bucket: SymbolBucket, crossTileIDs: CrossTileIDs) {\n if (this.indexes[tileID.overscaledZ] &&\n this.indexes[tileID.overscaledZ][tileID.key]) {\n if (this.indexes[tileID.overscaledZ][tileID.key].bucketInstanceId ===\n bucket.bucketInstanceId) {\n return false;\n } else {\n // We're replacing this bucket with an updated version\n // Remove the old bucket's \"used crossTileIDs\" now so that\n // the new bucket can claim them.\n // The old index entries themselves stick around until\n // 'removeStaleBuckets' is called.\n this.removeBucketCrossTileIDs(tileID.overscaledZ,\n this.indexes[tileID.overscaledZ][tileID.key]);\n }\n }\n\n for (let i = 0; i < bucket.symbolInstances.length; i++) {\n const symbolInstance = bucket.symbolInstances.get(i);\n symbolInstance.crossTileID = 0;\n }\n\n if (!this.usedCrossTileIDs[tileID.overscaledZ]) {\n this.usedCrossTileIDs[tileID.overscaledZ] = {};\n }\n const zoomCrossTileIDs = this.usedCrossTileIDs[tileID.overscaledZ];\n\n for (const zoom in this.indexes) {\n const zoomIndexes = this.indexes[zoom];\n if (Number(zoom) > tileID.overscaledZ) {\n for (const id in zoomIndexes) {\n const childIndex = zoomIndexes[id];\n if (childIndex.tileID.isChildOf(tileID)) {\n childIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs);\n }\n }\n } else {\n const parentCoord = tileID.scaledTo(Number(zoom));\n const parentIndex = zoomIndexes[parentCoord.key];\n if (parentIndex) {\n parentIndex.findMatches(bucket.symbolInstances, tileID, zoomCrossTileIDs);\n }\n }\n }\n\n for (let i = 0; i < bucket.symbolInstances.length; i++) {\n const symbolInstance = bucket.symbolInstances.get(i);\n if (!symbolInstance.crossTileID) {\n // symbol did not match any known symbol, assign a new id\n symbolInstance.crossTileID = crossTileIDs.generate();\n zoomCrossTileIDs[symbolInstance.crossTileID] = true;\n }\n }\n\n if (this.indexes[tileID.overscaledZ] === undefined) {\n this.indexes[tileID.overscaledZ] = {};\n }\n this.indexes[tileID.overscaledZ][tileID.key] = new TileLayerIndex(tileID, bucket.symbolInstances, bucket.bucketInstanceId);\n\n return true;\n }\n\n removeBucketCrossTileIDs(zoom: string | number, removedBucket: TileLayerIndex) {\n for (const key in removedBucket.indexedSymbolInstances) {\n for (const symbolInstance of removedBucket.indexedSymbolInstances[(key: any)]) {\n delete this.usedCrossTileIDs[zoom][symbolInstance.crossTileID];\n }\n }\n }\n\n removeStaleBuckets(currentIDs: { [string | number]: boolean }) {\n let tilesChanged = false;\n for (const z in this.indexes) {\n const zoomIndexes = this.indexes[z];\n for (const tileKey in zoomIndexes) {\n if (!currentIDs[zoomIndexes[tileKey].bucketInstanceId]) {\n this.removeBucketCrossTileIDs(z, zoomIndexes[tileKey]);\n delete zoomIndexes[tileKey];\n tilesChanged = true;\n }\n }\n }\n return tilesChanged;\n }\n}\n\nclass CrossTileSymbolIndex {\n layerIndexes: {[layerId: string]: CrossTileSymbolLayerIndex};\n crossTileIDs: CrossTileIDs;\n maxBucketInstanceId: number;\n bucketsInCurrentPlacement: {[_: number]: boolean};\n\n constructor() {\n this.layerIndexes = {};\n this.crossTileIDs = new CrossTileIDs();\n this.maxBucketInstanceId = 0;\n this.bucketsInCurrentPlacement = {};\n }\n\n addLayer(styleLayer: StyleLayer, tiles: Array, lng: number) {\n let layerIndex = this.layerIndexes[styleLayer.id];\n if (layerIndex === undefined) {\n layerIndex = this.layerIndexes[styleLayer.id] = new CrossTileSymbolLayerIndex();\n }\n\n let symbolBucketsChanged = false;\n const currentBucketIDs = {};\n\n layerIndex.handleWrapJump(lng);\n\n for (const tile of tiles) {\n const symbolBucket = ((tile.getBucket(styleLayer): any): SymbolBucket);\n if (!symbolBucket || styleLayer.id !== symbolBucket.layerIds[0])\n continue;\n\n if (!symbolBucket.bucketInstanceId) {\n symbolBucket.bucketInstanceId = ++this.maxBucketInstanceId;\n }\n\n if (layerIndex.addBucket(tile.tileID, symbolBucket, this.crossTileIDs)) {\n symbolBucketsChanged = true;\n }\n currentBucketIDs[symbolBucket.bucketInstanceId] = true;\n }\n\n if (layerIndex.removeStaleBuckets(currentBucketIDs)) {\n symbolBucketsChanged = true;\n }\n\n return symbolBucketsChanged;\n }\n\n pruneUnusedLayers(usedLayers: Array) {\n const usedLayerMap = {};\n usedLayers.forEach((usedLayer) => {\n usedLayerMap[usedLayer] = true;\n });\n for (const layerId in this.layerIndexes) {\n if (!usedLayerMap[layerId]) {\n delete this.layerIndexes[layerId];\n }\n }\n }\n}\n\nexport default CrossTileSymbolIndex;\n","// @flow\n\nimport assert from 'assert';\n\nimport {Event, ErrorEvent, Evented} from '../util/evented';\nimport StyleLayer from './style_layer';\nimport createStyleLayer from './create_style_layer';\nimport loadSprite from './load_sprite';\nimport ImageManager from '../render/image_manager';\nimport GlyphManager from '../render/glyph_manager';\nimport Light from './light';\nimport LineAtlas from '../render/line_atlas';\nimport {pick, clone, extend, deepEqual, filterObject, mapObject} from '../util/util';\nimport {getJSON, getReferrer, makeRequest, ResourceType} from '../util/ajax';\nimport {isMapboxURL} from '../util/mapbox';\nimport browser from '../util/browser';\nimport Dispatcher from '../util/dispatcher';\nimport {validateStyle, emitValidationErrors as _emitValidationErrors} from './validate_style';\nimport {\n getType as getSourceType,\n setType as setSourceType,\n type SourceClass\n} from '../source/source';\nimport {queryRenderedFeatures, queryRenderedSymbols, querySourceFeatures} from '../source/query_features';\nimport SourceCache from '../source/source_cache';\nimport GeoJSONSource from '../source/geojson_source';\nimport styleSpec from '../style-spec/reference/latest';\nimport getWorkerPool from '../util/global_worker_pool';\nimport deref from '../style-spec/deref';\nimport emptyStyle from '../style-spec/empty';\nimport diffStyles, {operations as diffOperations} from '../style-spec/diff';\nimport {\n registerForPluginStateChange,\n evented as rtlTextPluginEvented,\n triggerPluginCompletionEvent\n} from '../source/rtl_text_plugin';\nimport PauseablePlacement from './pauseable_placement';\nimport ZoomHistory from './zoom_history';\nimport CrossTileSymbolIndex from '../symbol/cross_tile_symbol_index';\nimport {validateCustomStyleLayer} from './style_layer/custom_style_layer';\n\n// We're skipping validation errors with the `source.canvas` identifier in order\n// to continue to allow canvas sources to be added at runtime/updated in\n// smart setStyle (see https://github.com/mapbox/mapbox-gl-js/pull/6424):\nconst emitValidationErrors = (evented: Evented, errors: ?$ReadOnlyArray<{message: string, identifier?: string}>) =>\n _emitValidationErrors(evented, errors && errors.filter(error => error.identifier !== 'source.canvas'));\n\nimport type Map from '../ui/map';\nimport type Transform from '../geo/transform';\nimport type {StyleImage} from './style_image';\nimport type {StyleGlyph} from './style_glyph';\nimport type {Callback} from '../types/callback';\nimport type EvaluationParameters from './evaluation_parameters';\nimport type {Placement} from '../symbol/placement';\nimport type {Cancelable} from '../types/cancelable';\nimport type {RequestParameters, ResponseCallback} from '../util/ajax';\nimport type {GeoJSON} from '@mapbox/geojson-types';\nimport type {\n LayerSpecification,\n FilterSpecification,\n StyleSpecification,\n LightSpecification,\n SourceSpecification\n} from '../style-spec/types';\nimport type {CustomLayerInterface} from './style_layer/custom_style_layer';\nimport type {Validator} from './validate_style';\nimport type {OverscaledTileID} from '../source/tile_id';\n\nconst supportedDiffOperations = pick(diffOperations, [\n 'addLayer',\n 'removeLayer',\n 'setPaintProperty',\n 'setLayoutProperty',\n 'setFilter',\n 'addSource',\n 'removeSource',\n 'setLayerZoomRange',\n 'setLight',\n 'setTransition',\n 'setGeoJSONSourceData'\n // 'setGlyphs',\n // 'setSprite',\n]);\n\nconst ignoredDiffOperations = pick(diffOperations, [\n 'setCenter',\n 'setZoom',\n 'setBearing',\n 'setPitch'\n]);\n\nconst empty = emptyStyle();\n\nexport type StyleOptions = {\n validate?: boolean,\n localIdeographFontFamily?: string\n};\n\nexport type StyleSetterOptions = {\n validate?: boolean\n};\n/**\n * @private\n */\nclass Style extends Evented {\n map: Map;\n stylesheet: StyleSpecification;\n dispatcher: Dispatcher;\n imageManager: ImageManager;\n glyphManager: GlyphManager;\n lineAtlas: LineAtlas;\n light: Light;\n\n _request: ?Cancelable;\n _spriteRequest: ?Cancelable;\n _layers: {[_: string]: StyleLayer};\n _serializedLayers: {[_: string]: Object};\n _order: Array;\n sourceCaches: {[_: string]: SourceCache};\n zoomHistory: ZoomHistory;\n _loaded: boolean;\n _rtlTextPluginCallback: Function;\n _changed: boolean;\n _updatedSources: {[_: string]: 'clear' | 'reload'};\n _updatedLayers: {[_: string]: true};\n _removedLayers: {[_: string]: StyleLayer};\n _changedImages: {[_: string]: true};\n _updatedPaintProps: {[layer: string]: true};\n _layerOrderChanged: boolean;\n _availableImages: Array;\n\n crossTileSymbolIndex: CrossTileSymbolIndex;\n pauseablePlacement: PauseablePlacement;\n placement: Placement;\n z: number;\n\n // exposed to allow stubbing by unit tests\n static getSourceType: typeof getSourceType;\n static setSourceType: typeof setSourceType;\n static registerForPluginStateChange: typeof registerForPluginStateChange;\n\n constructor(map: Map, options: StyleOptions = {}) {\n super();\n\n this.map = map;\n this.dispatcher = new Dispatcher(getWorkerPool(), this);\n this.imageManager = new ImageManager();\n this.imageManager.setEventedParent(this);\n this.glyphManager = new GlyphManager(map._requestManager, options.localIdeographFontFamily);\n this.lineAtlas = new LineAtlas(256, 512);\n this.crossTileSymbolIndex = new CrossTileSymbolIndex();\n\n this._layers = {};\n this._serializedLayers = {};\n this._order = [];\n this.sourceCaches = {};\n this.zoomHistory = new ZoomHistory();\n this._loaded = false;\n this._availableImages = [];\n\n this._resetUpdates();\n\n this.dispatcher.broadcast('setReferrer', getReferrer());\n\n const self = this;\n this._rtlTextPluginCallback = Style.registerForPluginStateChange((event) => {\n const state = {\n pluginStatus: event.pluginStatus,\n pluginURL: event.pluginURL\n };\n self.dispatcher.broadcast('syncRTLPluginState', state, (err, results) => {\n triggerPluginCompletionEvent(err);\n if (results) {\n const allComplete = results.every((elem) => elem);\n if (allComplete) {\n for (const id in self.sourceCaches) {\n self.sourceCaches[id].reload(); // Should be a no-op if the plugin loads before any tiles load\n }\n }\n }\n\n });\n });\n\n this.on('data', (event) => {\n if (event.dataType !== 'source' || event.sourceDataType !== 'metadata') {\n return;\n }\n\n const sourceCache = this.sourceCaches[event.sourceId];\n if (!sourceCache) {\n return;\n }\n\n const source = sourceCache.getSource();\n if (!source || !source.vectorLayerIds) {\n return;\n }\n\n for (const layerId in this._layers) {\n const layer = this._layers[layerId];\n if (layer.source === source.id) {\n this._validateLayer(layer);\n }\n }\n });\n }\n\n loadURL(url: string, options: {\n validate?: boolean,\n accessToken?: string\n } = {}) {\n this.fire(new Event('dataloading', {dataType: 'style'}));\n\n const validate = typeof options.validate === 'boolean' ?\n options.validate : !isMapboxURL(url);\n\n url = this.map._requestManager.normalizeStyleURL(url, options.accessToken);\n const request = this.map._requestManager.transformRequest(url, ResourceType.Style);\n this._request = getJSON(request, (error: ?Error, json: ?Object) => {\n this._request = null;\n if (error) {\n this.fire(new ErrorEvent(error));\n } else if (json) {\n this._load(json, validate);\n }\n });\n }\n\n loadJSON(json: StyleSpecification, options: StyleSetterOptions = {}) {\n this.fire(new Event('dataloading', {dataType: 'style'}));\n\n this._request = browser.frame(() => {\n this._request = null;\n this._load(json, options.validate !== false);\n });\n }\n\n loadEmpty() {\n this.fire(new Event('dataloading', {dataType: 'style'}));\n this._load(empty, false);\n }\n\n _load(json: StyleSpecification, validate: boolean) {\n if (validate && emitValidationErrors(this, validateStyle(json))) {\n return;\n }\n\n this._loaded = true;\n this.stylesheet = json;\n\n for (const id in json.sources) {\n this.addSource(id, json.sources[id], {validate: false});\n }\n\n if (json.sprite) {\n this._loadSprite(json.sprite);\n } else {\n this.imageManager.setLoaded(true);\n }\n\n this.glyphManager.setURL(json.glyphs);\n\n const layers = deref(this.stylesheet.layers);\n\n this._order = layers.map((layer) => layer.id);\n\n this._layers = {};\n this._serializedLayers = {};\n for (let layer of layers) {\n layer = createStyleLayer(layer);\n layer.setEventedParent(this, {layer: {id: layer.id}});\n this._layers[layer.id] = layer;\n this._serializedLayers[layer.id] = layer.serialize();\n }\n this.dispatcher.broadcast('setLayers', this._serializeLayers(this._order));\n\n this.light = new Light(this.stylesheet.light);\n\n this.fire(new Event('data', {dataType: 'style'}));\n this.fire(new Event('style.load'));\n }\n\n _loadSprite(url: string) {\n this._spriteRequest = loadSprite(url, this.map._requestManager, (err, images) => {\n this._spriteRequest = null;\n if (err) {\n this.fire(new ErrorEvent(err));\n } else if (images) {\n for (const id in images) {\n this.imageManager.addImage(id, images[id]);\n }\n }\n\n this.imageManager.setLoaded(true);\n this._availableImages = this.imageManager.listImages();\n this.dispatcher.broadcast('setImages', this._availableImages);\n this.fire(new Event('data', {dataType: 'style'}));\n });\n }\n\n _validateLayer(layer: StyleLayer) {\n const sourceCache = this.sourceCaches[layer.source];\n if (!sourceCache) {\n return;\n }\n\n const sourceLayer = layer.sourceLayer;\n if (!sourceLayer) {\n return;\n }\n\n const source = sourceCache.getSource();\n if (source.type === 'geojson' || (source.vectorLayerIds && source.vectorLayerIds.indexOf(sourceLayer) === -1)) {\n this.fire(new ErrorEvent(new Error(\n `Source layer \"${sourceLayer}\" ` +\n `does not exist on source \"${source.id}\" ` +\n `as specified by style layer \"${layer.id}\"`\n )));\n }\n }\n\n loaded() {\n if (!this._loaded)\n return false;\n\n if (Object.keys(this._updatedSources).length)\n return false;\n\n for (const id in this.sourceCaches)\n if (!this.sourceCaches[id].loaded())\n return false;\n\n if (!this.imageManager.isLoaded())\n return false;\n\n return true;\n }\n\n _serializeLayers(ids: Array): Array {\n const serializedLayers = [];\n for (const id of ids) {\n const layer = this._layers[id];\n if (layer.type !== 'custom') {\n serializedLayers.push(layer.serialize());\n }\n }\n return serializedLayers;\n }\n\n hasTransitions() {\n if (this.light && this.light.hasTransition()) {\n return true;\n }\n\n for (const id in this.sourceCaches) {\n if (this.sourceCaches[id].hasTransition()) {\n return true;\n }\n }\n\n for (const id in this._layers) {\n if (this._layers[id].hasTransition()) {\n return true;\n }\n }\n\n return false;\n }\n\n _checkLoaded() {\n if (!this._loaded) {\n throw new Error('Style is not done loading');\n }\n }\n\n /**\n * Apply queued style updates in a batch and recalculate zoom-dependent paint properties.\n * @private\n */\n update(parameters: EvaluationParameters) {\n if (!this._loaded) {\n return;\n }\n\n const changed = this._changed;\n if (this._changed) {\n const updatedIds = Object.keys(this._updatedLayers);\n const removedIds = Object.keys(this._removedLayers);\n\n if (updatedIds.length || removedIds.length) {\n this._updateWorkerLayers(updatedIds, removedIds);\n }\n for (const id in this._updatedSources) {\n const action = this._updatedSources[id];\n assert(action === 'reload' || action === 'clear');\n if (action === 'reload') {\n this._reloadSource(id);\n } else if (action === 'clear') {\n this._clearSource(id);\n }\n }\n\n this._updateTilesForChangedImages();\n\n for (const id in this._updatedPaintProps) {\n this._layers[id].updateTransitions(parameters);\n }\n\n this.light.updateTransitions(parameters);\n\n this._resetUpdates();\n }\n\n const sourcesUsedBefore = {};\n\n for (const sourceId in this.sourceCaches) {\n const sourceCache = this.sourceCaches[sourceId];\n sourcesUsedBefore[sourceId] = sourceCache.used;\n sourceCache.used = false;\n }\n\n for (const layerId of this._order) {\n const layer = this._layers[layerId];\n\n layer.recalculate(parameters, this._availableImages);\n if (!layer.isHidden(parameters.zoom) && layer.source) {\n this.sourceCaches[layer.source].used = true;\n }\n }\n\n for (const sourceId in sourcesUsedBefore) {\n const sourceCache = this.sourceCaches[sourceId];\n if (sourcesUsedBefore[sourceId] !== sourceCache.used) {\n sourceCache.fire(new Event('data', {sourceDataType: 'visibility', dataType:'source', sourceId}));\n }\n }\n\n this.light.recalculate(parameters);\n this.z = parameters.zoom;\n\n if (changed) {\n this.fire(new Event('data', {dataType: 'style'}));\n }\n\n }\n\n /*\n * Apply any queued image changes.\n */\n _updateTilesForChangedImages() {\n const changedImages = Object.keys(this._changedImages);\n if (changedImages.length) {\n for (const name in this.sourceCaches) {\n this.sourceCaches[name].reloadTilesForDependencies(['icons', 'patterns'], changedImages);\n }\n this._changedImages = {};\n }\n }\n\n _updateWorkerLayers(updatedIds: Array, removedIds: Array) {\n this.dispatcher.broadcast('updateLayers', {\n layers: this._serializeLayers(updatedIds),\n removedIds\n });\n }\n\n _resetUpdates() {\n this._changed = false;\n\n this._updatedLayers = {};\n this._removedLayers = {};\n\n this._updatedSources = {};\n this._updatedPaintProps = {};\n\n this._changedImages = {};\n }\n\n /**\n * Update this style's state to match the given style JSON, performing only\n * the necessary mutations.\n *\n * May throw an Error ('Unimplemented: METHOD') if the mapbox-gl-style-spec\n * diff algorithm produces an operation that is not supported.\n *\n * @returns {boolean} true if any changes were made; false otherwise\n * @private\n */\n setState(nextState: StyleSpecification) {\n this._checkLoaded();\n\n if (emitValidationErrors(this, validateStyle(nextState))) return false;\n\n nextState = clone(nextState);\n nextState.layers = deref(nextState.layers);\n\n const changes = diffStyles(this.serialize(), nextState)\n .filter(op => !(op.command in ignoredDiffOperations));\n\n if (changes.length === 0) {\n return false;\n }\n\n const unimplementedOps = changes.filter(op => !(op.command in supportedDiffOperations));\n if (unimplementedOps.length > 0) {\n throw new Error(`Unimplemented: ${unimplementedOps.map(op => op.command).join(', ')}.`);\n }\n\n changes.forEach((op) => {\n if (op.command === 'setTransition') {\n // `transition` is always read directly off of\n // `this.stylesheet`, which we update below\n return;\n }\n (this: any)[op.command].apply(this, op.args);\n });\n\n this.stylesheet = nextState;\n\n return true;\n }\n\n addImage(id: string, image: StyleImage) {\n if (this.getImage(id)) {\n return this.fire(new ErrorEvent(new Error('An image with this name already exists.')));\n }\n this.imageManager.addImage(id, image);\n this._afterImageUpdated(id);\n }\n\n updateImage(id: string, image: StyleImage) {\n this.imageManager.updateImage(id, image);\n }\n\n getImage(id: string): ?StyleImage {\n return this.imageManager.getImage(id);\n }\n\n removeImage(id: string) {\n if (!this.getImage(id)) {\n return this.fire(new ErrorEvent(new Error('No image with this name exists.')));\n }\n this.imageManager.removeImage(id);\n this._afterImageUpdated(id);\n }\n\n _afterImageUpdated(id: string) {\n this._availableImages = this.imageManager.listImages();\n this._changedImages[id] = true;\n this._changed = true;\n this.dispatcher.broadcast('setImages', this._availableImages);\n this.fire(new Event('data', {dataType: 'style'}));\n }\n\n listImages() {\n this._checkLoaded();\n\n return this.imageManager.listImages();\n }\n\n addSource(id: string, source: SourceSpecification, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n\n if (this.sourceCaches[id] !== undefined) {\n throw new Error('There is already a source with this ID');\n }\n\n if (!source.type) {\n throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(source).join(', ')}.`);\n }\n\n const builtIns = ['vector', 'raster', 'geojson', 'video', 'image'];\n const shouldValidate = builtIns.indexOf(source.type) >= 0;\n if (shouldValidate && this._validate(validateStyle.source, `sources.${id}`, source, null, options)) return;\n\n if (this.map && this.map._collectResourceTiming) (source: any).collectResourceTiming = true;\n const sourceCache = this.sourceCaches[id] = new SourceCache(id, source, this.dispatcher);\n sourceCache.style = this;\n sourceCache.setEventedParent(this, () => ({\n isSourceLoaded: this.loaded(),\n source: sourceCache.serialize(),\n sourceId: id\n }));\n\n sourceCache.onAdd(this.map);\n this._changed = true;\n }\n\n /**\n * Remove a source from this stylesheet, given its id.\n * @param {string} id id of the source to remove\n * @throws {Error} if no source is found with the given ID\n * @returns {Map} The {@link Map} object.\n */\n removeSource(id: string) {\n this._checkLoaded();\n\n if (this.sourceCaches[id] === undefined) {\n throw new Error('There is no source with this ID');\n }\n for (const layerId in this._layers) {\n if (this._layers[layerId].source === id) {\n return this.fire(new ErrorEvent(new Error(`Source \"${id}\" cannot be removed while layer \"${layerId}\" is using it.`)));\n }\n }\n\n const sourceCache = this.sourceCaches[id];\n delete this.sourceCaches[id];\n delete this._updatedSources[id];\n sourceCache.fire(new Event('data', {sourceDataType: 'metadata', dataType:'source', sourceId: id}));\n sourceCache.setEventedParent(null);\n sourceCache.clearTiles();\n\n if (sourceCache.onRemove) sourceCache.onRemove(this.map);\n this._changed = true;\n }\n\n /**\n * Set the data of a GeoJSON source, given its id.\n * @param {string} id id of the source\n * @param {GeoJSON|string} data GeoJSON source\n */\n setGeoJSONSourceData(id: string, data: GeoJSON | string) {\n this._checkLoaded();\n\n assert(this.sourceCaches[id] !== undefined, 'There is no source with this ID');\n const geojsonSource: GeoJSONSource = (this.sourceCaches[id].getSource(): any);\n assert(geojsonSource.type === 'geojson');\n\n geojsonSource.setData(data);\n this._changed = true;\n }\n\n /**\n * Get a source by id.\n * @param {string} id id of the desired source\n * @returns {Object} source\n */\n getSource(id: string): Object {\n return this.sourceCaches[id] && this.sourceCaches[id].getSource();\n }\n\n /**\n * Add a layer to the map style. The layer will be inserted before the layer with\n * ID `before`, or appended if `before` is omitted.\n * @param {Object | CustomLayerInterface} layerObject The style layer to add.\n * @param {string} [before] ID of an existing layer to insert before\n * @param {Object} options Style setter options.\n * @returns {Map} The {@link Map} object.\n */\n addLayer(layerObject: LayerSpecification | CustomLayerInterface, before?: string, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n\n const id = layerObject.id;\n\n if (this.getLayer(id)) {\n this.fire(new ErrorEvent(new Error(`Layer with id \"${id}\" already exists on this map`)));\n return;\n }\n\n let layer;\n if (layerObject.type === 'custom') {\n\n if (emitValidationErrors(this, validateCustomStyleLayer(layerObject))) return;\n\n layer = createStyleLayer(layerObject);\n\n } else {\n if (typeof layerObject.source === 'object') {\n this.addSource(id, layerObject.source);\n layerObject = clone(layerObject);\n layerObject = (extend(layerObject, {source: id}): any);\n }\n\n // this layer is not in the style.layers array, so we pass an impossible array index\n if (this._validate(validateStyle.layer,\n `layers.${id}`, layerObject, {arrayIndex: -1}, options)) return;\n\n layer = createStyleLayer(layerObject);\n this._validateLayer(layer);\n\n layer.setEventedParent(this, {layer: {id}});\n this._serializedLayers[layer.id] = layer.serialize();\n }\n\n const index = before ? this._order.indexOf(before) : this._order.length;\n if (before && index === -1) {\n this.fire(new ErrorEvent(new Error(`Layer with id \"${before}\" does not exist on this map.`)));\n return;\n }\n\n this._order.splice(index, 0, id);\n this._layerOrderChanged = true;\n\n this._layers[id] = layer;\n\n if (this._removedLayers[id] && layer.source && layer.type !== 'custom') {\n // If, in the current batch, we have already removed this layer\n // and we are now re-adding it with a different `type`, then we\n // need to clear (rather than just reload) the underyling source's\n // tiles. Otherwise, tiles marked 'reloading' will have buckets /\n // buffers that are set up for the _previous_ version of this\n // layer, causing, e.g.:\n // https://github.com/mapbox/mapbox-gl-js/issues/3633\n const removed = this._removedLayers[id];\n delete this._removedLayers[id];\n if (removed.type !== layer.type) {\n this._updatedSources[layer.source] = 'clear';\n } else {\n this._updatedSources[layer.source] = 'reload';\n this.sourceCaches[layer.source].pause();\n }\n }\n this._updateLayer(layer);\n\n if (layer.onAdd) {\n layer.onAdd(this.map);\n }\n }\n\n /**\n * Moves a layer to a different z-position. The layer will be inserted before the layer with\n * ID `before`, or appended if `before` is omitted.\n * @param {string} id ID of the layer to move\n * @param {string} [before] ID of an existing layer to insert before\n */\n moveLayer(id: string, before?: string) {\n this._checkLoaded();\n this._changed = true;\n\n const layer = this._layers[id];\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`The layer '${id}' does not exist in the map's style and cannot be moved.`)));\n return;\n }\n\n if (id === before) {\n return;\n }\n\n const index = this._order.indexOf(id);\n this._order.splice(index, 1);\n\n const newIndex = before ? this._order.indexOf(before) : this._order.length;\n if (before && newIndex === -1) {\n this.fire(new ErrorEvent(new Error(`Layer with id \"${before}\" does not exist on this map.`)));\n return;\n }\n this._order.splice(newIndex, 0, id);\n\n this._layerOrderChanged = true;\n }\n\n /**\n * Remove the layer with the given id from the style.\n *\n * If no such layer exists, an `error` event is fired.\n *\n * @param {string} id id of the layer to remove\n * @fires error\n */\n removeLayer(id: string) {\n this._checkLoaded();\n\n const layer = this._layers[id];\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`The layer '${id}' does not exist in the map's style and cannot be removed.`)));\n return;\n }\n\n layer.setEventedParent(null);\n\n const index = this._order.indexOf(id);\n this._order.splice(index, 1);\n\n this._layerOrderChanged = true;\n this._changed = true;\n this._removedLayers[id] = layer;\n delete this._layers[id];\n delete this._serializedLayers[id];\n delete this._updatedLayers[id];\n delete this._updatedPaintProps[id];\n\n if (layer.onRemove) {\n layer.onRemove(this.map);\n }\n }\n\n /**\n * Return the style layer object with the given `id`.\n *\n * @param {string} id - id of the desired layer\n * @returns {?Object} a layer, if one with the given `id` exists\n */\n getLayer(id: string): Object {\n return this._layers[id];\n }\n\n /**\n * checks if a specific layer is present within the style.\n *\n * @param {string} id - id of the desired layer\n * @returns {boolean} a boolean specifying if the given layer is present\n */\n hasLayer(id: string): boolean {\n return id in this._layers;\n }\n\n setLayerZoomRange(layerId: string, minzoom: ?number, maxzoom: ?number) {\n this._checkLoaded();\n\n const layer = this.getLayer(layerId);\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot have zoom extent.`)));\n return;\n }\n\n if (layer.minzoom === minzoom && layer.maxzoom === maxzoom) return;\n\n if (minzoom != null) {\n layer.minzoom = minzoom;\n }\n if (maxzoom != null) {\n layer.maxzoom = maxzoom;\n }\n this._updateLayer(layer);\n }\n\n setFilter(layerId: string, filter: ?FilterSpecification, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n\n const layer = this.getLayer(layerId);\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be filtered.`)));\n return;\n }\n\n if (deepEqual(layer.filter, filter)) {\n return;\n }\n\n if (filter === null || filter === undefined) {\n layer.filter = undefined;\n this._updateLayer(layer);\n return;\n }\n\n if (this._validate(validateStyle.filter, `layers.${layer.id}.filter`, filter, null, options)) {\n return;\n }\n\n layer.filter = clone(filter);\n this._updateLayer(layer);\n }\n\n /**\n * Get a layer's filter object\n * @param {string} layer the layer to inspect\n * @returns {*} the layer's filter, if any\n */\n getFilter(layer: string) {\n return clone(this.getLayer(layer).filter);\n }\n\n setLayoutProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n\n const layer = this.getLayer(layerId);\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be styled.`)));\n return;\n }\n\n if (deepEqual(layer.getLayoutProperty(name), value)) return;\n\n layer.setLayoutProperty(name, value, options);\n this._updateLayer(layer);\n }\n\n /**\n * Get a layout property's value from a given layer\n * @param {string} layerId the layer to inspect\n * @param {string} name the name of the layout property\n * @returns {*} the property value\n */\n getLayoutProperty(layerId: string, name: string) {\n const layer = this.getLayer(layerId);\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style.`)));\n return;\n }\n\n return layer.getLayoutProperty(name);\n }\n\n setPaintProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n\n const layer = this.getLayer(layerId);\n if (!layer) {\n this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be styled.`)));\n return;\n }\n\n if (deepEqual(layer.getPaintProperty(name), value)) return;\n\n const requiresRelayout = layer.setPaintProperty(name, value, options);\n if (requiresRelayout) {\n this._updateLayer(layer);\n }\n\n this._changed = true;\n this._updatedPaintProps[layerId] = true;\n }\n\n getPaintProperty(layer: string, name: string) {\n return this.getLayer(layer).getPaintProperty(name);\n }\n\n setFeatureState(target: { source: string; sourceLayer?: string; id: string | number; }, state: Object) {\n this._checkLoaded();\n const sourceId = target.source;\n const sourceLayer = target.sourceLayer;\n const sourceCache = this.sourceCaches[sourceId];\n\n if (sourceCache === undefined) {\n this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));\n return;\n }\n const sourceType = sourceCache.getSource().type;\n if (sourceType === 'geojson' && sourceLayer) {\n this.fire(new ErrorEvent(new Error(`GeoJSON sources cannot have a sourceLayer parameter.`)));\n return;\n }\n if (sourceType === 'vector' && !sourceLayer) {\n this.fire(new ErrorEvent(new Error(`The sourceLayer parameter must be provided for vector source types.`)));\n return;\n }\n if (target.id === undefined) {\n this.fire(new ErrorEvent(new Error(`The feature id parameter must be provided.`)));\n }\n\n sourceCache.setFeatureState(sourceLayer, target.id, state);\n }\n\n removeFeatureState(target: { source: string; sourceLayer?: string; id?: string | number; }, key?: string) {\n this._checkLoaded();\n const sourceId = target.source;\n const sourceCache = this.sourceCaches[sourceId];\n\n if (sourceCache === undefined) {\n this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));\n return;\n }\n\n const sourceType = sourceCache.getSource().type;\n const sourceLayer = sourceType === 'vector' ? target.sourceLayer : undefined;\n\n if (sourceType === 'vector' && !sourceLayer) {\n this.fire(new ErrorEvent(new Error(`The sourceLayer parameter must be provided for vector source types.`)));\n return;\n }\n\n if (key && (typeof target.id !== 'string' && typeof target.id !== 'number')) {\n this.fire(new ErrorEvent(new Error(`A feature id is required to remove its specific state property.`)));\n return;\n }\n\n sourceCache.removeFeatureState(sourceLayer, target.id, key);\n }\n\n getFeatureState(target: { source: string; sourceLayer?: string; id: string | number; }) {\n this._checkLoaded();\n const sourceId = target.source;\n const sourceLayer = target.sourceLayer;\n const sourceCache = this.sourceCaches[sourceId];\n\n if (sourceCache === undefined) {\n this.fire(new ErrorEvent(new Error(`The source '${sourceId}' does not exist in the map's style.`)));\n return;\n }\n const sourceType = sourceCache.getSource().type;\n if (sourceType === 'vector' && !sourceLayer) {\n this.fire(new ErrorEvent(new Error(`The sourceLayer parameter must be provided for vector source types.`)));\n return;\n }\n if (target.id === undefined) {\n this.fire(new ErrorEvent(new Error(`The feature id parameter must be provided.`)));\n }\n\n return sourceCache.getFeatureState(sourceLayer, target.id);\n }\n\n getTransition() {\n return extend({duration: 300, delay: 0}, this.stylesheet && this.stylesheet.transition);\n }\n\n serialize() {\n return filterObject({\n version: this.stylesheet.version,\n name: this.stylesheet.name,\n metadata: this.stylesheet.metadata,\n light: this.stylesheet.light,\n center: this.stylesheet.center,\n zoom: this.stylesheet.zoom,\n bearing: this.stylesheet.bearing,\n pitch: this.stylesheet.pitch,\n sprite: this.stylesheet.sprite,\n glyphs: this.stylesheet.glyphs,\n transition: this.stylesheet.transition,\n sources: mapObject(this.sourceCaches, (source) => source.serialize()),\n layers: this._serializeLayers(this._order)\n }, (value) => { return value !== undefined; });\n }\n\n _updateLayer(layer: StyleLayer) {\n this._updatedLayers[layer.id] = true;\n if (layer.source && !this._updatedSources[layer.source] &&\n //Skip for raster layers (https://github.com/mapbox/mapbox-gl-js/issues/7865)\n this.sourceCaches[layer.source].getSource().type !== 'raster') {\n this._updatedSources[layer.source] = 'reload';\n this.sourceCaches[layer.source].pause();\n }\n this._changed = true;\n }\n\n _flattenAndSortRenderedFeatures(sourceResults: Array) {\n // Feature order is complicated.\n // The order between features in two 2D layers is always determined by layer order.\n // The order between features in two 3D layers is always determined by depth.\n // The order between a feature in a 2D layer and a 3D layer is tricky:\n // Most often layer order determines the feature order in this case. If\n // a line layer is above a extrusion layer the line feature will be rendered\n // above the extrusion. If the line layer is below the extrusion layer,\n // it will be rendered below it.\n //\n // There is a weird case though.\n // You have layers in this order: extrusion_layer_a, line_layer, extrusion_layer_b\n // Each layer has a feature that overlaps the other features.\n // The feature in extrusion_layer_a is closer than the feature in extrusion_layer_b so it is rendered above.\n // The feature in line_layer is rendered above extrusion_layer_a.\n // This means that that the line_layer feature is above the extrusion_layer_b feature despite\n // it being in an earlier layer.\n\n const isLayer3D = layerId => this._layers[layerId].type === 'fill-extrusion';\n\n const layerIndex = {};\n const features3D = [];\n for (let l = this._order.length - 1; l >= 0; l--) {\n const layerId = this._order[l];\n if (isLayer3D(layerId)) {\n layerIndex[layerId] = l;\n for (const sourceResult of sourceResults) {\n const layerFeatures = sourceResult[layerId];\n if (layerFeatures) {\n for (const featureWrapper of layerFeatures) {\n features3D.push(featureWrapper);\n }\n }\n }\n }\n }\n\n features3D.sort((a, b) => {\n return b.intersectionZ - a.intersectionZ;\n });\n\n const features = [];\n for (let l = this._order.length - 1; l >= 0; l--) {\n const layerId = this._order[l];\n\n if (isLayer3D(layerId)) {\n // add all 3D features that are in or above the current layer\n for (let i = features3D.length - 1; i >= 0; i--) {\n const topmost3D = features3D[i].feature;\n if (layerIndex[topmost3D.layer.id] < l) break;\n features.push(topmost3D);\n features3D.pop();\n }\n } else {\n for (const sourceResult of sourceResults) {\n const layerFeatures = sourceResult[layerId];\n if (layerFeatures) {\n for (const featureWrapper of layerFeatures) {\n features.push(featureWrapper.feature);\n }\n }\n }\n }\n }\n\n return features;\n }\n\n queryRenderedFeatures(queryGeometry: any, params: any, transform: Transform) {\n if (params && params.filter) {\n this._validate(validateStyle.filter, 'queryRenderedFeatures.filter', params.filter, null, params);\n }\n\n const includedSources = {};\n if (params && params.layers) {\n if (!Array.isArray(params.layers)) {\n this.fire(new ErrorEvent(new Error('parameters.layers must be an Array.')));\n return [];\n }\n for (const layerId of params.layers) {\n const layer = this._layers[layerId];\n if (!layer) {\n // this layer is not in the style.layers array\n this.fire(new ErrorEvent(new Error(`The layer '${layerId}' does not exist in the map's style and cannot be queried for features.`)));\n return [];\n }\n includedSources[layer.source] = true;\n }\n }\n\n const sourceResults = [];\n\n params.availableImages = this._availableImages;\n\n for (const id in this.sourceCaches) {\n if (params.layers && !includedSources[id]) continue;\n sourceResults.push(\n queryRenderedFeatures(\n this.sourceCaches[id],\n this._layers,\n this._serializedLayers,\n queryGeometry,\n params,\n transform)\n );\n }\n\n if (this.placement) {\n // If a placement has run, query against its CollisionIndex\n // for symbol results, and treat it as an extra source to merge\n sourceResults.push(\n queryRenderedSymbols(\n this._layers,\n this._serializedLayers,\n this.sourceCaches,\n queryGeometry,\n params,\n this.placement.collisionIndex,\n this.placement.retainedQueryData)\n );\n }\n\n return this._flattenAndSortRenderedFeatures(sourceResults);\n }\n\n querySourceFeatures(sourceID: string, params: ?{sourceLayer: ?string, filter: ?Array, validate?: boolean}) {\n if (params && params.filter) {\n this._validate(validateStyle.filter, 'querySourceFeatures.filter', params.filter, null, params);\n }\n const sourceCache = this.sourceCaches[sourceID];\n return sourceCache ? querySourceFeatures(sourceCache, params) : [];\n }\n\n addSourceType(name: string, SourceType: SourceClass, callback: Callback) {\n if (Style.getSourceType(name)) {\n return callback(new Error(`A source type called \"${name}\" already exists.`));\n }\n\n Style.setSourceType(name, SourceType);\n\n if (!SourceType.workerSourceURL) {\n return callback(null, null);\n }\n\n this.dispatcher.broadcast('loadWorkerSource', {\n name,\n url: SourceType.workerSourceURL\n }, callback);\n }\n\n getLight() {\n return this.light.getLight();\n }\n\n setLight(lightOptions: LightSpecification, options: StyleSetterOptions = {}) {\n this._checkLoaded();\n\n const light = this.light.getLight();\n let _update = false;\n for (const key in lightOptions) {\n if (!deepEqual(lightOptions[key], light[key])) {\n _update = true;\n break;\n }\n }\n if (!_update) return;\n\n const parameters = {\n now: browser.now(),\n transition: extend({\n duration: 300,\n delay: 0\n }, this.stylesheet.transition)\n };\n\n this.light.setLight(lightOptions, options);\n this.light.updateTransitions(parameters);\n }\n\n _validate(validate: Validator, key: string, value: any, props: any, options: { validate?: boolean } = {}) {\n if (options && options.validate === false) {\n return false;\n }\n return emitValidationErrors(this, validate.call(validateStyle, extend({\n key,\n style: this.serialize(),\n value,\n styleSpec\n }, props)));\n }\n\n _remove() {\n if (this._request) {\n this._request.cancel();\n this._request = null;\n }\n if (this._spriteRequest) {\n this._spriteRequest.cancel();\n this._spriteRequest = null;\n }\n rtlTextPluginEvented.off('pluginStateChange', this._rtlTextPluginCallback);\n for (const layerId in this._layers) {\n const layer: StyleLayer = this._layers[layerId];\n layer.setEventedParent(null);\n }\n for (const id in this.sourceCaches) {\n this.sourceCaches[id].clearTiles();\n this.sourceCaches[id].setEventedParent(null);\n }\n this.imageManager.setEventedParent(null);\n this.setEventedParent(null);\n this.dispatcher.remove();\n }\n\n _clearSource(id: string) {\n this.sourceCaches[id].clearTiles();\n }\n\n _reloadSource(id: string) {\n this.sourceCaches[id].resume();\n this.sourceCaches[id].reload();\n }\n\n _updateSources(transform: Transform) {\n for (const id in this.sourceCaches) {\n this.sourceCaches[id].update(transform);\n }\n }\n\n _generateCollisionBoxes() {\n for (const id in this.sourceCaches) {\n this._reloadSource(id);\n }\n }\n\n _updatePlacement(transform: Transform, showCollisionBoxes: boolean, fadeDuration: number, crossSourceCollisions: boolean, forceFullPlacement: boolean = false) {\n let symbolBucketsChanged = false;\n let placementCommitted = false;\n\n const layerTiles = {};\n\n for (const layerID of this._order) {\n const styleLayer = this._layers[layerID];\n if (styleLayer.type !== 'symbol') continue;\n\n if (!layerTiles[styleLayer.source]) {\n const sourceCache = this.sourceCaches[styleLayer.source];\n layerTiles[styleLayer.source] = sourceCache.getRenderableIds(true)\n .map((id) => sourceCache.getTileByID(id))\n .sort((a, b) => (b.tileID.overscaledZ - a.tileID.overscaledZ) || (a.tileID.isLessThan(b.tileID) ? -1 : 1));\n }\n\n const layerBucketsChanged = this.crossTileSymbolIndex.addLayer(styleLayer, layerTiles[styleLayer.source], transform.center.lng);\n symbolBucketsChanged = symbolBucketsChanged || layerBucketsChanged;\n }\n this.crossTileSymbolIndex.pruneUnusedLayers(this._order);\n\n // Anything that changes our \"in progress\" layer and tile indices requires us\n // to start over. When we start over, we do a full placement instead of incremental\n // to prevent starvation.\n // We need to restart placement to keep layer indices in sync.\n // Also force full placement when fadeDuration === 0 to ensure that newly loaded\n // tiles will fully display symbols in their first frame\n forceFullPlacement = forceFullPlacement || this._layerOrderChanged || fadeDuration === 0;\n\n if (forceFullPlacement || !this.pauseablePlacement || (this.pauseablePlacement.isDone() && !this.placement.stillRecent(browser.now(), transform.zoom))) {\n this.pauseablePlacement = new PauseablePlacement(transform, this._order, forceFullPlacement, showCollisionBoxes, fadeDuration, crossSourceCollisions, this.placement);\n this._layerOrderChanged = false;\n }\n\n if (this.pauseablePlacement.isDone()) {\n // the last placement finished running, but the next one hasn’t\n // started yet because of the `stillRecent` check immediately\n // above, so mark it stale to ensure that we request another\n // render frame\n this.placement.setStale();\n } else {\n this.pauseablePlacement.continuePlacement(this._order, this._layers, layerTiles);\n\n if (this.pauseablePlacement.isDone()) {\n this.placement = this.pauseablePlacement.commit(browser.now());\n placementCommitted = true;\n }\n\n if (symbolBucketsChanged) {\n // since the placement gets split over multiple frames it is possible\n // these buckets were processed before they were changed and so the\n // placement is already stale while it is in progress\n this.pauseablePlacement.placement.setStale();\n }\n }\n\n if (placementCommitted || symbolBucketsChanged) {\n for (const layerID of this._order) {\n const styleLayer = this._layers[layerID];\n if (styleLayer.type !== 'symbol') continue;\n this.placement.updateLayerOpacities(styleLayer, layerTiles[styleLayer.source]);\n }\n }\n\n // needsRender is false when we have just finished a placement that didn't change the visibility of any symbols\n const needsRerender = !this.pauseablePlacement.isDone() || this.placement.hasTransitions(browser.now());\n return needsRerender;\n }\n\n _releaseSymbolFadeTiles() {\n for (const id in this.sourceCaches) {\n this.sourceCaches[id].releaseSymbolFadeTiles();\n }\n }\n\n // Callbacks from web workers\n\n getImages(mapId: string, params: {icons: Array, source: string, tileID: OverscaledTileID, type: string}, callback: Callback<{[_: string]: StyleImage}>) {\n\n this.imageManager.getImages(params.icons, callback);\n\n // Apply queued image changes before setting the tile's dependencies so that the tile\n // is not reloaded unecessarily. Without this forced update the reload could happen in cases\n // like this one:\n // - icons contains \"my-image\"\n // - imageManager.getImages(...) triggers `onstyleimagemissing`\n // - the user adds \"my-image\" within the callback\n // - addImage adds \"my-image\" to this._changedImages\n // - the next frame triggers a reload of this tile even though it already has the latest version\n this._updateTilesForChangedImages();\n\n const sourceCache = this.sourceCaches[params.source];\n if (sourceCache) {\n sourceCache.setDependencies(params.tileID.key, params.type, params.icons);\n }\n }\n\n getGlyphs(mapId: string, params: {stacks: {[_: string]: Array}}, callback: Callback<{[_: string]: {[_: number]: ?StyleGlyph}}>) {\n this.glyphManager.getGlyphs(params.stacks, callback);\n }\n\n getResource(mapId: string, params: RequestParameters, callback: ResponseCallback): Cancelable {\n return makeRequest(params, callback);\n }\n}\n\nStyle.getSourceType = getSourceType;\nStyle.setSourceType = setSourceType;\nStyle.registerForPluginStateChange = registerForPluginStateChange;\n\nexport default Style;\n","import latest from './reference/latest';\n\nexport default function emptyStyle() {\n const style = {};\n\n const version = latest['$version'];\n for (const styleKey in latest['$root']) {\n const spec = latest['$root'][styleKey];\n\n if (spec.required) {\n let value = null;\n if (styleKey === 'version') {\n value = version;\n } else {\n if (spec.type === 'array') {\n value = [];\n } else {\n value = {};\n }\n }\n\n if (value != null) {\n style[styleKey] = value;\n }\n }\n }\n\n return style;\n}\n","// @flow\n\nimport {getJSON, getImage, ResourceType} from '../util/ajax';\n\nimport browser from '../util/browser';\nimport {RGBAImage} from '../util/image';\n\nimport type {StyleImage} from './style_image';\nimport type {RequestManager} from '../util/mapbox';\nimport type {Callback} from '../types/callback';\nimport type {Cancelable} from '../types/cancelable';\n\nexport default function(baseURL: string,\n requestManager: RequestManager,\n callback: Callback<{[_: string]: StyleImage}>): Cancelable {\n let json: any, image, error;\n const format = browser.devicePixelRatio > 1 ? '@2x' : '';\n\n let jsonRequest = getJSON(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, '.json'), ResourceType.SpriteJSON), (err: ?Error, data: ?Object) => {\n jsonRequest = null;\n if (!error) {\n error = err;\n json = data;\n maybeComplete();\n }\n });\n\n let imageRequest = getImage(requestManager.transformRequest(requestManager.normalizeSpriteURL(baseURL, format, '.png'), ResourceType.SpriteImage), (err, img) => {\n imageRequest = null;\n if (!error) {\n error = err;\n image = img;\n maybeComplete();\n }\n });\n\n function maybeComplete() {\n if (error) {\n callback(error);\n } else if (json && image) {\n const imageData = browser.getImageData(image);\n const result = {};\n\n for (const id in json) {\n const {width, height, x, y, sdf, pixelRatio, stretchX, stretchY, content} = json[id];\n const data = new RGBAImage({width, height});\n RGBAImage.copy(imageData, data, {x, y}, {x: 0, y: 0}, {width, height});\n result[id] = {data, pixelRatio, sdf, stretchX, stretchY, content};\n }\n\n callback(null, result);\n }\n }\n\n return {\n cancel() {\n if (jsonRequest) {\n jsonRequest.cancel();\n jsonRequest = null;\n }\n if (imageRequest) {\n imageRequest.cancel();\n imageRequest = null;\n }\n }\n };\n}\n","// @flow\nimport {createLayout} from '../util/struct_array';\n\nexport default createLayout([\n {name: 'a_pos', type: 'Int16', components: 2}\n]);\n","\n// Disable Flow annotations here because Flow doesn't support importing GLSL files\n/* eslint-disable flowtype/require-valid-file-annotation */\n\nimport preludeFrag from './_prelude.fragment.glsl';\nimport preludeVert from './_prelude.vertex.glsl';\nimport backgroundFrag from './background.fragment.glsl';\nimport backgroundVert from './background.vertex.glsl';\nimport backgroundPatternFrag from './background_pattern.fragment.glsl';\nimport backgroundPatternVert from './background_pattern.vertex.glsl';\nimport circleFrag from './circle.fragment.glsl';\nimport circleVert from './circle.vertex.glsl';\nimport clippingMaskFrag from './clipping_mask.fragment.glsl';\nimport clippingMaskVert from './clipping_mask.vertex.glsl';\nimport heatmapFrag from './heatmap.fragment.glsl';\nimport heatmapVert from './heatmap.vertex.glsl';\nimport heatmapTextureFrag from './heatmap_texture.fragment.glsl';\nimport heatmapTextureVert from './heatmap_texture.vertex.glsl';\nimport collisionBoxFrag from './collision_box.fragment.glsl';\nimport collisionBoxVert from './collision_box.vertex.glsl';\nimport collisionCircleFrag from './collision_circle.fragment.glsl';\nimport collisionCircleVert from './collision_circle.vertex.glsl';\nimport debugFrag from './debug.fragment.glsl';\nimport debugVert from './debug.vertex.glsl';\nimport fillFrag from './fill.fragment.glsl';\nimport fillVert from './fill.vertex.glsl';\nimport fillOutlineFrag from './fill_outline.fragment.glsl';\nimport fillOutlineVert from './fill_outline.vertex.glsl';\nimport fillOutlinePatternFrag from './fill_outline_pattern.fragment.glsl';\nimport fillOutlinePatternVert from './fill_outline_pattern.vertex.glsl';\nimport fillPatternFrag from './fill_pattern.fragment.glsl';\nimport fillPatternVert from './fill_pattern.vertex.glsl';\nimport fillExtrusionFrag from './fill_extrusion.fragment.glsl';\nimport fillExtrusionVert from './fill_extrusion.vertex.glsl';\nimport fillExtrusionPatternFrag from './fill_extrusion_pattern.fragment.glsl';\nimport fillExtrusionPatternVert from './fill_extrusion_pattern.vertex.glsl';\nimport hillshadePrepareFrag from './hillshade_prepare.fragment.glsl';\nimport hillshadePrepareVert from './hillshade_prepare.vertex.glsl';\nimport hillshadeFrag from './hillshade.fragment.glsl';\nimport hillshadeVert from './hillshade.vertex.glsl';\nimport lineFrag from './line.fragment.glsl';\nimport lineVert from './line.vertex.glsl';\nimport lineGradientFrag from './line_gradient.fragment.glsl';\nimport lineGradientVert from './line_gradient.vertex.glsl';\nimport linePatternFrag from './line_pattern.fragment.glsl';\nimport linePatternVert from './line_pattern.vertex.glsl';\nimport lineSDFFrag from './line_sdf.fragment.glsl';\nimport lineSDFVert from './line_sdf.vertex.glsl';\nimport rasterFrag from './raster.fragment.glsl';\nimport rasterVert from './raster.vertex.glsl';\nimport symbolIconFrag from './symbol_icon.fragment.glsl';\nimport symbolIconVert from './symbol_icon.vertex.glsl';\nimport symbolSDFFrag from './symbol_sdf.fragment.glsl';\nimport symbolSDFVert from './symbol_sdf.vertex.glsl';\nimport symbolTextAndIconFrag from './symbol_text_and_icon.fragment.glsl';\nimport symbolTextAndIconVert from './symbol_text_and_icon.vertex.glsl';\n\nexport const prelude = compile(preludeFrag, preludeVert);\nexport const background = compile(backgroundFrag, backgroundVert);\nexport const backgroundPattern = compile(backgroundPatternFrag, backgroundPatternVert);\nexport const circle = compile(circleFrag, circleVert);\nexport const clippingMask = compile(clippingMaskFrag, clippingMaskVert);\nexport const heatmap = compile(heatmapFrag, heatmapVert);\nexport const heatmapTexture = compile(heatmapTextureFrag, heatmapTextureVert);\nexport const collisionBox = compile(collisionBoxFrag, collisionBoxVert);\nexport const collisionCircle = compile(collisionCircleFrag, collisionCircleVert);\nexport const debug = compile(debugFrag, debugVert);\nexport const fill = compile(fillFrag, fillVert);\nexport const fillOutline = compile(fillOutlineFrag, fillOutlineVert);\nexport const fillOutlinePattern = compile(fillOutlinePatternFrag, fillOutlinePatternVert);\nexport const fillPattern = compile(fillPatternFrag, fillPatternVert);\nexport const fillExtrusion = compile(fillExtrusionFrag, fillExtrusionVert);\nexport const fillExtrusionPattern = compile(fillExtrusionPatternFrag, fillExtrusionPatternVert);\nexport const hillshadePrepare = compile(hillshadePrepareFrag, hillshadePrepareVert);\nexport const hillshade = compile(hillshadeFrag, hillshadeVert);\nexport const line = compile(lineFrag, lineVert);\nexport const lineGradient = compile(lineGradientFrag, lineGradientVert);\nexport const linePattern = compile(linePatternFrag, linePatternVert);\nexport const lineSDF = compile(lineSDFFrag, lineSDFVert);\nexport const raster = compile(rasterFrag, rasterVert);\nexport const symbolIcon = compile(symbolIconFrag, symbolIconVert);\nexport const symbolSDF = compile(symbolSDFFrag, symbolSDFVert);\nexport const symbolTextAndIcon = compile(symbolTextAndIconFrag, symbolTextAndIconVert);\n\n// Expand #pragmas to #ifdefs.\n\nfunction compile(fragmentSource, vertexSource) {\n const re = /#pragma mapbox: ([\\w]+) ([\\w]+) ([\\w]+) ([\\w]+)/g;\n\n const staticAttributes = vertexSource.match(/attribute ([\\w]+) ([\\w]+)/g);\n const fragmentUniforms = fragmentSource.match(/uniform ([\\w]+) ([\\w]+)([\\s]*)([\\w]*)/g);\n const vertexUniforms = vertexSource.match(/uniform ([\\w]+) ([\\w]+)([\\s]*)([\\w]*)/g);\n const staticUniforms = vertexUniforms ? vertexUniforms.concat(fragmentUniforms) : fragmentUniforms;\n\n const fragmentPragmas = {};\n\n fragmentSource = fragmentSource.replace(re, (match, operation, precision, type, name) => {\n fragmentPragmas[name] = true;\n if (operation === 'define') {\n return `\n#ifndef HAS_UNIFORM_u_${name}\nvarying ${precision} ${type} ${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`;\n } else /* if (operation === 'initialize') */ {\n return `\n#ifdef HAS_UNIFORM_u_${name}\n ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n }\n });\n\n vertexSource = vertexSource.replace(re, (match, operation, precision, type, name) => {\n const attrType = type === 'float' ? 'vec2' : 'vec4';\n const unpackType = name.match(/color/) ? 'color' : attrType;\n\n if (fragmentPragmas[name]) {\n if (operation === 'define') {\n return `\n#ifndef HAS_UNIFORM_u_${name}\nuniform lowp float u_${name}_t;\nattribute ${precision} ${attrType} a_${name};\nvarying ${precision} ${type} ${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`;\n } else /* if (operation === 'initialize') */ {\n if (unpackType === 'vec4') {\n // vec4 attributes are only used for cross-faded properties, and are not packed\n return `\n#ifndef HAS_UNIFORM_u_${name}\n ${name} = a_${name};\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n } else {\n return `\n#ifndef HAS_UNIFORM_u_${name}\n ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t);\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n }\n }\n } else {\n if (operation === 'define') {\n return `\n#ifndef HAS_UNIFORM_u_${name}\nuniform lowp float u_${name}_t;\nattribute ${precision} ${attrType} a_${name};\n#else\nuniform ${precision} ${type} u_${name};\n#endif\n`;\n } else /* if (operation === 'initialize') */ {\n if (unpackType === 'vec4') {\n // vec4 attributes are only used for cross-faded properties, and are not packed\n return `\n#ifndef HAS_UNIFORM_u_${name}\n ${precision} ${type} ${name} = a_${name};\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n } else /* */{\n return `\n#ifndef HAS_UNIFORM_u_${name}\n ${precision} ${type} ${name} = unpack_mix_${unpackType}(a_${name}, u_${name}_t);\n#else\n ${precision} ${type} ${name} = u_${name};\n#endif\n`;\n }\n }\n }\n });\n\n return {fragmentSource, vertexSource, staticAttributes, staticUniforms};\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport type Program from './program';\nimport type VertexBuffer from '../gl/vertex_buffer';\nimport type IndexBuffer from '../gl/index_buffer';\nimport type Context from '../gl/context';\n\nclass VertexArrayObject {\n context: Context;\n boundProgram: ?Program<*>;\n boundLayoutVertexBuffer: ?VertexBuffer;\n boundPaintVertexBuffers: Array;\n boundIndexBuffer: ?IndexBuffer;\n boundVertexOffset: ?number;\n boundDynamicVertexBuffer: ?VertexBuffer;\n boundDynamicVertexBuffer2: ?VertexBuffer;\n vao: any;\n\n constructor() {\n this.boundProgram = null;\n this.boundLayoutVertexBuffer = null;\n this.boundPaintVertexBuffers = [];\n this.boundIndexBuffer = null;\n this.boundVertexOffset = null;\n this.boundDynamicVertexBuffer = null;\n this.vao = null;\n }\n\n bind(context: Context,\n program: Program<*>,\n layoutVertexBuffer: VertexBuffer,\n paintVertexBuffers: Array,\n indexBuffer: ?IndexBuffer,\n vertexOffset: ?number,\n dynamicVertexBuffer: ?VertexBuffer,\n dynamicVertexBuffer2: ?VertexBuffer) {\n\n this.context = context;\n\n let paintBuffersDiffer = this.boundPaintVertexBuffers.length !== paintVertexBuffers.length;\n for (let i = 0; !paintBuffersDiffer && i < paintVertexBuffers.length; i++) {\n if (this.boundPaintVertexBuffers[i] !== paintVertexBuffers[i]) {\n paintBuffersDiffer = true;\n }\n }\n\n const isFreshBindRequired = (\n !this.vao ||\n this.boundProgram !== program ||\n this.boundLayoutVertexBuffer !== layoutVertexBuffer ||\n paintBuffersDiffer ||\n this.boundIndexBuffer !== indexBuffer ||\n this.boundVertexOffset !== vertexOffset ||\n this.boundDynamicVertexBuffer !== dynamicVertexBuffer ||\n this.boundDynamicVertexBuffer2 !== dynamicVertexBuffer2\n );\n\n if (!context.extVertexArrayObject || isFreshBindRequired) {\n this.freshBind(program, layoutVertexBuffer, paintVertexBuffers, indexBuffer, vertexOffset, dynamicVertexBuffer, dynamicVertexBuffer2);\n } else {\n context.bindVertexArrayOES.set(this.vao);\n\n if (dynamicVertexBuffer) {\n // The buffer may have been updated. Rebind to upload data.\n dynamicVertexBuffer.bind();\n }\n\n if (indexBuffer && indexBuffer.dynamicDraw) {\n indexBuffer.bind();\n }\n\n if (dynamicVertexBuffer2) {\n dynamicVertexBuffer2.bind();\n }\n }\n }\n\n freshBind(program: Program<*>,\n layoutVertexBuffer: VertexBuffer,\n paintVertexBuffers: Array,\n indexBuffer: ?IndexBuffer,\n vertexOffset: ?number,\n dynamicVertexBuffer: ?VertexBuffer,\n dynamicVertexBuffer2: ?VertexBuffer) {\n let numPrevAttributes;\n const numNextAttributes = program.numAttributes;\n\n const context = this.context;\n const gl = context.gl;\n\n if (context.extVertexArrayObject) {\n if (this.vao) this.destroy();\n this.vao = context.extVertexArrayObject.createVertexArrayOES();\n context.bindVertexArrayOES.set(this.vao);\n numPrevAttributes = 0;\n\n // store the arguments so that we can verify them when the vao is bound again\n this.boundProgram = program;\n this.boundLayoutVertexBuffer = layoutVertexBuffer;\n this.boundPaintVertexBuffers = paintVertexBuffers;\n this.boundIndexBuffer = indexBuffer;\n this.boundVertexOffset = vertexOffset;\n this.boundDynamicVertexBuffer = dynamicVertexBuffer;\n this.boundDynamicVertexBuffer2 = dynamicVertexBuffer2;\n\n } else {\n numPrevAttributes = context.currentNumAttributes || 0;\n\n // Disable all attributes from the previous program that aren't used in\n // the new program. Note: attribute indices are *not* program specific!\n for (let i = numNextAttributes; i < numPrevAttributes; i++) {\n // WebGL breaks if you disable attribute 0.\n // http://stackoverflow.com/questions/20305231\n assert(i !== 0);\n gl.disableVertexAttribArray(i);\n }\n }\n\n layoutVertexBuffer.enableAttributes(gl, program);\n for (const vertexBuffer of paintVertexBuffers) {\n vertexBuffer.enableAttributes(gl, program);\n }\n\n if (dynamicVertexBuffer) {\n dynamicVertexBuffer.enableAttributes(gl, program);\n }\n if (dynamicVertexBuffer2) {\n dynamicVertexBuffer2.enableAttributes(gl, program);\n }\n\n layoutVertexBuffer.bind();\n layoutVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset);\n for (const vertexBuffer of paintVertexBuffers) {\n vertexBuffer.bind();\n vertexBuffer.setVertexAttribPointers(gl, program, vertexOffset);\n }\n\n if (dynamicVertexBuffer) {\n dynamicVertexBuffer.bind();\n dynamicVertexBuffer.setVertexAttribPointers(gl, program, vertexOffset);\n }\n if (indexBuffer) {\n indexBuffer.bind();\n }\n if (dynamicVertexBuffer2) {\n dynamicVertexBuffer2.bind();\n dynamicVertexBuffer2.setVertexAttribPointers(gl, program, vertexOffset);\n }\n\n context.currentNumAttributes = numNextAttributes;\n }\n\n destroy() {\n if (this.vao) {\n this.context.extVertexArrayObject.deleteVertexArrayOES(this.vao);\n this.vao = null;\n }\n }\n}\n\nexport default VertexArrayObject;\n","// @flow\n\nimport {prelude} from '../shaders';\nimport assert from 'assert';\nimport ProgramConfiguration from '../data/program_configuration';\nimport VertexArrayObject from './vertex_array_object';\nimport Context from '../gl/context';\n\nimport type SegmentVector from '../data/segment';\nimport type VertexBuffer from '../gl/vertex_buffer';\nimport type IndexBuffer from '../gl/index_buffer';\nimport type DepthMode from '../gl/depth_mode';\nimport type StencilMode from '../gl/stencil_mode';\nimport type ColorMode from '../gl/color_mode';\nimport type CullFaceMode from '../gl/cull_face_mode';\nimport type {UniformBindings, UniformValues, UniformLocations} from './uniform_binding';\nimport type {BinderUniform} from '../data/program_configuration';\n\nexport type DrawMode =\n | $PropertyType\n | $PropertyType\n | $PropertyType;\n\nfunction getTokenizedAttributesAndUniforms (array: Array): Array {\n const result = [];\n\n for (let i = 0; i < array.length; i++) {\n if (array[i] === null) continue;\n const token = array[i].split(' ');\n result.push(token.pop());\n }\n return result;\n}\nclass Program {\n program: WebGLProgram;\n attributes: {[_: string]: number};\n numAttributes: number;\n fixedUniforms: Us;\n binderUniforms: Array;\n failedToCreate: boolean;\n\n constructor(context: Context,\n name: string,\n source: {fragmentSource: string, vertexSource: string, staticAttributes: Array, staticUniforms: Array},\n configuration: ?ProgramConfiguration,\n fixedUniforms: (Context, UniformLocations) => Us,\n showOverdrawInspector: boolean) {\n const gl = context.gl;\n this.program = gl.createProgram();\n\n const staticAttrInfo = getTokenizedAttributesAndUniforms(source.staticAttributes);\n const dynamicAttrInfo = configuration ? configuration.getBinderAttributes() : [];\n const allAttrInfo = staticAttrInfo.concat(dynamicAttrInfo);\n\n const staticUniformsInfo = source.staticUniforms ? getTokenizedAttributesAndUniforms(source.staticUniforms) : [];\n const dynamicUniformsInfo = configuration ? configuration.getBinderUniforms() : [];\n // remove duplicate uniforms\n const uniformList = staticUniformsInfo.concat(dynamicUniformsInfo);\n const allUniformsInfo = [];\n for (const uniform of uniformList) {\n if (allUniformsInfo.indexOf(uniform) < 0) allUniformsInfo.push(uniform);\n }\n\n const defines = configuration ? configuration.defines() : [];\n if (showOverdrawInspector) {\n defines.push('#define OVERDRAW_INSPECTOR;');\n }\n\n const fragmentSource = defines.concat(prelude.fragmentSource, source.fragmentSource).join('\\n');\n const vertexSource = defines.concat(prelude.vertexSource, source.vertexSource).join('\\n');\n const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n if (gl.isContextLost()) {\n this.failedToCreate = true;\n return;\n }\n gl.shaderSource(fragmentShader, fragmentSource);\n gl.compileShader(fragmentShader);\n assert(gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS), (gl.getShaderInfoLog(fragmentShader): any));\n gl.attachShader(this.program, fragmentShader);\n\n const vertexShader = gl.createShader(gl.VERTEX_SHADER);\n if (gl.isContextLost()) {\n this.failedToCreate = true;\n return;\n }\n gl.shaderSource(vertexShader, vertexSource);\n gl.compileShader(vertexShader);\n assert(gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS), (gl.getShaderInfoLog(vertexShader): any));\n gl.attachShader(this.program, vertexShader);\n\n this.attributes = {};\n const uniformLocations = {};\n\n this.numAttributes = allAttrInfo.length;\n\n for (let i = 0; i < this.numAttributes; i++) {\n if (allAttrInfo[i]) {\n gl.bindAttribLocation(this.program, i, allAttrInfo[i]);\n this.attributes[allAttrInfo[i]] = i;\n }\n }\n\n gl.linkProgram(this.program);\n assert(gl.getProgramParameter(this.program, gl.LINK_STATUS), (gl.getProgramInfoLog(this.program): any));\n\n gl.deleteShader(vertexShader);\n gl.deleteShader(fragmentShader);\n\n for (let it = 0; it < allUniformsInfo.length; it++) {\n const uniform = allUniformsInfo[it];\n if (uniform && !uniformLocations[uniform]) {\n const uniformLocation = gl.getUniformLocation(this.program, uniform);\n if (uniformLocation) {\n uniformLocations[uniform] = uniformLocation;\n }\n }\n }\n\n this.fixedUniforms = fixedUniforms(context, uniformLocations);\n this.binderUniforms = configuration ? configuration.getUniforms(context, uniformLocations) : [];\n }\n\n draw(context: Context,\n drawMode: DrawMode,\n depthMode: $ReadOnly,\n stencilMode: $ReadOnly,\n colorMode: $ReadOnly,\n cullFaceMode: $ReadOnly,\n uniformValues: UniformValues,\n layerID: string,\n layoutVertexBuffer: VertexBuffer,\n indexBuffer: IndexBuffer,\n segments: SegmentVector,\n currentProperties: any,\n zoom: ?number,\n configuration: ?ProgramConfiguration,\n dynamicLayoutBuffer: ?VertexBuffer,\n dynamicLayoutBuffer2: ?VertexBuffer) {\n\n const gl = context.gl;\n\n if (this.failedToCreate) return;\n\n context.program.set(this.program);\n context.setDepthMode(depthMode);\n context.setStencilMode(stencilMode);\n context.setColorMode(colorMode);\n context.setCullFace(cullFaceMode);\n\n for (const name in this.fixedUniforms) {\n this.fixedUniforms[name].set(uniformValues[name]);\n }\n\n if (configuration) {\n configuration.setUniforms(context, this.binderUniforms, currentProperties, {zoom: (zoom: any)});\n }\n\n const primitiveSize = {\n [gl.LINES]: 2,\n [gl.TRIANGLES]: 3,\n [gl.LINE_STRIP]: 1\n }[drawMode];\n\n for (const segment of segments.get()) {\n const vaos = segment.vaos || (segment.vaos = {});\n const vao: VertexArrayObject = vaos[layerID] || (vaos[layerID] = new VertexArrayObject());\n\n vao.bind(\n context,\n this,\n layoutVertexBuffer,\n configuration ? configuration.getPaintVertexBuffers() : [],\n indexBuffer,\n segment.vertexOffset,\n dynamicLayoutBuffer,\n dynamicLayoutBuffer2\n );\n\n gl.drawElements(\n drawMode,\n segment.primitiveLength * primitiveSize,\n gl.UNSIGNED_SHORT,\n segment.primitiveOffset * primitiveSize * 2);\n }\n }\n}\n\nexport default Program;\n","// @flow\n\nimport assert from 'assert';\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform3f\n} from '../uniform_binding';\nimport pixelsToTileUnits from '../../source/pixels_to_tile_units';\n\nimport type Painter from '../painter';\nimport type {OverscaledTileID} from '../../source/tile_id';\nimport type {CrossFaded} from '../../style/properties';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters';\nimport type {UniformValues} from '../uniform_binding';\nimport type Tile from '../../source/tile';\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image';\n\ntype BackgroundPatternUniformsType = {|\n 'u_image': Uniform1i,\n 'u_pattern_tl_a': Uniform2f,\n 'u_pattern_br_a': Uniform2f,\n 'u_pattern_tl_b': Uniform2f,\n 'u_pattern_br_b': Uniform2f,\n 'u_texsize': Uniform2f,\n 'u_mix': Uniform1f,\n 'u_pattern_size_a': Uniform2f,\n 'u_pattern_size_b': Uniform2f,\n 'u_scale_a': Uniform1f,\n 'u_scale_b': Uniform1f,\n 'u_pixel_coord_upper': Uniform2f,\n 'u_pixel_coord_lower': Uniform2f,\n 'u_tile_units_to_pixels': Uniform1f\n|};\n\nexport type PatternUniformsType = {|\n // pattern uniforms:\n 'u_image': Uniform1i,\n 'u_texsize': Uniform2f,\n 'u_scale': Uniform3f,\n 'u_fade': Uniform1f,\n 'u_pixel_coord_upper': Uniform2f,\n 'u_pixel_coord_lower': Uniform2f\n|};\n\nfunction patternUniformValues(crossfade: CrossfadeParameters, painter: Painter,\n tile: Tile\n): UniformValues {\n\n const tileRatio = 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom);\n\n const numTiles = Math.pow(2, tile.tileID.overscaledZ);\n const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles;\n\n const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles);\n const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y;\n\n return {\n 'u_image': 0,\n 'u_texsize': tile.imageAtlasTexture.size,\n 'u_scale': [tileRatio, crossfade.fromScale, crossfade.toScale],\n 'u_fade': crossfade.t,\n // split the pixel coord into two pairs of 16 bit numbers. The glsl spec only guarantees 16 bits of precision.\n 'u_pixel_coord_upper': [pixelX >> 16, pixelY >> 16],\n 'u_pixel_coord_lower': [pixelX & 0xFFFF, pixelY & 0xFFFF]\n };\n}\n\nfunction bgPatternUniformValues(image: CrossFaded, crossfade: CrossfadeParameters, painter: Painter,\n tile: {tileID: OverscaledTileID, tileSize: number}\n): UniformValues {\n const imagePosA = painter.imageManager.getPattern(image.from.toString());\n const imagePosB = painter.imageManager.getPattern(image.to.toString());\n assert(imagePosA && imagePosB);\n const {width, height} = painter.imageManager.getPixelSize();\n\n const numTiles = Math.pow(2, tile.tileID.overscaledZ);\n const tileSizeAtNearestZoom = tile.tileSize * Math.pow(2, painter.transform.tileZoom) / numTiles;\n\n const pixelX = tileSizeAtNearestZoom * (tile.tileID.canonical.x + tile.tileID.wrap * numTiles);\n const pixelY = tileSizeAtNearestZoom * tile.tileID.canonical.y;\n\n return {\n 'u_image': 0,\n 'u_pattern_tl_a': (imagePosA: any).tl,\n 'u_pattern_br_a': (imagePosA: any).br,\n 'u_pattern_tl_b': (imagePosB: any).tl,\n 'u_pattern_br_b': (imagePosB: any).br,\n 'u_texsize': [width, height],\n 'u_mix': crossfade.t,\n 'u_pattern_size_a': (imagePosA: any).displaySize,\n 'u_pattern_size_b': (imagePosB: any).displaySize,\n 'u_scale_a': crossfade.fromScale,\n 'u_scale_b': crossfade.toScale,\n 'u_tile_units_to_pixels': 1 / pixelsToTileUnits(tile, 1, painter.transform.tileZoom),\n // split the pixel coord into two pairs of 16 bit numbers. The glsl spec only guarantees 16 bits of precision.\n 'u_pixel_coord_upper': [pixelX >> 16, pixelY >> 16],\n 'u_pixel_coord_lower': [pixelX & 0xFFFF, pixelY & 0xFFFF]\n };\n}\nexport {bgPatternUniformValues, patternUniformValues};\n","// @flow\n\nimport {patternUniformValues} from './pattern';\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform3f,\n UniformMatrix4f\n} from '../uniform_binding';\n\nimport {mat3, vec3} from 'gl-matrix';\nimport {extend} from '../../util/util';\n\nimport type Context from '../../gl/context';\nimport type Painter from '../painter';\nimport type {OverscaledTileID} from '../../source/tile_id';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters';\nimport type Tile from '../../source/tile';\n\nexport type FillExtrusionUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_lightpos': Uniform3f,\n 'u_lightintensity': Uniform1f,\n 'u_lightcolor': Uniform3f,\n 'u_vertical_gradient': Uniform1f,\n 'u_opacity': Uniform1f\n|};\n\nexport type FillExtrusionPatternUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_lightpos': Uniform3f,\n 'u_lightintensity': Uniform1f,\n 'u_lightcolor': Uniform3f,\n 'u_height_factor': Uniform1f,\n 'u_vertical_gradient': Uniform1f,\n // pattern uniforms:\n 'u_texsize': Uniform2f,\n 'u_image': Uniform1i,\n 'u_pixel_coord_upper': Uniform2f,\n 'u_pixel_coord_lower': Uniform2f,\n 'u_scale': Uniform3f,\n 'u_fade': Uniform1f,\n 'u_opacity': Uniform1f\n|};\n\nconst fillExtrusionUniforms = (context: Context, locations: UniformLocations): FillExtrusionUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_lightpos': new Uniform3f(context, locations.u_lightpos),\n 'u_lightintensity': new Uniform1f(context, locations.u_lightintensity),\n 'u_lightcolor': new Uniform3f(context, locations.u_lightcolor),\n 'u_vertical_gradient': new Uniform1f(context, locations.u_vertical_gradient),\n 'u_opacity': new Uniform1f(context, locations.u_opacity)\n});\n\nconst fillExtrusionPatternUniforms = (context: Context, locations: UniformLocations): FillExtrusionPatternUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_lightpos': new Uniform3f(context, locations.u_lightpos),\n 'u_lightintensity': new Uniform1f(context, locations.u_lightintensity),\n 'u_lightcolor': new Uniform3f(context, locations.u_lightcolor),\n 'u_vertical_gradient': new Uniform1f(context, locations.u_vertical_gradient),\n 'u_height_factor': new Uniform1f(context, locations.u_height_factor),\n // pattern uniforms\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper),\n 'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower),\n 'u_scale': new Uniform3f(context, locations.u_scale),\n 'u_fade': new Uniform1f(context, locations.u_fade),\n 'u_opacity': new Uniform1f(context, locations.u_opacity)\n});\n\nconst fillExtrusionUniformValues = (\n matrix: Float32Array,\n painter: Painter,\n shouldUseVerticalGradient: boolean,\n opacity: number\n): UniformValues => {\n const light = painter.style.light;\n const _lp = light.properties.get('position');\n const lightPos = [_lp.x, _lp.y, _lp.z];\n const lightMat = mat3.create();\n if (light.properties.get('anchor') === 'viewport') {\n mat3.fromRotation(lightMat, -painter.transform.angle);\n }\n vec3.transformMat3(lightPos, lightPos, lightMat);\n\n const lightColor = light.properties.get('color');\n\n return {\n 'u_matrix': matrix,\n 'u_lightpos': lightPos,\n 'u_lightintensity': light.properties.get('intensity'),\n 'u_lightcolor': [lightColor.r, lightColor.g, lightColor.b],\n 'u_vertical_gradient': +shouldUseVerticalGradient,\n 'u_opacity': opacity\n };\n};\n\nconst fillExtrusionPatternUniformValues = (\n matrix: Float32Array,\n painter: Painter,\n shouldUseVerticalGradient: boolean,\n opacity: number,\n coord: OverscaledTileID,\n crossfade: CrossfadeParameters,\n tile: Tile\n): UniformValues => {\n return extend(fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity),\n patternUniformValues(crossfade, painter, tile),\n {\n 'u_height_factor': -Math.pow(2, coord.overscaledZ) / tile.tileSize / 8\n });\n};\n\nexport {\n fillExtrusionUniforms,\n fillExtrusionPatternUniforms,\n fillExtrusionUniformValues,\n fillExtrusionPatternUniformValues\n};\n","import * as glMatrix from \"./common.js\";\n/**\r\n * 3x3 Matrix\r\n * @module mat3\r\n */\n\n/**\r\n * Creates a new identity mat3\r\n *\r\n * @returns {mat3} a new 3x3 matrix\r\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(9);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n }\n\n out[0] = 1;\n out[4] = 1;\n out[8] = 1;\n return out;\n}\n/**\r\n * Copies the upper-left 3x3 values into the given mat3.\r\n *\r\n * @param {mat3} out the receiving 3x3 matrix\r\n * @param {mat4} a the source 4x4 matrix\r\n * @returns {mat3} out\r\n */\n\nexport function fromMat4(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[4];\n out[4] = a[5];\n out[5] = a[6];\n out[6] = a[8];\n out[7] = a[9];\n out[8] = a[10];\n return out;\n}\n/**\r\n * Creates a new mat3 initialized with values from an existing matrix\r\n *\r\n * @param {mat3} a matrix to clone\r\n * @returns {mat3} a new 3x3 matrix\r\n */\n\nexport function clone(a) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = a[0];\n out[1] = a[1];\n out[2] = a[2];\n out[3] = a[3];\n out[4] = a[4];\n out[5] = a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\r\n * Copy the values from one mat3 to another\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the source matrix\r\n * @returns {mat3} 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 return out;\n}\n/**\r\n * Create a new mat3 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} m10 Component in column 1, row 0 position (index 3)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\r\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\r\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\r\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\r\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\r\n * @returns {mat3} A new mat3\r\n */\n\nexport function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n var out = new glMatrix.ARRAY_TYPE(9);\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\r\n * Set the components of a mat3 to the given values\r\n *\r\n * @param {mat3} 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} m10 Component in column 1, row 0 position (index 3)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 4)\r\n * @param {Number} m12 Component in column 1, row 2 position (index 5)\r\n * @param {Number} m20 Component in column 2, row 0 position (index 6)\r\n * @param {Number} m21 Component in column 2, row 1 position (index 7)\r\n * @param {Number} m22 Component in column 2, row 2 position (index 8)\r\n * @returns {mat3} out\r\n */\n\nexport function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m02;\n out[3] = m10;\n out[4] = m11;\n out[5] = m12;\n out[6] = m20;\n out[7] = m21;\n out[8] = m22;\n return out;\n}\n/**\r\n * Set a mat3 to the identity matrix\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @returns {mat3} 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] = 1;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\r\n * Transpose the values of a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the source matrix\r\n * @returns {mat3} 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 a12 = a[5];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a01;\n out[5] = a[7];\n out[6] = a02;\n out[7] = a12;\n } else {\n out[0] = a[0];\n out[1] = a[3];\n out[2] = a[6];\n out[3] = a[1];\n out[4] = a[4];\n out[5] = a[7];\n out[6] = a[2];\n out[7] = a[5];\n out[8] = a[8];\n }\n\n return out;\n}\n/**\r\n * Inverts a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the source matrix\r\n * @returns {mat3} out\r\n */\n\nexport function invert(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b01 = a22 * a11 - a12 * a21;\n var b11 = -a22 * a10 + a12 * a20;\n var b21 = a21 * a10 - a11 * a20; // Calculate the determinant\n\n var det = a00 * b01 + a01 * b11 + a02 * b21;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = b01 * det;\n out[1] = (-a22 * a01 + a02 * a21) * det;\n out[2] = (a12 * a01 - a02 * a11) * det;\n out[3] = b11 * det;\n out[4] = (a22 * a00 - a02 * a20) * det;\n out[5] = (-a12 * a00 + a02 * a10) * det;\n out[6] = b21 * det;\n out[7] = (-a21 * a00 + a01 * a20) * det;\n out[8] = (a11 * a00 - a01 * a10) * det;\n return out;\n}\n/**\r\n * Calculates the adjugate of a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the source matrix\r\n * @returns {mat3} out\r\n */\n\nexport function adjoint(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n out[0] = a11 * a22 - a12 * a21;\n out[1] = a02 * a21 - a01 * a22;\n out[2] = a01 * a12 - a02 * a11;\n out[3] = a12 * a20 - a10 * a22;\n out[4] = a00 * a22 - a02 * a20;\n out[5] = a02 * a10 - a00 * a12;\n out[6] = a10 * a21 - a11 * a20;\n out[7] = a01 * a20 - a00 * a21;\n out[8] = a00 * a11 - a01 * a10;\n return out;\n}\n/**\r\n * Calculates the determinant of a mat3\r\n *\r\n * @param {mat3} 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 var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20);\n}\n/**\r\n * Multiplies two mat3's\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the first operand\r\n * @param {mat3} b the second operand\r\n * @returns {mat3} out\r\n */\n\nexport function multiply(out, a, b) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2];\n var a10 = a[3],\n a11 = a[4],\n a12 = a[5];\n var a20 = a[6],\n a21 = a[7],\n a22 = a[8];\n var b00 = b[0],\n b01 = b[1],\n b02 = b[2];\n var b10 = b[3],\n b11 = b[4],\n b12 = b[5];\n var b20 = b[6],\n b21 = b[7],\n b22 = b[8];\n out[0] = b00 * a00 + b01 * a10 + b02 * a20;\n out[1] = b00 * a01 + b01 * a11 + b02 * a21;\n out[2] = b00 * a02 + b01 * a12 + b02 * a22;\n out[3] = b10 * a00 + b11 * a10 + b12 * a20;\n out[4] = b10 * a01 + b11 * a11 + b12 * a21;\n out[5] = b10 * a02 + b11 * a12 + b12 * a22;\n out[6] = b20 * a00 + b21 * a10 + b22 * a20;\n out[7] = b20 * a01 + b21 * a11 + b22 * a21;\n out[8] = b20 * a02 + b21 * a12 + b22 * a22;\n return out;\n}\n/**\r\n * Translate a mat3 by the given vector\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the matrix to translate\r\n * @param {vec2} v vector to translate by\r\n * @returns {mat3} out\r\n */\n\nexport function translate(out, a, v) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n x = v[0],\n y = v[1];\n out[0] = a00;\n out[1] = a01;\n out[2] = a02;\n out[3] = a10;\n out[4] = a11;\n out[5] = a12;\n out[6] = x * a00 + y * a10 + a20;\n out[7] = x * a01 + y * a11 + a21;\n out[8] = x * a02 + y * a12 + a22;\n return out;\n}\n/**\r\n * Rotates a mat3 by the given angle\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat3} out\r\n */\n\nexport function rotate(out, a, rad) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a10 = a[3],\n a11 = a[4],\n a12 = a[5],\n a20 = a[6],\n a21 = a[7],\n a22 = a[8],\n s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c * a00 + s * a10;\n out[1] = c * a01 + s * a11;\n out[2] = c * a02 + s * a12;\n out[3] = c * a10 - s * a00;\n out[4] = c * a11 - s * a01;\n out[5] = c * a12 - s * a02;\n out[6] = a20;\n out[7] = a21;\n out[8] = a22;\n return out;\n}\n/**\r\n * Scales the mat3 by the dimensions in the given vec2\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the matrix to rotate\r\n * @param {vec2} v the vec2 to scale the matrix by\r\n * @returns {mat3} out\r\n **/\n\nexport function scale(out, a, v) {\n var x = v[0],\n y = v[1];\n out[0] = x * a[0];\n out[1] = x * a[1];\n out[2] = x * a[2];\n out[3] = y * a[3];\n out[4] = y * a[4];\n out[5] = y * a[5];\n out[6] = a[6];\n out[7] = a[7];\n out[8] = a[8];\n return out;\n}\n/**\r\n * Creates a matrix from a vector translation\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat3.identity(dest);\r\n * mat3.translate(dest, dest, vec);\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {vec2} v Translation vector\r\n * @returns {mat3} 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] = 1;\n out[5] = 0;\n out[6] = v[0];\n out[7] = v[1];\n out[8] = 1;\n return out;\n}\n/**\r\n * Creates a matrix from a given angle\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat3.identity(dest);\r\n * mat3.rotate(dest, dest, rad);\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat3} out\r\n */\n\nexport function fromRotation(out, rad) {\n var s = Math.sin(rad),\n c = Math.cos(rad);\n out[0] = c;\n out[1] = s;\n out[2] = 0;\n out[3] = -s;\n out[4] = c;\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\r\n * Creates a matrix from a vector scaling\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat3.identity(dest);\r\n * mat3.scale(dest, dest, vec);\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {vec2} v Scaling vector\r\n * @returns {mat3} 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] = v[1];\n out[5] = 0;\n out[6] = 0;\n out[7] = 0;\n out[8] = 1;\n return out;\n}\n/**\r\n * Copies the values from a mat2d into a mat3\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat2d} a the matrix to copy\r\n * @returns {mat3} out\r\n **/\n\nexport function fromMat2d(out, a) {\n out[0] = a[0];\n out[1] = a[1];\n out[2] = 0;\n out[3] = a[2];\n out[4] = a[3];\n out[5] = 0;\n out[6] = a[4];\n out[7] = a[5];\n out[8] = 1;\n return out;\n}\n/**\r\n * Calculates a 3x3 matrix from the given quaternion\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {quat} q Quaternion to create matrix from\r\n *\r\n * @returns {mat3} 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[3] = yx - wz;\n out[6] = zx + wy;\n out[1] = yx + wz;\n out[4] = 1 - xx - zz;\n out[7] = zy - wx;\n out[2] = zx - wy;\n out[5] = zy + wx;\n out[8] = 1 - xx - yy;\n return out;\n}\n/**\r\n * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix\r\n *\r\n * @param {mat3} out mat3 receiving operation result\r\n * @param {mat4} a Mat4 to derive the normal matrix from\r\n *\r\n * @returns {mat3} out\r\n */\n\nexport function normalFromMat4(out, a) {\n var a00 = a[0],\n a01 = a[1],\n a02 = a[2],\n a03 = a[3];\n var a10 = a[4],\n a11 = a[5],\n a12 = a[6],\n a13 = a[7];\n var a20 = a[8],\n a21 = a[9],\n a22 = a[10],\n a23 = a[11];\n var a30 = a[12],\n a31 = a[13],\n a32 = a[14],\n a33 = a[15];\n var b00 = a00 * a11 - a01 * a10;\n var b01 = a00 * a12 - a02 * a10;\n var b02 = a00 * a13 - a03 * a10;\n var b03 = a01 * a12 - a02 * a11;\n var b04 = a01 * a13 - a03 * a11;\n var b05 = a02 * a13 - a03 * a12;\n var b06 = a20 * a31 - a21 * a30;\n var b07 = a20 * a32 - a22 * a30;\n var b08 = a20 * a33 - a23 * a30;\n var b09 = a21 * a32 - a22 * a31;\n var b10 = a21 * a33 - a23 * a31;\n var b11 = a22 * a33 - a23 * a32; // Calculate the determinant\n\n var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;\n out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det;\n out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det;\n out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det;\n out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det;\n out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det;\n out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det;\n out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det;\n out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det;\n return out;\n}\n/**\r\n * Generates a 2D projection matrix with the given bounds\r\n *\r\n * @param {mat3} out mat3 frustum matrix will be written into\r\n * @param {number} width Width of your gl context\r\n * @param {number} height Height of gl context\r\n * @returns {mat3} out\r\n */\n\nexport function projection(out, width, height) {\n out[0] = 2 / width;\n out[1] = 0;\n out[2] = 0;\n out[3] = 0;\n out[4] = -2 / height;\n out[5] = 0;\n out[6] = -1;\n out[7] = 1;\n out[8] = 1;\n return out;\n}\n/**\r\n * Returns a string representation of a mat3\r\n *\r\n * @param {mat3} 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 \"mat3(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \", \" + a[4] + \", \" + a[5] + \", \" + a[6] + \", \" + a[7] + \", \" + a[8] + \")\";\n}\n/**\r\n * Returns Frobenius norm of a mat3\r\n *\r\n * @param {mat3} 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]);\n}\n/**\r\n * Adds two mat3's\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the first operand\r\n * @param {mat3} b the second operand\r\n * @returns {mat3} 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 return out;\n}\n/**\r\n * Subtracts matrix b from matrix a\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the first operand\r\n * @param {mat3} b the second operand\r\n * @returns {mat3} 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 return out;\n}\n/**\r\n * Multiply each element of the matrix by a scalar.\r\n *\r\n * @param {mat3} out the receiving matrix\r\n * @param {mat3} a the matrix to scale\r\n * @param {Number} b amount to scale the matrix's elements by\r\n * @returns {mat3} 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 return out;\n}\n/**\r\n * Adds two mat3's after multiplying each element of the second operand by a scalar value.\r\n *\r\n * @param {mat3} out the receiving vector\r\n * @param {mat3} a the first operand\r\n * @param {mat3} b the second operand\r\n * @param {Number} scale the amount to scale b's elements by before adding\r\n * @returns {mat3} 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 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 {mat3} a The first matrix.\r\n * @param {mat3} 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];\n}\n/**\r\n * Returns whether or not the matrices have approximately the same elements in the same position.\r\n *\r\n * @param {mat3} a The first matrix.\r\n * @param {mat3} 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 a4 = a[4],\n a5 = a[5],\n a6 = a[6],\n a7 = a[7],\n a8 = a[8];\n var b0 = b[0],\n b1 = b[1],\n b2 = b[2],\n b3 = b[3],\n b4 = b[4],\n b5 = b[5],\n b6 = b[6],\n b7 = b[7],\n b8 = b[8];\n return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8));\n}\n/**\r\n * Alias for {@link mat3.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link mat3.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;","// @flow\n\nimport {patternUniformValues} from './pattern';\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform3f,\n UniformMatrix4f\n} from '../uniform_binding';\nimport {extend} from '../../util/util';\n\nimport type Painter from '../painter';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type Context from '../../gl/context';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters';\nimport type Tile from '../../source/tile';\n\nexport type FillUniformsType = {|\n 'u_matrix': UniformMatrix4f\n|};\n\nexport type FillOutlineUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_world': Uniform2f\n|};\n\nexport type FillPatternUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n // pattern uniforms:\n 'u_texsize': Uniform2f,\n 'u_image': Uniform1i,\n 'u_pixel_coord_upper': Uniform2f,\n 'u_pixel_coord_lower': Uniform2f,\n 'u_scale': Uniform3f,\n 'u_fade': Uniform1f\n|};\n\nexport type FillOutlinePatternUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_world': Uniform2f,\n // pattern uniforms:\n 'u_texsize': Uniform2f,\n 'u_image': Uniform1i,\n 'u_pixel_coord_upper': Uniform2f,\n 'u_pixel_coord_lower': Uniform2f,\n 'u_scale': Uniform3f,\n 'u_fade': Uniform1f\n|};\n\nconst fillUniforms = (context: Context, locations: UniformLocations): FillUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix)\n});\n\nconst fillPatternUniforms = (context: Context, locations: UniformLocations): FillPatternUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper),\n 'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower),\n 'u_scale': new Uniform3f(context, locations.u_scale),\n 'u_fade': new Uniform1f(context, locations.u_fade)\n\n});\n\nconst fillOutlineUniforms = (context: Context, locations: UniformLocations): FillOutlineUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_world': new Uniform2f(context, locations.u_world)\n});\n\nconst fillOutlinePatternUniforms = (context: Context, locations: UniformLocations): FillOutlinePatternUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_world': new Uniform2f(context, locations.u_world),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper),\n 'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower),\n 'u_scale': new Uniform3f(context, locations.u_scale),\n 'u_fade': new Uniform1f(context, locations.u_fade)\n});\n\nconst fillUniformValues = (matrix: Float32Array): UniformValues => ({\n 'u_matrix': matrix\n});\n\nconst fillPatternUniformValues = (\n matrix: Float32Array,\n painter: Painter,\n crossfade: CrossfadeParameters,\n tile: Tile\n): UniformValues => extend(\n fillUniformValues(matrix),\n patternUniformValues(crossfade, painter, tile)\n);\n\nconst fillOutlineUniformValues = (\n matrix: Float32Array,\n drawingBufferSize: [number, number]\n): UniformValues => ({\n 'u_matrix': matrix,\n 'u_world': drawingBufferSize\n});\n\nconst fillOutlinePatternUniformValues = (\n matrix: Float32Array,\n painter: Painter,\n crossfade: CrossfadeParameters,\n tile: Tile,\n drawingBufferSize: [number, number]\n): UniformValues => extend(\n fillPatternUniformValues(matrix, painter, crossfade, tile),\n {\n 'u_world': drawingBufferSize\n }\n);\n\nexport {\n fillUniforms,\n fillPatternUniforms,\n fillOutlineUniforms,\n fillOutlinePatternUniforms,\n fillUniformValues,\n fillPatternUniformValues,\n fillOutlineUniformValues,\n fillOutlinePatternUniformValues\n};\n","// @flow\n\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n UniformMatrix4f\n} from '../uniform_binding';\nimport pixelsToTileUnits from '../../source/pixels_to_tile_units';\n\nimport type Context from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type {OverscaledTileID} from '../../source/tile_id';\nimport type Tile from '../../source/tile';\nimport type CircleStyleLayer from '../../style/style_layer/circle_style_layer';\nimport type Painter from '../painter';\nimport browser from '../../util/browser';\n\nexport type CircleUniformsType = {|\n 'u_camera_to_center_distance': Uniform1f,\n 'u_scale_with_map': Uniform1i,\n 'u_pitch_with_map': Uniform1i,\n 'u_extrude_scale': Uniform2f,\n 'u_device_pixel_ratio': Uniform1f,\n 'u_matrix': UniformMatrix4f\n|};\n\nconst circleUniforms = (context: Context, locations: UniformLocations): CircleUniformsType => ({\n 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance),\n 'u_scale_with_map': new Uniform1i(context, locations.u_scale_with_map),\n 'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map),\n 'u_extrude_scale': new Uniform2f(context, locations.u_extrude_scale),\n 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio),\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix)\n});\n\nconst circleUniformValues = (\n painter: Painter,\n coord: OverscaledTileID,\n tile: Tile,\n layer: CircleStyleLayer\n): UniformValues => {\n const transform = painter.transform;\n\n let pitchWithMap: boolean, extrudeScale: [number, number];\n if (layer.paint.get('circle-pitch-alignment') === 'map') {\n const pixelRatio = pixelsToTileUnits(tile, 1, transform.zoom);\n pitchWithMap = true;\n extrudeScale = [pixelRatio, pixelRatio];\n } else {\n pitchWithMap = false;\n extrudeScale = transform.pixelsToGLUnits;\n }\n\n return {\n 'u_camera_to_center_distance': transform.cameraToCenterDistance,\n 'u_scale_with_map': +(layer.paint.get('circle-pitch-scale') === 'map'),\n 'u_matrix': painter.translatePosMatrix(\n coord.posMatrix,\n tile,\n layer.paint.get('circle-translate'),\n layer.paint.get('circle-translate-anchor')),\n 'u_pitch_with_map': +(pitchWithMap),\n 'u_device_pixel_ratio': browser.devicePixelRatio,\n 'u_extrude_scale': extrudeScale\n };\n};\n\nexport {circleUniforms, circleUniformValues};\n","// @flow\n\nimport {\n Uniform1f,\n Uniform2f,\n UniformMatrix4f\n} from '../uniform_binding';\nimport pixelsToTileUnits from '../../source/pixels_to_tile_units';\n\nimport type Context from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type Transform from '../../geo/transform';\nimport type Tile from '../../source/tile';\n\nexport type CollisionUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_camera_to_center_distance': Uniform1f,\n 'u_pixels_to_tile_units': Uniform1f,\n 'u_extrude_scale': Uniform2f,\n 'u_overscale_factor': Uniform1f\n|};\n\nexport type CollisionCircleUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_inv_matrix': UniformMatrix4f,\n 'u_camera_to_center_distance': Uniform1f,\n 'u_viewport_size': Uniform2f\n|};\n\nconst collisionUniforms = (context: Context, locations: UniformLocations): CollisionUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance),\n 'u_pixels_to_tile_units': new Uniform1f(context, locations.u_pixels_to_tile_units),\n 'u_extrude_scale': new Uniform2f(context, locations.u_extrude_scale),\n 'u_overscale_factor': new Uniform1f(context, locations.u_overscale_factor)\n});\n\nconst collisionCircleUniforms = (context: Context, locations: UniformLocations): CollisionCircleUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_inv_matrix': new UniformMatrix4f(context, locations.u_inv_matrix),\n 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance),\n 'u_viewport_size': new Uniform2f(context, locations.u_viewport_size)\n});\n\nconst collisionUniformValues = (\n matrix: Float32Array,\n transform: Transform,\n tile: Tile\n): UniformValues => {\n const pixelRatio = pixelsToTileUnits(tile, 1, transform.zoom);\n const scale = Math.pow(2, transform.zoom - tile.tileID.overscaledZ);\n const overscaleFactor = tile.tileID.overscaleFactor();\n return {\n 'u_matrix': matrix,\n 'u_camera_to_center_distance': transform.cameraToCenterDistance,\n 'u_pixels_to_tile_units': pixelRatio,\n 'u_extrude_scale': [transform.pixelsToGLUnits[0] / (pixelRatio * scale),\n transform.pixelsToGLUnits[1] / (pixelRatio * scale)],\n 'u_overscale_factor': overscaleFactor\n };\n};\n\nconst collisionCircleUniformValues = (\n matrix: Float32Array,\n invMatrix: Float32Array,\n transform: Transform\n): UniformValues => {\n return {\n 'u_matrix': matrix,\n 'u_inv_matrix': invMatrix,\n 'u_camera_to_center_distance': transform.cameraToCenterDistance,\n 'u_viewport_size': [transform.width, transform.height]\n };\n};\n\nexport {collisionUniforms, collisionUniformValues, collisionCircleUniforms, collisionCircleUniformValues};\n","// @flow\n\nimport {\n UniformColor,\n UniformMatrix4f,\n Uniform1i,\n Uniform1f\n} from '../uniform_binding';\n\nimport type Context from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type Color from '../../style-spec/util/color';\n\nexport type DebugUniformsType = {|\n 'u_color': UniformColor,\n 'u_matrix': UniformMatrix4f,\n 'u_overlay': Uniform1i,\n 'u_overlay_scale': Uniform1f\n|};\n\nconst debugUniforms = (context: Context, locations: UniformLocations): DebugUniformsType => ({\n 'u_color': new UniformColor(context, locations.u_color),\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_overlay': new Uniform1i(context, locations.u_overlay),\n 'u_overlay_scale': new Uniform1f(context, locations.u_overlay_scale),\n});\n\nconst debugUniformValues = (matrix: Float32Array, color: Color, scaleRatio: number = 1): UniformValues => ({\n 'u_matrix': matrix,\n 'u_color': color,\n 'u_overlay': 0,\n 'u_overlay_scale': scaleRatio\n});\n\nexport {debugUniforms, debugUniformValues};\n","// @flow\n\nimport {UniformMatrix4f} from '../uniform_binding';\n\nimport type Context from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\n\nexport type ClippingMaskUniformsType = {|\n 'u_matrix': UniformMatrix4f\n|};\n\nconst clippingMaskUniforms = (context: Context, locations: UniformLocations): ClippingMaskUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix)\n});\n\nconst clippingMaskUniformValues = (matrix: Float32Array): UniformValues => ({\n 'u_matrix': matrix\n});\n\nexport {clippingMaskUniforms, clippingMaskUniformValues};\n","// @flow\n\nimport {mat4} from 'gl-matrix';\n\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n UniformMatrix4f\n} from '../uniform_binding';\nimport pixelsToTileUnits from '../../source/pixels_to_tile_units';\n\nimport type Context from '../../gl/context';\nimport type Tile from '../../source/tile';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type Painter from '../painter';\nimport type HeatmapStyleLayer from '../../style/style_layer/heatmap_style_layer';\n\nexport type HeatmapUniformsType = {|\n 'u_extrude_scale': Uniform1f,\n 'u_intensity': Uniform1f,\n 'u_matrix': UniformMatrix4f\n|};\n\nexport type HeatmapTextureUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_world': Uniform2f,\n 'u_image': Uniform1i,\n 'u_color_ramp': Uniform1i,\n 'u_opacity': Uniform1f\n|};\n\nconst heatmapUniforms = (context: Context, locations: UniformLocations): HeatmapUniformsType => ({\n 'u_extrude_scale': new Uniform1f(context, locations.u_extrude_scale),\n 'u_intensity': new Uniform1f(context, locations.u_intensity),\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix)\n});\n\nconst heatmapTextureUniforms = (context: Context, locations: UniformLocations): HeatmapTextureUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_world': new Uniform2f(context, locations.u_world),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_color_ramp': new Uniform1i(context, locations.u_color_ramp),\n 'u_opacity': new Uniform1f(context, locations.u_opacity)\n});\n\nconst heatmapUniformValues = (\n matrix: Float32Array,\n tile: Tile,\n zoom: number,\n intensity: number\n): UniformValues => ({\n 'u_matrix': matrix,\n 'u_extrude_scale': pixelsToTileUnits(tile, 1, zoom),\n 'u_intensity': intensity\n});\n\nconst heatmapTextureUniformValues = (\n painter: Painter,\n layer: HeatmapStyleLayer,\n textureUnit: number,\n colorRampUnit: number\n): UniformValues => {\n const matrix = mat4.create();\n mat4.ortho(matrix, 0, painter.width, painter.height, 0, 0, 1);\n\n const gl = painter.context.gl;\n\n return {\n 'u_matrix': matrix,\n 'u_world': [gl.drawingBufferWidth, gl.drawingBufferHeight],\n 'u_image': textureUnit,\n 'u_color_ramp': colorRampUnit,\n 'u_opacity': layer.paint.get('heatmap-opacity')\n };\n};\n\nexport {\n heatmapUniforms,\n heatmapTextureUniforms,\n heatmapUniformValues,\n heatmapTextureUniformValues\n};\n","// @flow\n\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform3f,\n UniformMatrix4f\n} from '../uniform_binding';\nimport pixelsToTileUnits from '../../source/pixels_to_tile_units';\nimport {extend} from '../../util/util';\nimport browser from '../../util/browser';\n\nimport type Context from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type Transform from '../../geo/transform';\nimport type Tile from '../../source/tile';\nimport type {CrossFaded} from '../../style/properties';\nimport type LineStyleLayer from '../../style/style_layer/line_style_layer';\nimport type Painter from '../painter';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters';\n\nexport type LineUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_ratio': Uniform1f,\n 'u_device_pixel_ratio': Uniform1f,\n 'u_units_to_pixels': Uniform2f\n|};\n\nexport type LineGradientUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_ratio': Uniform1f,\n 'u_device_pixel_ratio': Uniform1f,\n 'u_units_to_pixels': Uniform2f,\n 'u_image': Uniform1i,\n 'u_image_height': Uniform1f,\n|};\n\nexport type LinePatternUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_texsize': Uniform2f,\n 'u_ratio': Uniform1f,\n 'u_device_pixel_ratio': Uniform1f,\n 'u_units_to_pixels': Uniform2f,\n 'u_image': Uniform1i,\n 'u_scale': Uniform3f,\n 'u_fade': Uniform1f\n|};\n\nexport type LineSDFUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_ratio': Uniform1f,\n 'u_device_pixel_ratio': Uniform1f,\n 'u_units_to_pixels': Uniform2f,\n 'u_patternscale_a': Uniform2f,\n 'u_patternscale_b': Uniform2f,\n 'u_sdfgamma': Uniform1f,\n 'u_image': Uniform1i,\n 'u_tex_y_a': Uniform1f,\n 'u_tex_y_b': Uniform1f,\n 'u_mix': Uniform1f\n|};\n\nconst lineUniforms = (context: Context, locations: UniformLocations): LineUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_ratio': new Uniform1f(context, locations.u_ratio),\n 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio),\n 'u_units_to_pixels': new Uniform2f(context, locations.u_units_to_pixels)\n});\n\nconst lineGradientUniforms = (context: Context, locations: UniformLocations): LineGradientUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_ratio': new Uniform1f(context, locations.u_ratio),\n 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio),\n 'u_units_to_pixels': new Uniform2f(context, locations.u_units_to_pixels),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_image_height': new Uniform1f(context, locations.u_image_height),\n});\n\nconst linePatternUniforms = (context: Context, locations: UniformLocations): LinePatternUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_ratio': new Uniform1f(context, locations.u_ratio),\n 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_units_to_pixels': new Uniform2f(context, locations.u_units_to_pixels),\n 'u_scale': new Uniform3f(context, locations.u_scale),\n 'u_fade': new Uniform1f(context, locations.u_fade)\n});\n\nconst lineSDFUniforms = (context: Context, locations: UniformLocations): LineSDFUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_ratio': new Uniform1f(context, locations.u_ratio),\n 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio),\n 'u_units_to_pixels': new Uniform2f(context, locations.u_units_to_pixels),\n 'u_patternscale_a': new Uniform2f(context, locations.u_patternscale_a),\n 'u_patternscale_b': new Uniform2f(context, locations.u_patternscale_b),\n 'u_sdfgamma': new Uniform1f(context, locations.u_sdfgamma),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_tex_y_a': new Uniform1f(context, locations.u_tex_y_a),\n 'u_tex_y_b': new Uniform1f(context, locations.u_tex_y_b),\n 'u_mix': new Uniform1f(context, locations.u_mix)\n});\n\nconst lineUniformValues = (\n painter: Painter,\n tile: Tile,\n layer: LineStyleLayer\n): UniformValues => {\n const transform = painter.transform;\n\n return {\n 'u_matrix': calculateMatrix(painter, tile, layer),\n 'u_ratio': 1 / pixelsToTileUnits(tile, 1, transform.zoom),\n 'u_device_pixel_ratio': browser.devicePixelRatio,\n 'u_units_to_pixels': [\n 1 / transform.pixelsToGLUnits[0],\n 1 / transform.pixelsToGLUnits[1]\n ]\n };\n};\n\nconst lineGradientUniformValues = (\n painter: Painter,\n tile: Tile,\n layer: LineStyleLayer,\n imageHeight: number\n): UniformValues => {\n return extend(lineUniformValues(painter, tile, layer), {\n 'u_image': 0,\n 'u_image_height': imageHeight,\n });\n};\n\nconst linePatternUniformValues = (\n painter: Painter,\n tile: Tile,\n layer: LineStyleLayer,\n crossfade: CrossfadeParameters\n): UniformValues => {\n const transform = painter.transform;\n const tileZoomRatio = calculateTileRatio(tile, transform);\n return {\n 'u_matrix': calculateMatrix(painter, tile, layer),\n 'u_texsize': tile.imageAtlasTexture.size,\n // camera zoom ratio\n 'u_ratio': 1 / pixelsToTileUnits(tile, 1, transform.zoom),\n 'u_device_pixel_ratio': browser.devicePixelRatio,\n 'u_image': 0,\n 'u_scale': [tileZoomRatio, crossfade.fromScale, crossfade.toScale],\n 'u_fade': crossfade.t,\n 'u_units_to_pixels': [\n 1 / transform.pixelsToGLUnits[0],\n 1 / transform.pixelsToGLUnits[1]\n ]\n };\n};\n\nconst lineSDFUniformValues = (\n painter: Painter,\n tile: Tile,\n layer: LineStyleLayer,\n dasharray: CrossFaded>,\n crossfade: CrossfadeParameters\n): UniformValues => {\n const transform = painter.transform;\n const lineAtlas = painter.lineAtlas;\n const tileRatio = calculateTileRatio(tile, transform);\n\n const round = layer.layout.get('line-cap') === 'round';\n\n const posA = lineAtlas.getDash(dasharray.from, round);\n const posB = lineAtlas.getDash(dasharray.to, round);\n\n const widthA = posA.width * crossfade.fromScale;\n const widthB = posB.width * crossfade.toScale;\n\n return extend(lineUniformValues(painter, tile, layer), {\n 'u_patternscale_a': [tileRatio / widthA, -posA.height / 2],\n 'u_patternscale_b': [tileRatio / widthB, -posB.height / 2],\n 'u_sdfgamma': lineAtlas.width / (Math.min(widthA, widthB) * 256 * browser.devicePixelRatio) / 2,\n 'u_image': 0,\n 'u_tex_y_a': posA.y,\n 'u_tex_y_b': posB.y,\n 'u_mix': crossfade.t\n });\n};\n\nfunction calculateTileRatio(tile: Tile, transform: Transform) {\n return 1 / pixelsToTileUnits(tile, 1, transform.tileZoom);\n}\n\nfunction calculateMatrix(painter, tile, layer) {\n return painter.translatePosMatrix(\n tile.tileID.posMatrix,\n tile,\n layer.paint.get('line-translate'),\n layer.paint.get('line-translate-anchor')\n );\n}\n\nexport {\n lineUniforms,\n lineGradientUniforms,\n linePatternUniforms,\n lineSDFUniforms,\n lineUniformValues,\n lineGradientUniformValues,\n linePatternUniformValues,\n lineSDFUniformValues\n};\n","// @flow\n\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform3f,\n UniformMatrix4f\n} from '../uniform_binding';\n\nimport type Context from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type RasterStyleLayer from '../../style/style_layer/raster_style_layer';\n\nexport type RasterUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_tl_parent': Uniform2f,\n 'u_scale_parent': Uniform1f,\n 'u_buffer_scale': Uniform1f,\n 'u_fade_t': Uniform1f,\n 'u_opacity': Uniform1f,\n 'u_image0': Uniform1i,\n 'u_image1': Uniform1i,\n 'u_brightness_low': Uniform1f,\n 'u_brightness_high': Uniform1f,\n 'u_saturation_factor': Uniform1f,\n 'u_contrast_factor': Uniform1f,\n 'u_spin_weights': Uniform3f\n|};\n\nconst rasterUniforms = (context: Context, locations: UniformLocations): RasterUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_tl_parent': new Uniform2f(context, locations.u_tl_parent),\n 'u_scale_parent': new Uniform1f(context, locations.u_scale_parent),\n 'u_buffer_scale': new Uniform1f(context, locations.u_buffer_scale),\n 'u_fade_t': new Uniform1f(context, locations.u_fade_t),\n 'u_opacity': new Uniform1f(context, locations.u_opacity),\n 'u_image0': new Uniform1i(context, locations.u_image0),\n 'u_image1': new Uniform1i(context, locations.u_image1),\n 'u_brightness_low': new Uniform1f(context, locations.u_brightness_low),\n 'u_brightness_high': new Uniform1f(context, locations.u_brightness_high),\n 'u_saturation_factor': new Uniform1f(context, locations.u_saturation_factor),\n 'u_contrast_factor': new Uniform1f(context, locations.u_contrast_factor),\n 'u_spin_weights': new Uniform3f(context, locations.u_spin_weights)\n});\n\nconst rasterUniformValues = (\n matrix: Float32Array,\n parentTL: [number, number],\n parentScaleBy: number,\n fade: {mix: number, opacity: number},\n layer: RasterStyleLayer\n): UniformValues => ({\n 'u_matrix': matrix,\n 'u_tl_parent': parentTL,\n 'u_scale_parent': parentScaleBy,\n 'u_buffer_scale': 1,\n 'u_fade_t': fade.mix,\n 'u_opacity': fade.opacity * layer.paint.get('raster-opacity'),\n 'u_image0': 0,\n 'u_image1': 1,\n 'u_brightness_low': layer.paint.get('raster-brightness-min'),\n 'u_brightness_high': layer.paint.get('raster-brightness-max'),\n 'u_saturation_factor': saturationFactor(layer.paint.get('raster-saturation')),\n 'u_contrast_factor': contrastFactor(layer.paint.get('raster-contrast')),\n 'u_spin_weights': spinWeights(layer.paint.get('raster-hue-rotate'))\n});\n\nfunction spinWeights(angle) {\n angle *= Math.PI / 180;\n const s = Math.sin(angle);\n const c = Math.cos(angle);\n return [\n (2 * c + 1) / 3,\n (-Math.sqrt(3) * s - c + 1) / 3,\n (Math.sqrt(3) * s - c + 1) / 3\n ];\n}\n\nfunction contrastFactor(contrast) {\n return contrast > 0 ?\n 1 / (1 - contrast) :\n 1 + contrast;\n}\n\nfunction saturationFactor(saturation) {\n return saturation > 0 ?\n 1 - 1 / (1.001 - saturation) :\n -saturation;\n}\n\nexport {rasterUniforms, rasterUniformValues};\n","// @flow\n\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n UniformMatrix4f\n} from '../uniform_binding';\nimport {extend} from '../../util/util';\nimport browser from '../../util/browser';\n\nimport type Context from '../../gl/context';\nimport type Painter from '../painter';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\n\nexport type SymbolIconUniformsType = {|\n 'u_is_size_zoom_constant': Uniform1i,\n 'u_is_size_feature_constant': Uniform1i,\n 'u_size_t': Uniform1f,\n 'u_size': Uniform1f,\n 'u_camera_to_center_distance': Uniform1f,\n 'u_pitch': Uniform1f,\n 'u_rotate_symbol': Uniform1i,\n 'u_aspect_ratio': Uniform1f,\n 'u_fade_change': Uniform1f,\n 'u_matrix': UniformMatrix4f,\n 'u_label_plane_matrix': UniformMatrix4f,\n 'u_coord_matrix': UniformMatrix4f,\n 'u_is_text': Uniform1i,\n 'u_pitch_with_map': Uniform1i,\n 'u_texsize': Uniform2f,\n 'u_texture': Uniform1i\n|};\n\nexport type SymbolSDFUniformsType = {|\n 'u_is_size_zoom_constant': Uniform1i,\n 'u_is_size_feature_constant': Uniform1i,\n 'u_size_t': Uniform1f,\n 'u_size': Uniform1f,\n 'u_camera_to_center_distance': Uniform1f,\n 'u_pitch': Uniform1f,\n 'u_rotate_symbol': Uniform1i,\n 'u_aspect_ratio': Uniform1f,\n 'u_fade_change': Uniform1f,\n 'u_matrix': UniformMatrix4f,\n 'u_label_plane_matrix': UniformMatrix4f,\n 'u_coord_matrix': UniformMatrix4f,\n 'u_is_text': Uniform1i,\n 'u_pitch_with_map': Uniform1i,\n 'u_texsize': Uniform2f,\n 'u_texture': Uniform1i,\n 'u_gamma_scale': Uniform1f,\n 'u_device_pixel_ratio': Uniform1f,\n 'u_is_halo': Uniform1i\n|};\n\nexport type symbolTextAndIconUniformsType = {|\n 'u_is_size_zoom_constant': Uniform1i,\n 'u_is_size_feature_constant': Uniform1i,\n 'u_size_t': Uniform1f,\n 'u_size': Uniform1f,\n 'u_camera_to_center_distance': Uniform1f,\n 'u_pitch': Uniform1f,\n 'u_rotate_symbol': Uniform1i,\n 'u_aspect_ratio': Uniform1f,\n 'u_fade_change': Uniform1f,\n 'u_matrix': UniformMatrix4f,\n 'u_label_plane_matrix': UniformMatrix4f,\n 'u_coord_matrix': UniformMatrix4f,\n 'u_is_text': Uniform1i,\n 'u_pitch_with_map': Uniform1i,\n 'u_texsize': Uniform2f,\n 'u_texsize_icon': Uniform2f,\n 'u_texture': Uniform1i,\n 'u_texture_icon': Uniform1i,\n 'u_gamma_scale': Uniform1f,\n 'u_device_pixel_ratio': Uniform1f,\n 'u_is_halo': Uniform1i\n|};\n\nconst symbolIconUniforms = (context: Context, locations: UniformLocations): SymbolIconUniformsType => ({\n 'u_is_size_zoom_constant': new Uniform1i(context, locations.u_is_size_zoom_constant),\n 'u_is_size_feature_constant': new Uniform1i(context, locations.u_is_size_feature_constant),\n 'u_size_t': new Uniform1f(context, locations.u_size_t),\n 'u_size': new Uniform1f(context, locations.u_size),\n 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance),\n 'u_pitch': new Uniform1f(context, locations.u_pitch),\n 'u_rotate_symbol': new Uniform1i(context, locations.u_rotate_symbol),\n 'u_aspect_ratio': new Uniform1f(context, locations.u_aspect_ratio),\n 'u_fade_change': new Uniform1f(context, locations.u_fade_change),\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_label_plane_matrix': new UniformMatrix4f(context, locations.u_label_plane_matrix),\n 'u_coord_matrix': new UniformMatrix4f(context, locations.u_coord_matrix),\n 'u_is_text': new Uniform1i(context, locations.u_is_text),\n 'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_texture': new Uniform1i(context, locations.u_texture)\n});\n\nconst symbolSDFUniforms = (context: Context, locations: UniformLocations): SymbolSDFUniformsType => ({\n 'u_is_size_zoom_constant': new Uniform1i(context, locations.u_is_size_zoom_constant),\n 'u_is_size_feature_constant': new Uniform1i(context, locations.u_is_size_feature_constant),\n 'u_size_t': new Uniform1f(context, locations.u_size_t),\n 'u_size': new Uniform1f(context, locations.u_size),\n 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance),\n 'u_pitch': new Uniform1f(context, locations.u_pitch),\n 'u_rotate_symbol': new Uniform1i(context, locations.u_rotate_symbol),\n 'u_aspect_ratio': new Uniform1f(context, locations.u_aspect_ratio),\n 'u_fade_change': new Uniform1f(context, locations.u_fade_change),\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_label_plane_matrix': new UniformMatrix4f(context, locations.u_label_plane_matrix),\n 'u_coord_matrix': new UniformMatrix4f(context, locations.u_coord_matrix),\n 'u_is_text': new Uniform1i(context, locations.u_is_text),\n 'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_texture': new Uniform1i(context, locations.u_texture),\n 'u_gamma_scale': new Uniform1f(context, locations.u_gamma_scale),\n 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio),\n 'u_is_halo': new Uniform1i(context, locations.u_is_halo)\n});\n\nconst symbolTextAndIconUniforms = (context: Context, locations: UniformLocations): symbolTextAndIconUniformsType => ({\n 'u_is_size_zoom_constant': new Uniform1i(context, locations.u_is_size_zoom_constant),\n 'u_is_size_feature_constant': new Uniform1i(context, locations.u_is_size_feature_constant),\n 'u_size_t': new Uniform1f(context, locations.u_size_t),\n 'u_size': new Uniform1f(context, locations.u_size),\n 'u_camera_to_center_distance': new Uniform1f(context, locations.u_camera_to_center_distance),\n 'u_pitch': new Uniform1f(context, locations.u_pitch),\n 'u_rotate_symbol': new Uniform1i(context, locations.u_rotate_symbol),\n 'u_aspect_ratio': new Uniform1f(context, locations.u_aspect_ratio),\n 'u_fade_change': new Uniform1f(context, locations.u_fade_change),\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_label_plane_matrix': new UniformMatrix4f(context, locations.u_label_plane_matrix),\n 'u_coord_matrix': new UniformMatrix4f(context, locations.u_coord_matrix),\n 'u_is_text': new Uniform1i(context, locations.u_is_text),\n 'u_pitch_with_map': new Uniform1i(context, locations.u_pitch_with_map),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_texsize_icon': new Uniform2f(context, locations.u_texsize_icon),\n 'u_texture': new Uniform1i(context, locations.u_texture),\n 'u_texture_icon': new Uniform1i(context, locations.u_texture_icon),\n 'u_gamma_scale': new Uniform1f(context, locations.u_gamma_scale),\n 'u_device_pixel_ratio': new Uniform1f(context, locations.u_device_pixel_ratio),\n 'u_is_halo': new Uniform1i(context, locations.u_is_halo)\n});\n\nconst symbolIconUniformValues = (\n functionType: string,\n size: ?{uSizeT: number, uSize: number},\n rotateInShader: boolean,\n pitchWithMap: boolean,\n painter: Painter,\n matrix: Float32Array,\n labelPlaneMatrix: Float32Array,\n glCoordMatrix: Float32Array,\n isText: boolean,\n texSize: [number, number]\n): UniformValues => {\n const transform = painter.transform;\n\n return {\n 'u_is_size_zoom_constant': +(functionType === 'constant' || functionType === 'source'),\n 'u_is_size_feature_constant': +(functionType === 'constant' || functionType === 'camera'),\n 'u_size_t': size ? size.uSizeT : 0,\n 'u_size': size ? size.uSize : 0,\n 'u_camera_to_center_distance': transform.cameraToCenterDistance,\n 'u_pitch': transform.pitch / 360 * 2 * Math.PI,\n 'u_rotate_symbol': +rotateInShader,\n 'u_aspect_ratio': transform.width / transform.height,\n 'u_fade_change': painter.options.fadeDuration ? painter.symbolFadeChange : 1,\n 'u_matrix': matrix,\n 'u_label_plane_matrix': labelPlaneMatrix,\n 'u_coord_matrix': glCoordMatrix,\n 'u_is_text': +isText,\n 'u_pitch_with_map': +pitchWithMap,\n 'u_texsize': texSize,\n 'u_texture': 0\n };\n};\n\nconst symbolSDFUniformValues = (\n functionType: string,\n size: ?{uSizeT: number, uSize: number},\n rotateInShader: boolean,\n pitchWithMap: boolean,\n painter: Painter,\n matrix: Float32Array,\n labelPlaneMatrix: Float32Array,\n glCoordMatrix: Float32Array,\n isText: boolean,\n texSize: [number, number],\n isHalo: boolean\n): UniformValues => {\n const transform = painter.transform;\n\n return extend(symbolIconUniformValues(functionType, size,\n rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix,\n glCoordMatrix, isText, texSize), {\n 'u_gamma_scale': (pitchWithMap ? Math.cos(transform._pitch) * transform.cameraToCenterDistance : 1),\n 'u_device_pixel_ratio': browser.devicePixelRatio,\n 'u_is_halo': +isHalo\n });\n};\n\nconst symbolTextAndIconUniformValues = (\n functionType: string,\n size: ?{uSizeT: number, uSize: number},\n rotateInShader: boolean,\n pitchWithMap: boolean,\n painter: Painter,\n matrix: Float32Array,\n labelPlaneMatrix: Float32Array,\n glCoordMatrix: Float32Array,\n texSizeSDF: [number, number],\n texSizeIcon: [number, number]\n): UniformValues => {\n return extend(symbolSDFUniformValues(functionType, size,\n rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix,\n glCoordMatrix, true, texSizeSDF, true), {\n 'u_texsize_icon': texSizeIcon,\n 'u_texture_icon': 1\n });\n};\n\nexport {symbolIconUniforms, symbolSDFUniforms, symbolIconUniformValues, symbolSDFUniformValues, symbolTextAndIconUniformValues, symbolTextAndIconUniforms};\n","// @flow\n\nimport type Painter from './painter';\nimport type SourceCache from '../source/source_cache';\nimport type StyleLayer from '../style/style_layer';\nimport type {OverscaledTileID} from '../source/tile_id';\nimport type SymbolBucket from '../data/bucket/symbol_bucket';\nimport DepthMode from '../gl/depth_mode';\nimport StencilMode from '../gl/stencil_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport {collisionUniformValues, collisionCircleUniformValues} from './program/collision_program';\n\nimport {QuadTriangleArray, CollisionCircleLayoutArray} from '../data/array_types';\nimport {collisionCircleLayout} from '../data/bucket/symbol_attributes';\nimport SegmentVector from '../data/segment';\nimport {mat4} from 'gl-matrix';\nimport VertexBuffer from '../gl/vertex_buffer';\nimport IndexBuffer from '../gl/index_buffer';\n\nexport default drawCollisionDebug;\n\ntype TileBatch = {\n circleArray: Array,\n circleOffset: number,\n transform: mat4,\n invTransform: mat4\n};\n\nlet quadTriangles: ?QuadTriangleArray;\n\nfunction drawCollisionDebug(painter: Painter, sourceCache: SourceCache, layer: StyleLayer, coords: Array, translate: [number, number], translateAnchor: 'map' | 'viewport', isText: boolean) {\n const context = painter.context;\n const gl = context.gl;\n const program = painter.useProgram('collisionBox');\n const tileBatches: Array = [];\n let circleCount = 0;\n let circleOffset = 0;\n\n for (let i = 0; i < coords.length; i++) {\n const coord = coords[i];\n const tile = sourceCache.getTile(coord);\n const bucket: ?SymbolBucket = (tile.getBucket(layer): any);\n if (!bucket) continue;\n let posMatrix = coord.posMatrix;\n if (translate[0] !== 0 || translate[1] !== 0) {\n posMatrix = painter.translatePosMatrix(coord.posMatrix, tile, translate, translateAnchor);\n }\n const buffers = isText ? bucket.textCollisionBox : bucket.iconCollisionBox;\n // Get collision circle data of this bucket\n const circleArray: Array = bucket.collisionCircleArray;\n if (circleArray.length > 0) {\n // We need to know the projection matrix that was used for projecting collision circles to the screen.\n // This might vary between buckets as the symbol placement is a continous process. This matrix is\n // required for transforming points from previous screen space to the current one\n const invTransform = mat4.create();\n const transform = posMatrix;\n\n mat4.mul(invTransform, bucket.placementInvProjMatrix, painter.transform.glCoordMatrix);\n mat4.mul(invTransform, invTransform, bucket.placementViewportMatrix);\n\n tileBatches.push({\n circleArray,\n circleOffset,\n transform,\n invTransform\n });\n\n circleCount += circleArray.length / 4; // 4 values per circle\n circleOffset = circleCount;\n }\n if (!buffers) continue;\n program.draw(context, gl.LINES,\n DepthMode.disabled, StencilMode.disabled,\n painter.colorModeForRenderPass(),\n CullFaceMode.disabled,\n collisionUniformValues(\n posMatrix,\n painter.transform,\n tile),\n layer.id, buffers.layoutVertexBuffer, buffers.indexBuffer,\n buffers.segments, null, painter.transform.zoom, null, null,\n buffers.collisionVertexBuffer);\n }\n\n if (!isText || !tileBatches.length) {\n return;\n }\n\n // Render collision circles\n const circleProgram = painter.useProgram('collisionCircle');\n\n // Construct vertex data\n const vertexData = new CollisionCircleLayoutArray();\n vertexData.resize(circleCount * 4);\n vertexData._trim();\n\n let vertexOffset = 0;\n\n for (const batch of tileBatches) {\n for (let i = 0; i < batch.circleArray.length / 4; i++) {\n const circleIdx = i * 4;\n const x = batch.circleArray[circleIdx + 0];\n const y = batch.circleArray[circleIdx + 1];\n const radius = batch.circleArray[circleIdx + 2];\n const collision = batch.circleArray[circleIdx + 3];\n\n // 4 floats per vertex, 4 vertices per quad\n vertexData.emplace(vertexOffset++, x, y, radius, collision, 0);\n vertexData.emplace(vertexOffset++, x, y, radius, collision, 1);\n vertexData.emplace(vertexOffset++, x, y, radius, collision, 2);\n vertexData.emplace(vertexOffset++, x, y, radius, collision, 3);\n }\n }\n if (!quadTriangles || quadTriangles.length < circleCount * 2) {\n quadTriangles = createQuadTriangles(circleCount);\n }\n\n const indexBuffer: IndexBuffer = context.createIndexBuffer(quadTriangles, true);\n const vertexBuffer: VertexBuffer = context.createVertexBuffer(vertexData, collisionCircleLayout.members, true);\n\n // Render batches\n for (const batch of tileBatches) {\n const uniforms = collisionCircleUniformValues(\n batch.transform,\n batch.invTransform,\n painter.transform\n );\n\n circleProgram.draw(\n context,\n gl.TRIANGLES,\n DepthMode.disabled,\n StencilMode.disabled,\n painter.colorModeForRenderPass(),\n CullFaceMode.disabled,\n uniforms,\n layer.id,\n vertexBuffer,\n indexBuffer,\n SegmentVector.simpleSegment(0, batch.circleOffset * 2, batch.circleArray.length, batch.circleArray.length / 2),\n null,\n painter.transform.zoom,\n null,\n null,\n null);\n }\n\n vertexBuffer.destroy();\n indexBuffer.destroy();\n}\n\nfunction createQuadTriangles(quadCount: number): QuadTriangleArray {\n const triCount = quadCount * 2;\n const array = new QuadTriangleArray();\n\n array.resize(triCount);\n array._trim();\n\n // Two triangles and 4 vertices per quad.\n for (let i = 0; i < triCount; i++) {\n const idx = i * 6;\n\n array.uint16[idx + 0] = i * 4 + 0;\n array.uint16[idx + 1] = i * 4 + 1;\n array.uint16[idx + 2] = i * 4 + 2;\n array.uint16[idx + 3] = i * 4 + 2;\n array.uint16[idx + 4] = i * 4 + 3;\n array.uint16[idx + 5] = i * 4 + 0;\n }\n\n return array;\n}\n","// @flow\n\nimport {bgPatternUniformValues} from './pattern';\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n UniformColor,\n UniformMatrix4f\n} from '../uniform_binding';\nimport {extend} from '../../util/util';\n\nimport type Painter from '../painter';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type Context from '../../gl/context';\nimport type Color from '../../style-spec/util/color';\nimport type {CrossFaded} from '../../style/properties';\nimport type {CrossfadeParameters} from '../../style/evaluation_parameters';\nimport type {OverscaledTileID} from '../../source/tile_id';\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image';\n\nexport type BackgroundUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_opacity': Uniform1f,\n 'u_color': UniformColor\n|};\n\nexport type BackgroundPatternUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_opacity': Uniform1f,\n // pattern uniforms:\n 'u_image': Uniform1i,\n 'u_pattern_tl_a': Uniform2f,\n 'u_pattern_br_a': Uniform2f,\n 'u_pattern_tl_b': Uniform2f,\n 'u_pattern_br_b': Uniform2f,\n 'u_texsize': Uniform2f,\n 'u_mix': Uniform1f,\n 'u_pattern_size_a': Uniform2f,\n 'u_pattern_size_b': Uniform2f,\n 'u_scale_a': Uniform1f,\n 'u_scale_b': Uniform1f,\n 'u_pixel_coord_upper': Uniform2f,\n 'u_pixel_coord_lower': Uniform2f,\n 'u_tile_units_to_pixels': Uniform1f\n|};\n\nconst backgroundUniforms = (context: Context, locations: UniformLocations): BackgroundUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_opacity': new Uniform1f(context, locations.u_opacity),\n 'u_color': new UniformColor(context, locations.u_color)\n});\n\nconst backgroundPatternUniforms = (context: Context, locations: UniformLocations): BackgroundPatternUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_opacity': new Uniform1f(context, locations.u_opacity),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_pattern_tl_a': new Uniform2f(context, locations.u_pattern_tl_a),\n 'u_pattern_br_a': new Uniform2f(context, locations.u_pattern_br_a),\n 'u_pattern_tl_b': new Uniform2f(context, locations.u_pattern_tl_b),\n 'u_pattern_br_b': new Uniform2f(context, locations.u_pattern_br_b),\n 'u_texsize': new Uniform2f(context, locations.u_texsize),\n 'u_mix': new Uniform1f(context, locations.u_mix),\n 'u_pattern_size_a': new Uniform2f(context, locations.u_pattern_size_a),\n 'u_pattern_size_b': new Uniform2f(context, locations.u_pattern_size_b),\n 'u_scale_a': new Uniform1f(context, locations.u_scale_a),\n 'u_scale_b': new Uniform1f(context, locations.u_scale_b),\n 'u_pixel_coord_upper': new Uniform2f(context, locations.u_pixel_coord_upper),\n 'u_pixel_coord_lower': new Uniform2f(context, locations.u_pixel_coord_lower),\n 'u_tile_units_to_pixels': new Uniform1f(context, locations.u_tile_units_to_pixels)\n});\n\nconst backgroundUniformValues = (\n matrix: Float32Array,\n opacity: number,\n color: Color\n): UniformValues => ({\n 'u_matrix': matrix,\n 'u_opacity': opacity,\n 'u_color': color\n});\n\nconst backgroundPatternUniformValues = (\n matrix: Float32Array,\n opacity: number,\n painter: Painter,\n image: CrossFaded,\n tile: {tileID: OverscaledTileID, tileSize: number},\n crossfade: CrossfadeParameters\n): UniformValues => extend(\n bgPatternUniformValues(image, crossfade, painter, tile),\n {\n 'u_matrix': matrix,\n 'u_opacity': opacity\n }\n);\n\nexport {\n backgroundUniforms,\n backgroundPatternUniforms,\n backgroundUniformValues,\n backgroundPatternUniformValues\n};\n","// @flow\n\nimport {fillExtrusionUniforms, fillExtrusionPatternUniforms} from './fill_extrusion_program';\nimport {fillUniforms, fillPatternUniforms, fillOutlineUniforms, fillOutlinePatternUniforms} from './fill_program';\nimport {circleUniforms} from './circle_program';\nimport {collisionUniforms, collisionCircleUniforms} from './collision_program';\nimport {debugUniforms} from './debug_program';\nimport {clippingMaskUniforms} from './clipping_mask_program';\nimport {heatmapUniforms, heatmapTextureUniforms} from './heatmap_program';\nimport {hillshadeUniforms, hillshadePrepareUniforms} from './hillshade_program';\nimport {lineUniforms, lineGradientUniforms, linePatternUniforms, lineSDFUniforms} from './line_program';\nimport {rasterUniforms} from './raster_program';\nimport {symbolIconUniforms, symbolSDFUniforms, symbolTextAndIconUniforms} from './symbol_program';\nimport {backgroundUniforms, backgroundPatternUniforms} from './background_program';\n\nexport const programUniforms = {\n fillExtrusion: fillExtrusionUniforms,\n fillExtrusionPattern: fillExtrusionPatternUniforms,\n fill: fillUniforms,\n fillPattern: fillPatternUniforms,\n fillOutline: fillOutlineUniforms,\n fillOutlinePattern: fillOutlinePatternUniforms,\n circle: circleUniforms,\n collisionBox: collisionUniforms,\n collisionCircle: collisionCircleUniforms,\n debug: debugUniforms,\n clippingMask: clippingMaskUniforms,\n heatmap: heatmapUniforms,\n heatmapTexture: heatmapTextureUniforms,\n hillshade: hillshadeUniforms,\n hillshadePrepare: hillshadePrepareUniforms,\n line: lineUniforms,\n lineGradient: lineGradientUniforms,\n linePattern: linePatternUniforms,\n lineSDF: lineSDFUniforms,\n raster: rasterUniforms,\n symbolIcon: symbolIconUniforms,\n symbolSDF: symbolSDFUniforms,\n symbolTextAndIcon: symbolTextAndIconUniforms,\n background: backgroundUniforms,\n backgroundPattern: backgroundPatternUniforms\n};\n","// @flow\n\nimport {mat4} from 'gl-matrix';\n\nimport {\n Uniform1i,\n Uniform1f,\n Uniform2f,\n UniformColor,\n UniformMatrix4f,\n Uniform4f\n} from '../uniform_binding';\nimport EXTENT from '../../data/extent';\nimport MercatorCoordinate from '../../geo/mercator_coordinate';\n\nimport type Context from '../../gl/context';\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type Tile from '../../source/tile';\nimport type Painter from '../painter';\nimport type HillshadeStyleLayer from '../../style/style_layer/hillshade_style_layer';\nimport type DEMData from '../../data/dem_data';\nimport type {OverscaledTileID} from '../../source/tile_id';\n\nexport type HillshadeUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_image': Uniform1i,\n 'u_latrange': Uniform2f,\n 'u_light': Uniform2f,\n 'u_shadow': UniformColor,\n 'u_highlight': UniformColor,\n 'u_accent': UniformColor\n|};\n\nexport type HillshadePrepareUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_image': Uniform1i,\n 'u_dimension': Uniform2f,\n 'u_zoom': Uniform1f,\n 'u_unpack': Uniform4f\n|};\n\nconst hillshadeUniforms = (context: Context, locations: UniformLocations): HillshadeUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_latrange': new Uniform2f(context, locations.u_latrange),\n 'u_light': new Uniform2f(context, locations.u_light),\n 'u_shadow': new UniformColor(context, locations.u_shadow),\n 'u_highlight': new UniformColor(context, locations.u_highlight),\n 'u_accent': new UniformColor(context, locations.u_accent)\n});\n\nconst hillshadePrepareUniforms = (context: Context, locations: UniformLocations): HillshadePrepareUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_image': new Uniform1i(context, locations.u_image),\n 'u_dimension': new Uniform2f(context, locations.u_dimension),\n 'u_zoom': new Uniform1f(context, locations.u_zoom),\n 'u_unpack': new Uniform4f(context, locations.u_unpack)\n});\n\nconst hillshadeUniformValues = (\n painter: Painter,\n tile: Tile,\n layer: HillshadeStyleLayer\n): UniformValues => {\n const shadow = layer.paint.get(\"hillshade-shadow-color\");\n const highlight = layer.paint.get(\"hillshade-highlight-color\");\n const accent = layer.paint.get(\"hillshade-accent-color\");\n\n let azimuthal = layer.paint.get('hillshade-illumination-direction') * (Math.PI / 180);\n // modify azimuthal angle by map rotation if light is anchored at the viewport\n if (layer.paint.get('hillshade-illumination-anchor') === 'viewport') {\n azimuthal -= painter.transform.angle;\n }\n const align = !painter.options.moving;\n return {\n 'u_matrix': painter.transform.calculatePosMatrix(tile.tileID.toUnwrapped(), align),\n 'u_image': 0,\n 'u_latrange': getTileLatRange(painter, tile.tileID),\n 'u_light': [layer.paint.get('hillshade-exaggeration'), azimuthal],\n 'u_shadow': shadow,\n 'u_highlight': highlight,\n 'u_accent': accent\n };\n};\n\nconst hillshadeUniformPrepareValues = (\n tileID: OverscaledTileID, dem: DEMData\n): UniformValues => {\n\n const stride = dem.stride;\n const matrix = mat4.create();\n // Flip rendering at y axis.\n mat4.ortho(matrix, 0, EXTENT, -EXTENT, 0, 0, 1);\n mat4.translate(matrix, matrix, [0, -EXTENT, 0]);\n\n return {\n 'u_matrix': matrix,\n 'u_image': 1,\n 'u_dimension': [stride, stride],\n 'u_zoom': tileID.overscaledZ,\n 'u_unpack': dem.getUnpackVector()\n };\n};\n\nfunction getTileLatRange(painter: Painter, tileID: OverscaledTileID) {\n // for scaling the magnitude of a points slope by its latitude\n const tilesAtZoom = Math.pow(2, tileID.canonical.z);\n const y = tileID.canonical.y;\n return [\n new MercatorCoordinate(0, y / tilesAtZoom).toLngLat().lat,\n new MercatorCoordinate(0, (y + 1) / tilesAtZoom).toLngLat().lat];\n}\n\nexport {\n hillshadeUniforms,\n hillshadePrepareUniforms,\n hillshadeUniformValues,\n hillshadeUniformPrepareValues\n};\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\nimport drawCollisionDebug from './draw_collision_debug';\n\nimport SegmentVector from '../data/segment';\nimport pixelsToTileUnits from '../source/pixels_to_tile_units';\nimport * as symbolProjection from '../symbol/projection';\nimport * as symbolSize from '../symbol/symbol_size';\nimport {mat4} from 'gl-matrix';\nconst identityMat4 = mat4.identity(new Float32Array(16));\nimport StencilMode from '../gl/stencil_mode';\nimport DepthMode from '../gl/depth_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport {addDynamicAttributes} from '../data/bucket/symbol_bucket';\n\nimport {getAnchorAlignment, WritingMode} from '../symbol/shaping';\nimport ONE_EM from '../symbol/one_em';\nimport {evaluateVariableOffset} from '../symbol/symbol_layout';\n\nimport {\n symbolIconUniformValues,\n symbolSDFUniformValues,\n symbolTextAndIconUniformValues\n} from './program/symbol_program';\n\nimport type Painter from './painter';\nimport type SourceCache from '../source/source_cache';\nimport type SymbolStyleLayer from '../style/style_layer/symbol_style_layer';\nimport type SymbolBucket, {SymbolBuffers} from '../data/bucket/symbol_bucket';\nimport type Texture from '../render/texture';\nimport type {OverscaledTileID} from '../source/tile_id';\nimport type {UniformValues} from './uniform_binding';\nimport type {SymbolSDFUniformsType} from '../render/program/symbol_program';\nimport type {CrossTileID, VariableOffset} from '../symbol/placement';\n\nexport default drawSymbols;\n\ntype SymbolTileRenderState = {\n segments: SegmentVector,\n sortKey: number,\n state: {\n program: any,\n buffers: SymbolBuffers,\n uniformValues: any,\n atlasTexture: Texture,\n atlasTextureIcon: Texture | null,\n atlasInterpolation: any,\n atlasInterpolationIcon: any,\n isSDF: boolean,\n hasHalo: boolean\n }\n};\n\nfunction drawSymbols(painter: Painter, sourceCache: SourceCache, layer: SymbolStyleLayer, coords: Array, variableOffsets: {[_: CrossTileID]: VariableOffset}) {\n if (painter.renderPass !== 'translucent') return;\n\n // Disable the stencil test so that labels aren't clipped to tile boundaries.\n const stencilMode = StencilMode.disabled;\n const colorMode = painter.colorModeForRenderPass();\n const variablePlacement = layer.layout.get('text-variable-anchor');\n\n //Compute variable-offsets before painting since icons and text data positioning\n //depend on each other in this case.\n if (variablePlacement) {\n updateVariableAnchors(coords, painter, layer, sourceCache,\n layer.layout.get('text-rotation-alignment'),\n layer.layout.get('text-pitch-alignment'),\n variableOffsets\n );\n }\n\n if (layer.paint.get('icon-opacity').constantOr(1) !== 0) {\n drawLayerSymbols(painter, sourceCache, layer, coords, false,\n layer.paint.get('icon-translate'),\n layer.paint.get('icon-translate-anchor'),\n layer.layout.get('icon-rotation-alignment'),\n layer.layout.get('icon-pitch-alignment'),\n layer.layout.get('icon-keep-upright'),\n stencilMode, colorMode\n );\n }\n\n if (layer.paint.get('text-opacity').constantOr(1) !== 0) {\n drawLayerSymbols(painter, sourceCache, layer, coords, true,\n layer.paint.get('text-translate'),\n layer.paint.get('text-translate-anchor'),\n layer.layout.get('text-rotation-alignment'),\n layer.layout.get('text-pitch-alignment'),\n layer.layout.get('text-keep-upright'),\n stencilMode, colorMode\n );\n }\n\n if (sourceCache.map.showCollisionBoxes) {\n drawCollisionDebug(painter, sourceCache, layer, coords, layer.paint.get('text-translate'),\n layer.paint.get('text-translate-anchor'), true);\n drawCollisionDebug(painter, sourceCache, layer, coords, layer.paint.get('icon-translate'),\n layer.paint.get('icon-translate-anchor'), false);\n }\n}\n\nfunction calculateVariableRenderShift(anchor, width, height, textOffset, textBoxScale, renderTextSize): Point {\n const {horizontalAlign, verticalAlign} = getAnchorAlignment(anchor);\n const shiftX = -(horizontalAlign - 0.5) * width;\n const shiftY = -(verticalAlign - 0.5) * height;\n const variableOffset = evaluateVariableOffset(anchor, textOffset);\n return new Point(\n (shiftX / textBoxScale + variableOffset[0]) * renderTextSize,\n (shiftY / textBoxScale + variableOffset[1]) * renderTextSize\n );\n}\n\nfunction updateVariableAnchors(coords, painter, layer, sourceCache, rotationAlignment, pitchAlignment, variableOffsets) {\n const tr = painter.transform;\n const rotateWithMap = rotationAlignment === 'map';\n const pitchWithMap = pitchAlignment === 'map';\n\n for (const coord of coords) {\n const tile = sourceCache.getTile(coord);\n const bucket: SymbolBucket = (tile.getBucket(layer): any);\n if (!bucket || !bucket.text || !bucket.text.segments.get().length) continue;\n\n const sizeData = bucket.textSizeData;\n const size = symbolSize.evaluateSizeForZoom(sizeData, tr.zoom);\n\n const pixelToTileScale = pixelsToTileUnits(tile, 1, painter.transform.zoom);\n const labelPlaneMatrix = symbolProjection.getLabelPlaneMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, pixelToTileScale);\n const updateTextFitIcon = layer.layout.get('icon-text-fit') !== 'none' && bucket.hasIconData();\n\n if (size) {\n const tileScale = Math.pow(2, tr.zoom - tile.tileID.overscaledZ);\n updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, symbolSize,\n tr, labelPlaneMatrix, coord.posMatrix, tileScale, size, updateTextFitIcon);\n }\n }\n}\n\nfunction updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, symbolSize,\n transform, labelPlaneMatrix, posMatrix, tileScale, size, updateTextFitIcon) {\n const placedSymbols = bucket.text.placedSymbolArray;\n const dynamicTextLayoutVertexArray = bucket.text.dynamicLayoutVertexArray;\n const dynamicIconLayoutVertexArray = bucket.icon.dynamicLayoutVertexArray;\n const placedTextShifts = {};\n\n dynamicTextLayoutVertexArray.clear();\n for (let s = 0; s < placedSymbols.length; s++) {\n const symbol: any = placedSymbols.get(s);\n const skipOrientation = bucket.allowVerticalPlacement && !symbol.placedOrientation;\n const variableOffset = (!symbol.hidden && symbol.crossTileID && !skipOrientation) ? variableOffsets[symbol.crossTileID] : null;\n\n if (!variableOffset) {\n // These symbols are from a justification that is not being used, or a label that wasn't placed\n // so we don't need to do the extra math to figure out what incremental shift to apply.\n symbolProjection.hideGlyphs(symbol.numGlyphs, dynamicTextLayoutVertexArray);\n } else {\n const tileAnchor = new Point(symbol.anchorX, symbol.anchorY);\n const projectedAnchor = symbolProjection.project(tileAnchor, pitchWithMap ? posMatrix : labelPlaneMatrix);\n const perspectiveRatio = symbolProjection.getPerspectiveRatio(transform.cameraToCenterDistance, projectedAnchor.signedDistanceFromCamera);\n let renderTextSize = symbolSize.evaluateSizeForFeature(bucket.textSizeData, size, symbol) * perspectiveRatio / ONE_EM;\n if (pitchWithMap) {\n // Go from size in pixels to equivalent size in tile units\n renderTextSize *= bucket.tilePixelRatio / tileScale;\n }\n\n const {width, height, anchor, textOffset, textBoxScale} = variableOffset;\n\n const shift = calculateVariableRenderShift(\n anchor, width, height, textOffset, textBoxScale, renderTextSize);\n\n // Usual case is that we take the projected anchor and add the pixel-based shift\n // calculated above. In the (somewhat weird) case of pitch-aligned text, we add an equivalent\n // tile-unit based shift to the anchor before projecting to the label plane.\n const shiftedAnchor = pitchWithMap ?\n symbolProjection.project(tileAnchor.add(shift), labelPlaneMatrix).point :\n projectedAnchor.point.add(rotateWithMap ?\n shift.rotate(-transform.angle) :\n shift);\n\n const angle = (bucket.allowVerticalPlacement && symbol.placedOrientation === WritingMode.vertical) ? Math.PI / 2 : 0;\n for (let g = 0; g < symbol.numGlyphs; g++) {\n addDynamicAttributes(dynamicTextLayoutVertexArray, shiftedAnchor, angle);\n }\n //Only offset horizontal text icons\n if (updateTextFitIcon && symbol.associatedIconIndex >= 0) {\n placedTextShifts[symbol.associatedIconIndex] = {shiftedAnchor, angle};\n }\n }\n }\n\n if (updateTextFitIcon) {\n dynamicIconLayoutVertexArray.clear();\n const placedIcons = bucket.icon.placedSymbolArray;\n for (let i = 0; i < placedIcons.length; i++) {\n const placedIcon = placedIcons.get(i);\n if (placedIcon.hidden) {\n symbolProjection.hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray);\n } else {\n const shift = placedTextShifts[i];\n if (!shift) {\n symbolProjection.hideGlyphs(placedIcon.numGlyphs, dynamicIconLayoutVertexArray);\n } else {\n for (let g = 0; g < placedIcon.numGlyphs; g++) {\n addDynamicAttributes(dynamicIconLayoutVertexArray, shift.shiftedAnchor, shift.angle);\n }\n }\n }\n }\n bucket.icon.dynamicLayoutVertexBuffer.updateData(dynamicIconLayoutVertexArray);\n }\n bucket.text.dynamicLayoutVertexBuffer.updateData(dynamicTextLayoutVertexArray);\n}\n\nfunction getSymbolProgramName(isSDF: boolean, isText: boolean, bucket: SymbolBucket) {\n if (bucket.iconsInText && isText) {\n return 'symbolTextAndIcon';\n } else if (isSDF) {\n return 'symbolSDF';\n } else {\n return 'symbolIcon';\n }\n}\n\nfunction drawLayerSymbols(painter, sourceCache, layer, coords, isText, translate, translateAnchor,\n rotationAlignment, pitchAlignment, keepUpright, stencilMode, colorMode) {\n\n const context = painter.context;\n const gl = context.gl;\n const tr = painter.transform;\n\n const rotateWithMap = rotationAlignment === 'map';\n const pitchWithMap = pitchAlignment === 'map';\n const alongLine = rotateWithMap && layer.layout.get('symbol-placement') !== 'point';\n // Line label rotation happens in `updateLineLabels`\n // Pitched point labels are automatically rotated by the labelPlaneMatrix projection\n // Unpitched point labels need to have their rotation applied after projection\n const rotateInShader = rotateWithMap && !pitchWithMap && !alongLine;\n\n const hasSortKey = layer.layout.get('symbol-sort-key').constantOr(1) !== undefined;\n let sortFeaturesByKey = false;\n\n const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);\n\n const variablePlacement = layer.layout.get('text-variable-anchor');\n\n const tileRenderState: Array = [];\n\n for (const coord of coords) {\n const tile = sourceCache.getTile(coord);\n const bucket: SymbolBucket = (tile.getBucket(layer): any);\n if (!bucket) continue;\n const buffers = isText ? bucket.text : bucket.icon;\n if (!buffers || !buffers.segments.get().length) continue;\n const programConfiguration = buffers.programConfigurations.get(layer.id);\n\n const isSDF = isText || bucket.sdfIcons;\n\n const sizeData = isText ? bucket.textSizeData : bucket.iconSizeData;\n const transformed = pitchWithMap || tr.pitch !== 0;\n\n const program = painter.useProgram(getSymbolProgramName(isSDF, isText, bucket), programConfiguration);\n const size = symbolSize.evaluateSizeForZoom(sizeData, tr.zoom);\n\n let texSize: [number, number];\n let texSizeIcon: [number, number] = [0, 0];\n let atlasTexture;\n let atlasInterpolation;\n let atlasTextureIcon = null;\n let atlasInterpolationIcon;\n if (isText) {\n atlasTexture = tile.glyphAtlasTexture;\n atlasInterpolation = gl.LINEAR;\n texSize = tile.glyphAtlasTexture.size;\n if (bucket.iconsInText) {\n texSizeIcon = tile.imageAtlasTexture.size;\n atlasTextureIcon = tile.imageAtlasTexture;\n const zoomDependentSize = sizeData.kind === 'composite' || sizeData.kind === 'camera';\n atlasInterpolationIcon = transformed || painter.options.rotating || painter.options.zooming || zoomDependentSize ? gl.LINEAR : gl.NEAREST;\n }\n } else {\n const iconScaled = layer.layout.get('icon-size').constantOr(0) !== 1 || bucket.iconsNeedLinear;\n atlasTexture = tile.imageAtlasTexture;\n atlasInterpolation = isSDF || painter.options.rotating || painter.options.zooming || iconScaled || transformed ?\n gl.LINEAR :\n gl.NEAREST;\n texSize = tile.imageAtlasTexture.size;\n }\n\n const s = pixelsToTileUnits(tile, 1, painter.transform.zoom);\n const labelPlaneMatrix = symbolProjection.getLabelPlaneMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, s);\n const glCoordMatrix = symbolProjection.getGlCoordMatrix(coord.posMatrix, pitchWithMap, rotateWithMap, painter.transform, s);\n\n const hasVariableAnchors = variablePlacement && bucket.hasTextData();\n const updateTextFitIcon = layer.layout.get('icon-text-fit') !== 'none' &&\n hasVariableAnchors &&\n bucket.hasIconData();\n\n if (alongLine) {\n symbolProjection.updateLineLabels(bucket, coord.posMatrix, painter, isText, labelPlaneMatrix, glCoordMatrix, pitchWithMap, keepUpright);\n }\n\n const matrix = painter.translatePosMatrix(coord.posMatrix, tile, translate, translateAnchor),\n uLabelPlaneMatrix = (alongLine || (isText && variablePlacement) || updateTextFitIcon) ? identityMat4 : labelPlaneMatrix,\n uglCoordMatrix = painter.translatePosMatrix(glCoordMatrix, tile, translate, translateAnchor, true);\n\n const hasHalo = isSDF && layer.paint.get(isText ? 'text-halo-width' : 'icon-halo-width').constantOr(1) !== 0;\n\n let uniformValues;\n if (isSDF) {\n if (!bucket.iconsInText) {\n uniformValues = symbolSDFUniformValues(sizeData.kind,\n size, rotateInShader, pitchWithMap, painter, matrix,\n uLabelPlaneMatrix, uglCoordMatrix, isText, texSize, true);\n } else {\n uniformValues = symbolTextAndIconUniformValues(sizeData.kind,\n size, rotateInShader, pitchWithMap, painter, matrix,\n uLabelPlaneMatrix, uglCoordMatrix, texSize, texSizeIcon);\n }\n } else {\n uniformValues = symbolIconUniformValues(sizeData.kind,\n size, rotateInShader, pitchWithMap, painter, matrix,\n uLabelPlaneMatrix, uglCoordMatrix, isText, texSize);\n }\n\n const state = {\n program,\n buffers,\n uniformValues,\n atlasTexture,\n atlasTextureIcon,\n atlasInterpolation,\n atlasInterpolationIcon,\n isSDF,\n hasHalo\n };\n\n if (hasSortKey && bucket.canOverlap) {\n sortFeaturesByKey = true;\n const oldSegments = buffers.segments.get();\n for (const segment of oldSegments) {\n tileRenderState.push({\n segments: new SegmentVector([segment]),\n sortKey: ((segment.sortKey: any): number),\n state\n });\n }\n } else {\n tileRenderState.push({\n segments: buffers.segments,\n sortKey: 0,\n state\n });\n }\n }\n\n if (sortFeaturesByKey) {\n tileRenderState.sort((a, b) => a.sortKey - b.sortKey);\n }\n\n for (const segmentState of tileRenderState) {\n const state = segmentState.state;\n\n context.activeTexture.set(gl.TEXTURE0);\n state.atlasTexture.bind(state.atlasInterpolation, gl.CLAMP_TO_EDGE);\n if (state.atlasTextureIcon) {\n context.activeTexture.set(gl.TEXTURE1);\n if (state.atlasTextureIcon) {\n state.atlasTextureIcon.bind(state.atlasInterpolationIcon, gl.CLAMP_TO_EDGE);\n }\n }\n\n if (state.isSDF) {\n const uniformValues = ((state.uniformValues: any): UniformValues);\n if (state.hasHalo) {\n uniformValues['u_is_halo'] = 1;\n drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, uniformValues);\n }\n uniformValues['u_is_halo'] = 0;\n }\n drawSymbolElements(state.buffers, segmentState.segments, layer, painter, state.program, depthMode, stencilMode, colorMode, state.uniformValues);\n }\n}\n\nfunction drawSymbolElements(buffers, segments, layer, painter, program, depthMode, stencilMode, colorMode, uniformValues) {\n const context = painter.context;\n const gl = context.gl;\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, layer.id, buffers.layoutVertexBuffer,\n buffers.indexBuffer, segments, layer.paint,\n painter.transform.zoom, buffers.programConfigurations.get(layer.id),\n buffers.dynamicLayoutVertexBuffer, buffers.opacityVertexBuffer);\n}\n","// @flow\n\nimport Color from '../style-spec/util/color';\nimport DepthMode from '../gl/depth_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport {\n fillUniformValues,\n fillPatternUniformValues,\n fillOutlineUniformValues,\n fillOutlinePatternUniformValues\n} from './program/fill_program';\n\nimport type Painter from './painter';\nimport type SourceCache from '../source/source_cache';\nimport type FillStyleLayer from '../style/style_layer/fill_style_layer';\nimport type FillBucket from '../data/bucket/fill_bucket';\nimport type {OverscaledTileID} from '../source/tile_id';\n\nexport default drawFill;\n\nfunction drawFill(painter: Painter, sourceCache: SourceCache, layer: FillStyleLayer, coords: Array) {\n const color = layer.paint.get('fill-color');\n const opacity = layer.paint.get('fill-opacity');\n\n if (opacity.constantOr(1) === 0) {\n return;\n }\n\n const colorMode = painter.colorModeForRenderPass();\n\n const pattern = layer.paint.get('fill-pattern');\n const pass = painter.opaquePassEnabledForLayer() &&\n (!pattern.constantOr((1: any)) &&\n color.constantOr(Color.transparent).a === 1 &&\n opacity.constantOr(0) === 1) ? 'opaque' : 'translucent';\n\n // Draw fill\n if (painter.renderPass === pass) {\n const depthMode = painter.depthModeForSublayer(\n 1, painter.renderPass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly);\n drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, false);\n }\n\n // Draw stroke\n if (painter.renderPass === 'translucent' && layer.paint.get('fill-antialias')) {\n\n // If we defined a different color for the fill outline, we are\n // going to ignore the bits in 0x07 and just care about the global\n // clipping mask.\n // Otherwise, we only want to drawFill the antialiased parts that are\n // *outside* the current shape. This is important in case the fill\n // or stroke color is translucent. If we wouldn't clip to outside\n // the current shape, some pixels from the outline stroke overlapped\n // the (non-antialiased) fill.\n const depthMode = painter.depthModeForSublayer(\n layer.getPaintProperty('fill-outline-color') ? 2 : 0, DepthMode.ReadOnly);\n drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, true);\n }\n}\n\nfunction drawFillTiles(painter, sourceCache, layer, coords, depthMode, colorMode, isOutline) {\n const gl = painter.context.gl;\n\n const patternProperty = layer.paint.get('fill-pattern');\n const image = patternProperty && patternProperty.constantOr((1: any));\n const crossfade = layer.getCrossfadeParameters();\n let drawMode, programName, uniformValues, indexBuffer, segments;\n\n if (!isOutline) {\n programName = image ? 'fillPattern' : 'fill';\n drawMode = gl.TRIANGLES;\n } else {\n programName = image && !layer.getPaintProperty('fill-outline-color') ? 'fillOutlinePattern' : 'fillOutline';\n drawMode = gl.LINES;\n }\n\n for (const coord of coords) {\n const tile = sourceCache.getTile(coord);\n if (image && !tile.patternsLoaded()) continue;\n\n const bucket: ?FillBucket = (tile.getBucket(layer): any);\n if (!bucket) continue;\n\n const programConfiguration = bucket.programConfigurations.get(layer.id);\n const program = painter.useProgram(programName, programConfiguration);\n\n if (image) {\n painter.context.activeTexture.set(gl.TEXTURE0);\n tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n programConfiguration.updatePaintBuffers(crossfade);\n }\n\n const constantPattern = patternProperty.constantOr(null);\n if (constantPattern && tile.imageAtlas) {\n const atlas = tile.imageAtlas;\n const posTo = atlas.patternPositions[constantPattern.to.toString()];\n const posFrom = atlas.patternPositions[constantPattern.from.toString()];\n if (posTo && posFrom) programConfiguration.setConstantPatternPositions(posTo, posFrom);\n }\n\n const tileMatrix = painter.translatePosMatrix(coord.posMatrix, tile,\n layer.paint.get('fill-translate'), layer.paint.get('fill-translate-anchor'));\n\n if (!isOutline) {\n indexBuffer = bucket.indexBuffer;\n segments = bucket.segments;\n uniformValues = image ?\n fillPatternUniformValues(tileMatrix, painter, crossfade, tile) :\n fillUniformValues(tileMatrix);\n } else {\n indexBuffer = bucket.indexBuffer2;\n segments = bucket.segments2;\n const drawingBufferSize = [gl.drawingBufferWidth, gl.drawingBufferHeight];\n uniformValues = (programName === 'fillOutlinePattern' && image) ?\n fillOutlinePatternUniformValues(tileMatrix, painter, crossfade, tile, drawingBufferSize) :\n fillOutlineUniformValues(tileMatrix, drawingBufferSize);\n }\n\n program.draw(painter.context, drawMode, depthMode,\n painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues,\n layer.id, bucket.layoutVertexBuffer, indexBuffer, segments,\n layer.paint, painter.transform.zoom, programConfiguration);\n }\n}\n","// @flow\n\nimport DepthMode from '../gl/depth_mode';\nimport StencilMode from '../gl/stencil_mode';\nimport ColorMode from '../gl/color_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport {\n fillExtrusionUniformValues,\n fillExtrusionPatternUniformValues,\n} from './program/fill_extrusion_program';\n\nimport type Painter from './painter';\nimport type SourceCache from '../source/source_cache';\nimport type FillExtrusionStyleLayer from '../style/style_layer/fill_extrusion_style_layer';\nimport type FillExtrusionBucket from '../data/bucket/fill_extrusion_bucket';\nimport type {OverscaledTileID} from '../source/tile_id';\n\nexport default draw;\n\nfunction draw(painter: Painter, source: SourceCache, layer: FillExtrusionStyleLayer, coords: Array) {\n const opacity = layer.paint.get('fill-extrusion-opacity');\n if (opacity === 0) {\n return;\n }\n\n if (painter.renderPass === 'translucent') {\n const depthMode = new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);\n\n if (opacity === 1 && !layer.paint.get('fill-extrusion-pattern').constantOr((1: any))) {\n const colorMode = painter.colorModeForRenderPass();\n drawExtrusionTiles(painter, source, layer, coords, depthMode, StencilMode.disabled, colorMode);\n\n } else {\n // Draw transparent buildings in two passes so that only the closest surface is drawn.\n // First draw all the extrusions into only the depth buffer. No colors are drawn.\n drawExtrusionTiles(painter, source, layer, coords, depthMode,\n StencilMode.disabled,\n ColorMode.disabled);\n\n // Then draw all the extrusions a second type, only coloring fragments if they have the\n // same depth value as the closest fragment in the previous pass. Use the stencil buffer\n // to prevent the second draw in cases where we have coincident polygons.\n drawExtrusionTiles(painter, source, layer, coords, depthMode,\n painter.stencilModeFor3D(),\n painter.colorModeForRenderPass());\n }\n }\n}\n\nfunction drawExtrusionTiles(painter, source, layer, coords, depthMode, stencilMode, colorMode) {\n const context = painter.context;\n const gl = context.gl;\n const patternProperty = layer.paint.get('fill-extrusion-pattern');\n const image = patternProperty.constantOr((1: any));\n const crossfade = layer.getCrossfadeParameters();\n const opacity = layer.paint.get('fill-extrusion-opacity');\n\n for (const coord of coords) {\n const tile = source.getTile(coord);\n const bucket: ?FillExtrusionBucket = (tile.getBucket(layer): any);\n if (!bucket) continue;\n\n const programConfiguration = bucket.programConfigurations.get(layer.id);\n const program = painter.useProgram(image ? 'fillExtrusionPattern' : 'fillExtrusion', programConfiguration);\n\n if (image) {\n painter.context.activeTexture.set(gl.TEXTURE0);\n tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n programConfiguration.updatePaintBuffers(crossfade);\n }\n const constantPattern = patternProperty.constantOr(null);\n if (constantPattern && tile.imageAtlas) {\n const atlas = tile.imageAtlas;\n const posTo = atlas.patternPositions[constantPattern.to.toString()];\n const posFrom = atlas.patternPositions[constantPattern.from.toString()];\n if (posTo && posFrom) programConfiguration.setConstantPatternPositions(posTo, posFrom);\n }\n\n const matrix = painter.translatePosMatrix(\n coord.posMatrix,\n tile,\n layer.paint.get('fill-extrusion-translate'),\n layer.paint.get('fill-extrusion-translate-anchor'));\n\n const shouldUseVerticalGradient = layer.paint.get('fill-extrusion-vertical-gradient');\n const uniformValues = image ?\n fillExtrusionPatternUniformValues(matrix, painter, shouldUseVerticalGradient, opacity, coord, crossfade, tile) :\n fillExtrusionUniformValues(matrix, painter, shouldUseVerticalGradient, opacity);\n\n program.draw(context, context.gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW,\n uniformValues, layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer,\n bucket.segments, layer.paint, painter.transform.zoom,\n programConfiguration);\n }\n}\n","// @flow\n\nimport Texture from './texture';\nimport StencilMode from '../gl/stencil_mode';\nimport DepthMode from '../gl/depth_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport {\n hillshadeUniformValues,\n hillshadeUniformPrepareValues\n} from './program/hillshade_program';\n\nimport type Painter from './painter';\nimport type SourceCache from '../source/source_cache';\nimport type HillshadeStyleLayer from '../style/style_layer/hillshade_style_layer';\nimport type {OverscaledTileID} from '../source/tile_id';\n\nexport default drawHillshade;\n\nfunction drawHillshade(painter: Painter, sourceCache: SourceCache, layer: HillshadeStyleLayer, tileIDs: Array) {\n if (painter.renderPass !== 'offscreen' && painter.renderPass !== 'translucent') return;\n\n const context = painter.context;\n\n const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);\n const colorMode = painter.colorModeForRenderPass();\n\n const [stencilModes, coords] = painter.renderPass === 'translucent' ?\n painter.stencilConfigForOverlap(tileIDs) : [{}, tileIDs];\n\n for (const coord of coords) {\n const tile = sourceCache.getTile(coord);\n if (tile.needsHillshadePrepare && painter.renderPass === 'offscreen') {\n prepareHillshade(painter, tile, layer, depthMode, StencilMode.disabled, colorMode);\n } else if (painter.renderPass === 'translucent') {\n renderHillshade(painter, tile, layer, depthMode, stencilModes[coord.overscaledZ], colorMode);\n }\n }\n\n context.viewport.set([0, 0, painter.width, painter.height]);\n}\n\nfunction renderHillshade(painter, tile, layer, depthMode, stencilMode, colorMode) {\n const context = painter.context;\n const gl = context.gl;\n const fbo = tile.fbo;\n if (!fbo) return;\n\n const program = painter.useProgram('hillshade');\n\n context.activeTexture.set(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());\n\n const uniformValues = hillshadeUniformValues(painter, tile, layer);\n\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, layer.id, painter.rasterBoundsBuffer,\n painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);\n}\n\n// hillshade rendering is done in two steps. the prepare step first calculates the slope of the terrain in the x and y\n// directions for each pixel, and saves those values to a framebuffer texture in the r and g channels.\nfunction prepareHillshade(painter, tile, layer, depthMode, stencilMode, colorMode) {\n const context = painter.context;\n const gl = context.gl;\n const dem = tile.dem;\n if (dem && dem.data) {\n const tileSize = dem.dim;\n const textureStride = dem.stride;\n\n const pixelData = dem.getPixels();\n context.activeTexture.set(gl.TEXTURE1);\n\n context.pixelStoreUnpackPremultiplyAlpha.set(false);\n tile.demTexture = tile.demTexture || painter.getTileTexture(textureStride);\n if (tile.demTexture) {\n const demTexture = tile.demTexture;\n demTexture.update(pixelData, {premultiply: false});\n demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);\n } else {\n tile.demTexture = new Texture(context, pixelData, gl.RGBA, {premultiply: false});\n tile.demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);\n }\n\n context.activeTexture.set(gl.TEXTURE0);\n\n let fbo = tile.fbo;\n\n if (!fbo) {\n const renderTexture = new Texture(context, {width: tileSize, height: tileSize, data: null}, gl.RGBA);\n renderTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n\n fbo = tile.fbo = context.createFramebuffer(tileSize, tileSize, true);\n fbo.colorAttachment.set(renderTexture.texture);\n }\n\n context.bindFramebuffer.set(fbo.framebuffer);\n context.viewport.set([0, 0, tileSize, tileSize]);\n\n painter.useProgram('hillshadePrepare').draw(context, gl.TRIANGLES,\n depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n hillshadeUniformPrepareValues(tile.tileID, dem),\n layer.id, painter.rasterBoundsBuffer,\n painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);\n\n tile.needsHillshadePrepare = false;\n }\n}\n","// @flow\n\nimport {clamp} from '../util/util';\n\nimport ImageSource from '../source/image_source';\nimport browser from '../util/browser';\nimport StencilMode from '../gl/stencil_mode';\nimport DepthMode from '../gl/depth_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport {rasterUniformValues} from './program/raster_program';\n\nimport type Painter from './painter';\nimport type SourceCache from '../source/source_cache';\nimport type RasterStyleLayer from '../style/style_layer/raster_style_layer';\nimport type {OverscaledTileID} from '../source/tile_id';\n\nexport default drawRaster;\n\nfunction drawRaster(painter: Painter, sourceCache: SourceCache, layer: RasterStyleLayer, tileIDs: Array) {\n if (painter.renderPass !== 'translucent') return;\n if (layer.paint.get('raster-opacity') === 0) return;\n if (!tileIDs.length) return;\n\n const context = painter.context;\n const gl = context.gl;\n const source = sourceCache.getSource();\n const program = painter.useProgram('raster');\n\n const colorMode = painter.colorModeForRenderPass();\n\n const [stencilModes, coords] = source instanceof ImageSource ? [{}, tileIDs] :\n painter.stencilConfigForOverlap(tileIDs);\n\n const minTileZ = coords[coords.length - 1].overscaledZ;\n\n const align = !painter.options.moving;\n for (const coord of coords) {\n // Set the lower zoom level to sublayer 0, and higher zoom levels to higher sublayers\n // Use gl.LESS to prevent double drawing in areas where tiles overlap.\n const depthMode = painter.depthModeForSublayer(coord.overscaledZ - minTileZ,\n layer.paint.get('raster-opacity') === 1 ? DepthMode.ReadWrite : DepthMode.ReadOnly, gl.LESS);\n\n const tile = sourceCache.getTile(coord);\n const posMatrix = painter.transform.calculatePosMatrix(coord.toUnwrapped(), align);\n\n tile.registerFadeDuration(layer.paint.get('raster-fade-duration'));\n\n const parentTile = sourceCache.findLoadedParent(coord, 0),\n fade = getFadeValues(tile, parentTile, sourceCache, layer, painter.transform);\n\n let parentScaleBy, parentTL;\n\n const textureFilter = layer.paint.get('raster-resampling') === 'nearest' ? gl.NEAREST : gl.LINEAR;\n\n context.activeTexture.set(gl.TEXTURE0);\n tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);\n\n context.activeTexture.set(gl.TEXTURE1);\n\n if (parentTile) {\n parentTile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);\n parentScaleBy = Math.pow(2, parentTile.tileID.overscaledZ - tile.tileID.overscaledZ);\n parentTL = [tile.tileID.canonical.x * parentScaleBy % 1, tile.tileID.canonical.y * parentScaleBy % 1];\n\n } else {\n tile.texture.bind(textureFilter, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);\n }\n\n const uniformValues = rasterUniformValues(posMatrix, parentTL || [0, 0], parentScaleBy || 1, fade, layer);\n\n if (source instanceof ImageSource) {\n program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, colorMode, CullFaceMode.disabled,\n uniformValues, layer.id, source.boundsBuffer,\n painter.quadTriangleIndexBuffer, source.boundsSegments);\n } else {\n program.draw(context, gl.TRIANGLES, depthMode, stencilModes[coord.overscaledZ], colorMode, CullFaceMode.disabled,\n uniformValues, layer.id, painter.rasterBoundsBuffer,\n painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);\n }\n }\n}\n\nfunction getFadeValues(tile, parentTile, sourceCache, layer, transform) {\n const fadeDuration = layer.paint.get('raster-fade-duration');\n\n if (fadeDuration > 0) {\n const now = browser.now();\n const sinceTile = (now - tile.timeAdded) / fadeDuration;\n const sinceParent = parentTile ? (now - parentTile.timeAdded) / fadeDuration : -1;\n\n const source = sourceCache.getSource();\n const idealZ = transform.coveringZoomLevel({\n tileSize: source.tileSize,\n roundZoom: source.roundZoom\n });\n\n // if no parent or parent is older, fade in; if parent is younger, fade out\n const fadeIn = !parentTile || Math.abs(parentTile.tileID.overscaledZ - idealZ) > Math.abs(tile.tileID.overscaledZ - idealZ);\n\n const childOpacity = (fadeIn && tile.refreshedUponExpiration) ? 1 : clamp(fadeIn ? sinceTile : 1 - sinceParent, 0, 1);\n\n // we don't crossfade tiles that were just refreshed upon expiring:\n // once they're old enough to pass the crossfading threshold\n // (fadeDuration), unset the `refreshedUponExpiration` flag so we don't\n // incorrectly fail to crossfade them when zooming\n if (tile.refreshedUponExpiration && sinceTile >= 1) tile.refreshedUponExpiration = false;\n\n if (parentTile) {\n return {\n opacity: 1,\n mix: 1 - childOpacity\n };\n } else {\n return {\n opacity: childOpacity,\n mix: 0\n };\n }\n } else {\n return {\n opacity: 1,\n mix: 0\n };\n }\n}\n","// @flow\n\nimport DepthMode from '../gl/depth_mode';\nimport StencilMode from '../gl/stencil_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport {debugUniformValues} from './program/debug_program';\nimport Color from '../style-spec/util/color';\nimport ColorMode from '../gl/color_mode';\nimport browser from '../util/browser';\n\nimport type Painter from './painter';\nimport type SourceCache from '../source/source_cache';\nimport type {OverscaledTileID} from '../source/tile_id';\n\nexport default drawDebug;\n\nconst topColor = new Color(1, 0, 0, 1);\nconst btmColor = new Color(0, 1, 0, 1);\nconst leftColor = new Color(0, 0, 1, 1);\nconst rightColor = new Color(1, 0, 1, 1);\nconst centerColor = new Color(0, 1, 1, 1);\n\nexport function drawDebugPadding(painter: Painter) {\n const padding = painter.transform.padding;\n const lineWidth = 3;\n // Top\n drawHorizontalLine(painter, painter.transform.height - (padding.top || 0), lineWidth, topColor);\n // Bottom\n drawHorizontalLine(painter, padding.bottom || 0, lineWidth, btmColor);\n // Left\n drawVerticalLine(painter, padding.left || 0, lineWidth, leftColor);\n // Right\n drawVerticalLine(painter, painter.transform.width - (padding.right || 0), lineWidth, rightColor);\n // Center\n const center = painter.transform.centerPoint;\n drawCrosshair(painter, center.x, painter.transform.height - center.y, centerColor);\n}\n\nfunction drawCrosshair(painter: Painter, x: number, y: number, color: Color) {\n const size = 20;\n const lineWidth = 2;\n //Vertical line\n drawDebugSSRect(painter, x - lineWidth / 2, y - size / 2, lineWidth, size, color);\n //Horizontal line\n drawDebugSSRect(painter, x - size / 2, y - lineWidth / 2, size, lineWidth, color);\n}\n\nfunction drawHorizontalLine(painter: Painter, y: number, lineWidth: number, color: Color) {\n drawDebugSSRect(painter, 0, y + lineWidth / 2, painter.transform.width, lineWidth, color);\n}\n\nfunction drawVerticalLine(painter: Painter, x: number, lineWidth: number, color: Color) {\n drawDebugSSRect(painter, x - lineWidth / 2, 0, lineWidth, painter.transform.height, color);\n}\n\nfunction drawDebugSSRect(painter: Painter, x: number, y: number, width: number, height: number, color: Color) {\n const context = painter.context;\n const gl = context.gl;\n\n gl.enable(gl.SCISSOR_TEST);\n gl.scissor(x * browser.devicePixelRatio, y * browser.devicePixelRatio, width * browser.devicePixelRatio, height * browser.devicePixelRatio);\n context.clear({color});\n gl.disable(gl.SCISSOR_TEST);\n}\n\nfunction drawDebug(painter: Painter, sourceCache: SourceCache, coords: Array) {\n for (let i = 0; i < coords.length; i++) {\n drawDebugTile(painter, sourceCache, coords[i]);\n }\n}\n\nfunction drawDebugTile(painter, sourceCache, coord: OverscaledTileID) {\n const context = painter.context;\n const gl = context.gl;\n\n const posMatrix = coord.posMatrix;\n const program = painter.useProgram('debug');\n\n const depthMode = DepthMode.disabled;\n const stencilMode = StencilMode.disabled;\n const colorMode = painter.colorModeForRenderPass();\n const id = '$debug';\n\n context.activeTexture.set(gl.TEXTURE0);\n // Bind the empty texture for drawing outlines\n painter.emptyTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n\n program.draw(context, gl.LINE_STRIP, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n debugUniformValues(posMatrix, Color.red), id,\n painter.debugBuffer, painter.tileBorderIndexBuffer, painter.debugSegments);\n\n const tileRawData = sourceCache.getTileByID(coord.key).latestRawTileData;\n const tileByteLength = (tileRawData && tileRawData.byteLength) || 0;\n const tileSizeKb = Math.floor(tileByteLength / 1024);\n const tileSize = sourceCache.getTile(coord).tileSize;\n const scaleRatio = (512 / Math.min(tileSize, 512) * (coord.overscaledZ / painter.transform.zoom)) * 0.5;\n let tileIdText = coord.canonical.toString();\n if (coord.overscaledZ !== coord.canonical.z) {\n tileIdText += ` => ${coord.overscaledZ}`;\n }\n const tileLabel = `${tileIdText} ${tileSizeKb}kb`;\n drawTextToOverlay(painter, tileLabel);\n\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, ColorMode.alphaBlended, CullFaceMode.disabled,\n debugUniformValues(posMatrix, Color.transparent, scaleRatio), id,\n painter.debugBuffer, painter.quadTriangleIndexBuffer, painter.debugSegments);\n}\n\nfunction drawTextToOverlay(painter: Painter, text: string) {\n painter.initDebugOverlayCanvas();\n const canvas = painter.debugOverlayCanvas;\n const gl = painter.context.gl;\n const ctx2d = painter.debugOverlayCanvas.getContext('2d');\n ctx2d.clearRect(0, 0, canvas.width, canvas.height);\n\n ctx2d.shadowColor = 'white';\n ctx2d.shadowBlur = 2;\n ctx2d.lineWidth = 1.5;\n ctx2d.strokeStyle = 'white';\n ctx2d.textBaseline = 'top';\n ctx2d.font = `bold ${36}px Open Sans, sans-serif`;\n ctx2d.fillText(text, 5, 5);\n ctx2d.strokeText(text, 5, 5);\n\n painter.debugOverlayTexture.update(canvas);\n painter.debugOverlayTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n}\n","// @flow\n\nimport browser from '../util/browser';\nimport window from '../util/window';\n\nimport {mat4} from 'gl-matrix';\nimport SourceCache from '../source/source_cache';\nimport EXTENT from '../data/extent';\nimport pixelsToTileUnits from '../source/pixels_to_tile_units';\nimport SegmentVector from '../data/segment';\nimport {RasterBoundsArray, PosArray, TriangleIndexArray, LineStripIndexArray} from '../data/array_types';\nimport {values} from '../util/util';\nimport rasterBoundsAttributes from '../data/raster_bounds_attributes';\nimport posAttributes from '../data/pos_attributes';\nimport ProgramConfiguration from '../data/program_configuration';\nimport CrossTileSymbolIndex from '../symbol/cross_tile_symbol_index';\nimport * as shaders from '../shaders';\nimport Program from './program';\nimport {programUniforms} from './program/program_uniforms';\nimport Context from '../gl/context';\nimport DepthMode from '../gl/depth_mode';\nimport StencilMode from '../gl/stencil_mode';\nimport ColorMode from '../gl/color_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport Texture from './texture';\nimport {clippingMaskUniformValues} from './program/clipping_mask_program';\nimport Color from '../style-spec/util/color';\nimport symbol from './draw_symbol';\nimport circle from './draw_circle';\nimport heatmap from './draw_heatmap';\nimport line from './draw_line';\nimport fill from './draw_fill';\nimport fillExtrusion from './draw_fill_extrusion';\nimport hillshade from './draw_hillshade';\nimport raster from './draw_raster';\nimport background from './draw_background';\nimport debug, {drawDebugPadding} from './draw_debug';\nimport custom from './draw_custom';\n\nconst draw = {\n symbol,\n circle,\n heatmap,\n line,\n fill,\n 'fill-extrusion': fillExtrusion,\n hillshade,\n raster,\n background,\n debug,\n custom\n};\n\nimport type Transform from '../geo/transform';\nimport type Tile from '../source/tile';\nimport type {OverscaledTileID} from '../source/tile_id';\nimport type Style from '../style/style';\nimport type StyleLayer from '../style/style_layer';\nimport type {CrossFaded} from '../style/properties';\nimport type LineAtlas from './line_atlas';\nimport type ImageManager from './image_manager';\nimport type GlyphManager from './glyph_manager';\nimport type VertexBuffer from '../gl/vertex_buffer';\nimport type IndexBuffer from '../gl/index_buffer';\nimport type {DepthRangeType, DepthMaskType, DepthFuncType} from '../gl/types';\nimport type ResolvedImage from '../style-spec/expression/types/resolved_image';\n\nexport type RenderPass = 'offscreen' | 'opaque' | 'translucent';\n\ntype PainterOptions = {\n showOverdrawInspector: boolean,\n showTileBoundaries: boolean,\n showPadding: boolean,\n rotating: boolean,\n zooming: boolean,\n moving: boolean,\n gpuTiming: boolean,\n fadeDuration: number\n}\n\n/**\n * Initialize a new painter object.\n *\n * @param {Canvas} gl an experimental-webgl drawing context\n * @private\n */\nclass Painter {\n context: Context;\n transform: Transform;\n _tileTextures: {[_: number]: Array };\n numSublayers: number;\n depthEpsilon: number;\n emptyProgramConfiguration: ProgramConfiguration;\n width: number;\n height: number;\n tileExtentBuffer: VertexBuffer;\n tileExtentSegments: SegmentVector;\n debugBuffer: VertexBuffer;\n debugSegments: SegmentVector;\n rasterBoundsBuffer: VertexBuffer;\n rasterBoundsSegments: SegmentVector;\n viewportBuffer: VertexBuffer;\n viewportSegments: SegmentVector;\n quadTriangleIndexBuffer: IndexBuffer;\n tileBorderIndexBuffer: IndexBuffer;\n _tileClippingMaskIDs: {[_: string]: number };\n stencilClearMode: StencilMode;\n style: Style;\n options: PainterOptions;\n lineAtlas: LineAtlas;\n imageManager: ImageManager;\n glyphManager: GlyphManager;\n depthRangeFor3D: DepthRangeType;\n opaquePassCutoff: number;\n renderPass: RenderPass;\n currentLayer: number;\n currentStencilSource: ?string;\n nextStencilID: number;\n id: string;\n _showOverdrawInspector: boolean;\n cache: {[_: string]: Program<*> };\n crossTileSymbolIndex: CrossTileSymbolIndex;\n symbolFadeChange: number;\n gpuTimers: {[_: string]: any };\n emptyTexture: Texture;\n debugOverlayTexture: Texture;\n debugOverlayCanvas: HTMLCanvasElement;\n\n constructor(gl: WebGLRenderingContext, transform: Transform) {\n this.context = new Context(gl);\n this.transform = transform;\n this._tileTextures = {};\n\n this.setup();\n\n // Within each layer there are multiple distinct z-planes that can be drawn to.\n // This is implemented using the WebGL depth buffer.\n this.numSublayers = SourceCache.maxUnderzooming + SourceCache.maxOverzooming + 1;\n this.depthEpsilon = 1 / Math.pow(2, 16);\n\n this.crossTileSymbolIndex = new CrossTileSymbolIndex();\n\n this.gpuTimers = {};\n }\n\n /*\n * Update the GL viewport, projection matrix, and transforms to compensate\n * for a new width and height value.\n */\n resize(width: number, height: number) {\n this.width = width * browser.devicePixelRatio;\n this.height = height * browser.devicePixelRatio;\n this.context.viewport.set([0, 0, this.width, this.height]);\n\n if (this.style) {\n for (const layerId of this.style._order) {\n this.style._layers[layerId].resize();\n }\n }\n }\n\n setup() {\n const context = this.context;\n\n const tileExtentArray = new PosArray();\n tileExtentArray.emplaceBack(0, 0);\n tileExtentArray.emplaceBack(EXTENT, 0);\n tileExtentArray.emplaceBack(0, EXTENT);\n tileExtentArray.emplaceBack(EXTENT, EXTENT);\n this.tileExtentBuffer = context.createVertexBuffer(tileExtentArray, posAttributes.members);\n this.tileExtentSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n\n const debugArray = new PosArray();\n debugArray.emplaceBack(0, 0);\n debugArray.emplaceBack(EXTENT, 0);\n debugArray.emplaceBack(0, EXTENT);\n debugArray.emplaceBack(EXTENT, EXTENT);\n this.debugBuffer = context.createVertexBuffer(debugArray, posAttributes.members);\n this.debugSegments = SegmentVector.simpleSegment(0, 0, 4, 5);\n\n const rasterBoundsArray = new RasterBoundsArray();\n rasterBoundsArray.emplaceBack(0, 0, 0, 0);\n rasterBoundsArray.emplaceBack(EXTENT, 0, EXTENT, 0);\n rasterBoundsArray.emplaceBack(0, EXTENT, 0, EXTENT);\n rasterBoundsArray.emplaceBack(EXTENT, EXTENT, EXTENT, EXTENT);\n this.rasterBoundsBuffer = context.createVertexBuffer(rasterBoundsArray, rasterBoundsAttributes.members);\n this.rasterBoundsSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n\n const viewportArray = new PosArray();\n viewportArray.emplaceBack(0, 0);\n viewportArray.emplaceBack(1, 0);\n viewportArray.emplaceBack(0, 1);\n viewportArray.emplaceBack(1, 1);\n this.viewportBuffer = context.createVertexBuffer(viewportArray, posAttributes.members);\n this.viewportSegments = SegmentVector.simpleSegment(0, 0, 4, 2);\n\n const tileLineStripIndices = new LineStripIndexArray();\n tileLineStripIndices.emplaceBack(0);\n tileLineStripIndices.emplaceBack(1);\n tileLineStripIndices.emplaceBack(3);\n tileLineStripIndices.emplaceBack(2);\n tileLineStripIndices.emplaceBack(0);\n this.tileBorderIndexBuffer = context.createIndexBuffer(tileLineStripIndices);\n\n const quadTriangleIndices = new TriangleIndexArray();\n quadTriangleIndices.emplaceBack(0, 1, 2);\n quadTriangleIndices.emplaceBack(2, 1, 3);\n this.quadTriangleIndexBuffer = context.createIndexBuffer(quadTriangleIndices);\n\n this.emptyTexture = new Texture(context, {\n width: 1,\n height: 1,\n data: new Uint8Array([0, 0, 0, 0])\n }, context.gl.RGBA);\n\n const gl = this.context.gl;\n this.stencilClearMode = new StencilMode({func: gl.ALWAYS, mask: 0}, 0x0, 0xFF, gl.ZERO, gl.ZERO, gl.ZERO);\n }\n\n /*\n * Reset the drawing canvas by clearing the stencil buffer so that we can draw\n * new tiles at the same location, while retaining previously drawn pixels.\n */\n clearStencil() {\n const context = this.context;\n const gl = context.gl;\n\n this.nextStencilID = 1;\n this.currentStencilSource = undefined;\n\n // As a temporary workaround for https://github.com/mapbox/mapbox-gl-js/issues/5490,\n // pending an upstream fix, we draw a fullscreen stencil=0 clipping mask here,\n // effectively clearing the stencil buffer: once an upstream patch lands, remove\n // this function in favor of context.clear({ stencil: 0x0 })\n\n const matrix = mat4.create();\n mat4.ortho(matrix, 0, this.width, this.height, 0, 0, 1);\n mat4.scale(matrix, matrix, [gl.drawingBufferWidth, gl.drawingBufferHeight, 0]);\n\n this.useProgram('clippingMask').draw(context, gl.TRIANGLES,\n DepthMode.disabled, this.stencilClearMode, ColorMode.disabled, CullFaceMode.disabled,\n clippingMaskUniformValues(matrix),\n '$clipping', this.viewportBuffer,\n this.quadTriangleIndexBuffer, this.viewportSegments);\n }\n\n _renderTileClippingMasks(layer: StyleLayer, tileIDs: Array) {\n if (this.currentStencilSource === layer.source || !layer.isTileClipped() || !tileIDs || !tileIDs.length) return;\n\n this.currentStencilSource = layer.source;\n\n const context = this.context;\n const gl = context.gl;\n\n if (this.nextStencilID + tileIDs.length > 256) {\n // we'll run out of fresh IDs so we need to clear and start from scratch\n this.clearStencil();\n }\n\n context.setColorMode(ColorMode.disabled);\n context.setDepthMode(DepthMode.disabled);\n\n const program = this.useProgram('clippingMask');\n\n this._tileClippingMaskIDs = {};\n\n for (const tileID of tileIDs) {\n const id = this._tileClippingMaskIDs[tileID.key] = this.nextStencilID++;\n\n program.draw(context, gl.TRIANGLES, DepthMode.disabled,\n // Tests will always pass, and ref value will be written to stencil buffer.\n new StencilMode({func: gl.ALWAYS, mask: 0}, id, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE),\n ColorMode.disabled, CullFaceMode.disabled, clippingMaskUniformValues(tileID.posMatrix),\n '$clipping', this.tileExtentBuffer,\n this.quadTriangleIndexBuffer, this.tileExtentSegments);\n }\n }\n\n stencilModeFor3D(): StencilMode {\n this.currentStencilSource = undefined;\n\n if (this.nextStencilID + 1 > 256) {\n this.clearStencil();\n }\n\n const id = this.nextStencilID++;\n const gl = this.context.gl;\n return new StencilMode({func: gl.NOTEQUAL, mask: 0xFF}, id, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE);\n }\n\n stencilModeForClipping(tileID: OverscaledTileID): StencilMode {\n const gl = this.context.gl;\n return new StencilMode({func: gl.EQUAL, mask: 0xFF}, this._tileClippingMaskIDs[tileID.key], 0x00, gl.KEEP, gl.KEEP, gl.REPLACE);\n }\n\n /*\n * Sort coordinates by Z as drawing tiles is done in Z-descending order.\n * All children with the same Z write the same stencil value. Children\n * stencil values are greater than parent's. This is used only for raster\n * and raster-dem tiles, which are already clipped to tile boundaries, to\n * mask area of tile overlapped by children tiles.\n * Stencil ref values continue range used in _tileClippingMaskIDs.\n *\n * Returns [StencilMode for tile overscaleZ map, sortedCoords].\n */\n stencilConfigForOverlap(tileIDs: Array): [{[_: number]: $ReadOnly}, Array] {\n const gl = this.context.gl;\n const coords = tileIDs.sort((a, b) => b.overscaledZ - a.overscaledZ);\n const minTileZ = coords[coords.length - 1].overscaledZ;\n const stencilValues = coords[0].overscaledZ - minTileZ + 1;\n if (stencilValues > 1) {\n this.currentStencilSource = undefined;\n if (this.nextStencilID + stencilValues > 256) {\n this.clearStencil();\n }\n const zToStencilMode = {};\n for (let i = 0; i < stencilValues; i++) {\n zToStencilMode[i + minTileZ] = new StencilMode({func: gl.GEQUAL, mask: 0xFF}, i + this.nextStencilID, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE);\n }\n this.nextStencilID += stencilValues;\n return [zToStencilMode, coords];\n }\n return [{[minTileZ]: StencilMode.disabled}, coords];\n }\n\n colorModeForRenderPass(): $ReadOnly {\n const gl = this.context.gl;\n if (this._showOverdrawInspector) {\n const numOverdrawSteps = 8;\n const a = 1 / numOverdrawSteps;\n\n return new ColorMode([gl.CONSTANT_COLOR, gl.ONE], new Color(a, a, a, 0), [true, true, true, true]);\n } else if (this.renderPass === 'opaque') {\n return ColorMode.unblended;\n } else {\n return ColorMode.alphaBlended;\n }\n }\n\n depthModeForSublayer(n: number, mask: DepthMaskType, func: ?DepthFuncType): $ReadOnly {\n if (!this.opaquePassEnabledForLayer()) return DepthMode.disabled;\n const depth = 1 - ((1 + this.currentLayer) * this.numSublayers + n) * this.depthEpsilon;\n return new DepthMode(func || this.context.gl.LEQUAL, mask, [depth, depth]);\n }\n\n /*\n * The opaque pass and 3D layers both use the depth buffer.\n * Layers drawn above 3D layers need to be drawn using the\n * painter's algorithm so that they appear above 3D features.\n * This returns true for layers that can be drawn using the\n * opaque pass.\n */\n opaquePassEnabledForLayer() {\n return this.currentLayer < this.opaquePassCutoff;\n }\n\n render(style: Style, options: PainterOptions) {\n this.style = style;\n this.options = options;\n\n this.lineAtlas = style.lineAtlas;\n this.imageManager = style.imageManager;\n this.glyphManager = style.glyphManager;\n\n this.symbolFadeChange = style.placement.symbolFadeChange(browser.now());\n\n this.imageManager.beginFrame();\n\n const layerIds = this.style._order;\n const sourceCaches = this.style.sourceCaches;\n\n for (const id in sourceCaches) {\n const sourceCache = sourceCaches[id];\n if (sourceCache.used) {\n sourceCache.prepare(this.context);\n }\n }\n\n const coordsAscending: {[_: string]: Array} = {};\n const coordsDescending: {[_: string]: Array} = {};\n const coordsDescendingSymbol: {[_: string]: Array} = {};\n\n for (const id in sourceCaches) {\n const sourceCache = sourceCaches[id];\n coordsAscending[id] = sourceCache.getVisibleCoordinates();\n coordsDescending[id] = coordsAscending[id].slice().reverse();\n coordsDescendingSymbol[id] = sourceCache.getVisibleCoordinates(true).reverse();\n }\n\n this.opaquePassCutoff = Infinity;\n for (let i = 0; i < layerIds.length; i++) {\n const layerId = layerIds[i];\n if (this.style._layers[layerId].is3D()) {\n this.opaquePassCutoff = i;\n break;\n }\n }\n\n // Offscreen pass ===============================================\n // We first do all rendering that requires rendering to a separate\n // framebuffer, and then save those for rendering back to the map\n // later: in doing this we avoid doing expensive framebuffer restores.\n this.renderPass = 'offscreen';\n\n for (const layerId of layerIds) {\n const layer = this.style._layers[layerId];\n if (!layer.hasOffscreenPass() || layer.isHidden(this.transform.zoom)) continue;\n\n const coords = coordsDescending[layer.source];\n if (layer.type !== 'custom' && !coords.length) continue;\n\n this.renderLayer(this, sourceCaches[layer.source], layer, coords);\n }\n\n // Rebind the main framebuffer now that all offscreen layers have been rendered:\n this.context.bindFramebuffer.set(null);\n\n // Clear buffers in preparation for drawing to the main framebuffer\n this.context.clear({color: options.showOverdrawInspector ? Color.black : Color.transparent, depth: 1});\n this.clearStencil();\n\n this._showOverdrawInspector = options.showOverdrawInspector;\n this.depthRangeFor3D = [0, 1 - ((style._order.length + 2) * this.numSublayers * this.depthEpsilon)];\n\n // Opaque pass ===============================================\n // Draw opaque layers top-to-bottom first.\n this.renderPass = 'opaque';\n\n for (this.currentLayer = layerIds.length - 1; this.currentLayer >= 0; this.currentLayer--) {\n const layer = this.style._layers[layerIds[this.currentLayer]];\n const sourceCache = sourceCaches[layer.source];\n const coords = coordsAscending[layer.source];\n\n this._renderTileClippingMasks(layer, coords);\n this.renderLayer(this, sourceCache, layer, coords);\n }\n\n // Translucent pass ===============================================\n // Draw all other layers bottom-to-top.\n this.renderPass = 'translucent';\n\n for (this.currentLayer = 0; this.currentLayer < layerIds.length; this.currentLayer++) {\n const layer = this.style._layers[layerIds[this.currentLayer]];\n const sourceCache = sourceCaches[layer.source];\n\n // For symbol layers in the translucent pass, we add extra tiles to the renderable set\n // for cross-tile symbol fading. Symbol layers don't use tile clipping, so no need to render\n // separate clipping masks\n const coords = (layer.type === 'symbol' ? coordsDescendingSymbol : coordsDescending)[layer.source];\n\n this._renderTileClippingMasks(layer, coordsAscending[layer.source]);\n this.renderLayer(this, sourceCache, layer, coords);\n }\n\n if (this.options.showTileBoundaries) {\n //Use source with highest maxzoom\n let selectedSource;\n let sourceCache;\n const layers = values(this.style._layers);\n layers.forEach((layer) => {\n if (layer.source && !layer.isHidden(this.transform.zoom)) {\n if (layer.source !== (sourceCache && sourceCache.id)) {\n sourceCache = this.style.sourceCaches[layer.source];\n }\n if (!selectedSource || (selectedSource.getSource().maxzoom < sourceCache.getSource().maxzoom)) {\n selectedSource = sourceCache;\n }\n }\n });\n if (selectedSource) {\n draw.debug(this, selectedSource, selectedSource.getVisibleCoordinates());\n }\n }\n\n if (this.options.showPadding) {\n drawDebugPadding(this);\n }\n\n // Set defaults for most GL values so that anyone using the state after the render\n // encounters more expected values.\n this.context.setDefault();\n }\n\n renderLayer(painter: Painter, sourceCache: SourceCache, layer: StyleLayer, coords: Array) {\n if (layer.isHidden(this.transform.zoom)) return;\n if (layer.type !== 'background' && layer.type !== 'custom' && !coords.length) return;\n this.id = layer.id;\n\n this.gpuTimingStart(layer);\n draw[layer.type](painter, sourceCache, layer, coords, this.style.placement.variableOffsets);\n this.gpuTimingEnd();\n }\n\n gpuTimingStart(layer: StyleLayer) {\n if (!this.options.gpuTiming) return;\n const ext = this.context.extTimerQuery;\n // This tries to time the draw call itself, but note that the cost for drawing a layer\n // may be dominated by the cost of uploading vertices to the GPU.\n // To instrument that, we'd need to pass the layerTimers object down into the bucket\n // uploading logic.\n let layerTimer = this.gpuTimers[layer.id];\n if (!layerTimer) {\n layerTimer = this.gpuTimers[layer.id] = {\n calls: 0,\n cpuTime: 0,\n query: ext.createQueryEXT()\n };\n }\n layerTimer.calls++;\n ext.beginQueryEXT(ext.TIME_ELAPSED_EXT, layerTimer.query);\n }\n\n gpuTimingEnd() {\n if (!this.options.gpuTiming) return;\n const ext = this.context.extTimerQuery;\n ext.endQueryEXT(ext.TIME_ELAPSED_EXT);\n }\n\n collectGpuTimers() {\n const currentLayerTimers = this.gpuTimers;\n this.gpuTimers = {};\n return currentLayerTimers;\n }\n\n queryGpuTimers(gpuTimers: {[_: string]: any}) {\n const layers = {};\n for (const layerId in gpuTimers) {\n const gpuTimer = gpuTimers[layerId];\n const ext = this.context.extTimerQuery;\n const gpuTime = ext.getQueryObjectEXT(gpuTimer.query, ext.QUERY_RESULT_EXT) / (1000 * 1000);\n ext.deleteQueryEXT(gpuTimer.query);\n layers[layerId] = gpuTime;\n }\n return layers;\n }\n\n /**\n * Transform a matrix to incorporate the *-translate and *-translate-anchor properties into it.\n * @param inViewportPixelUnitsUnits True when the units accepted by the matrix are in viewport pixels instead of tile units.\n * @returns {Float32Array} matrix\n * @private\n */\n translatePosMatrix(matrix: Float32Array, tile: Tile, translate: [number, number], translateAnchor: 'map' | 'viewport', inViewportPixelUnitsUnits?: boolean) {\n if (!translate[0] && !translate[1]) return matrix;\n\n const angle = inViewportPixelUnitsUnits ?\n (translateAnchor === 'map' ? this.transform.angle : 0) :\n (translateAnchor === 'viewport' ? -this.transform.angle : 0);\n\n if (angle) {\n const sinA = Math.sin(angle);\n const cosA = Math.cos(angle);\n translate = [\n translate[0] * cosA - translate[1] * sinA,\n translate[0] * sinA + translate[1] * cosA\n ];\n }\n\n const translation = [\n inViewportPixelUnitsUnits ? translate[0] : pixelsToTileUnits(tile, translate[0], this.transform.zoom),\n inViewportPixelUnitsUnits ? translate[1] : pixelsToTileUnits(tile, translate[1], this.transform.zoom),\n 0\n ];\n\n const translatedMatrix = new Float32Array(16);\n mat4.translate(translatedMatrix, matrix, translation);\n return translatedMatrix;\n }\n\n saveTileTexture(texture: Texture) {\n const textures = this._tileTextures[texture.size[0]];\n if (!textures) {\n this._tileTextures[texture.size[0]] = [texture];\n } else {\n textures.push(texture);\n }\n }\n\n getTileTexture(size: number) {\n const textures = this._tileTextures[size];\n return textures && textures.length > 0 ? textures.pop() : null;\n }\n\n /**\n * Checks whether a pattern image is needed, and if it is, whether it is not loaded.\n *\n * @returns true if a needed image is missing and rendering needs to be skipped.\n * @private\n */\n isPatternMissing(image: ?CrossFaded): boolean {\n if (!image) return false;\n if (!image.from || !image.to) return true;\n const imagePosA = this.imageManager.getPattern(image.from.toString());\n const imagePosB = this.imageManager.getPattern(image.to.toString());\n return !imagePosA || !imagePosB;\n }\n\n useProgram(name: string, programConfiguration: ?ProgramConfiguration): Program {\n this.cache = this.cache || {};\n const key = `${name}${programConfiguration ? programConfiguration.cacheKey : ''}${this._showOverdrawInspector ? '/overdraw' : ''}`;\n if (!this.cache[key]) {\n this.cache[key] = new Program(this.context, name, shaders[name], programConfiguration, programUniforms[name], this._showOverdrawInspector);\n }\n return this.cache[key];\n }\n\n /*\n * Reset some GL state to default values to avoid hard-to-debug bugs\n * in custom layers.\n */\n setCustomLayerDefaults() {\n // Prevent custom layers from unintentionally modify the last VAO used.\n // All other state is state is restored on it's own, but for VAOs it's\n // simpler to unbind so that we don't have to track the state of VAOs.\n this.context.unbindVAO();\n\n // The default values for this state is meaningful and often expected.\n // Leaving this state dirty could cause a lot of confusion for users.\n this.context.cullFace.setDefault();\n this.context.activeTexture.setDefault();\n this.context.pixelStoreUnpack.setDefault();\n this.context.pixelStoreUnpackPremultiplyAlpha.setDefault();\n this.context.pixelStoreUnpackFlipY.setDefault();\n }\n\n /*\n * Set GL state that is shared by all layers.\n */\n setBaseState() {\n const gl = this.context.gl;\n this.context.cullFace.set(false);\n this.context.viewport.set([0, 0, this.width, this.height]);\n this.context.blendEquation.set(gl.FUNC_ADD);\n }\n\n initDebugOverlayCanvas() {\n if (this.debugOverlayCanvas == null) {\n this.debugOverlayCanvas = window.document.createElement('canvas');\n this.debugOverlayCanvas.width = 512;\n this.debugOverlayCanvas.height = 512;\n const gl = this.context.gl;\n this.debugOverlayTexture = new Texture(this.context, this.debugOverlayCanvas, gl.RGBA);\n }\n }\n\n destroy() {\n this.emptyTexture.destroy();\n if (this.debugOverlayTexture) {\n this.debugOverlayTexture.destroy();\n }\n }\n}\n\nexport default Painter;\n","// @flow\n\nimport StencilMode from '../gl/stencil_mode';\nimport DepthMode from '../gl/depth_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport Program from './program';\nimport {circleUniformValues} from './program/circle_program';\nimport SegmentVector from '../data/segment';\nimport {OverscaledTileID} from '../source/tile_id';\n\nimport type Painter from './painter';\nimport type SourceCache from '../source/source_cache';\nimport type CircleStyleLayer from '../style/style_layer/circle_style_layer';\nimport type CircleBucket from '../data/bucket/circle_bucket';\nimport type ProgramConfiguration from '../data/program_configuration';\nimport type VertexBuffer from '../gl/vertex_buffer';\nimport type IndexBuffer from '../gl/index_buffer';\nimport type {UniformValues} from './uniform_binding';\nimport type {CircleUniformsType} from './program/circle_program';\n\nexport default drawCircles;\n\ntype TileRenderState = {\n programConfiguration: ProgramConfiguration,\n program: Program<*>,\n layoutVertexBuffer: VertexBuffer,\n indexBuffer: IndexBuffer,\n uniformValues: UniformValues\n};\n\ntype SegmentsTileRenderState = {\n segments: SegmentVector,\n sortKey: number,\n state: TileRenderState\n};\n\nfunction drawCircles(painter: Painter, sourceCache: SourceCache, layer: CircleStyleLayer, coords: Array) {\n if (painter.renderPass !== 'translucent') return;\n\n const opacity = layer.paint.get('circle-opacity');\n const strokeWidth = layer.paint.get('circle-stroke-width');\n const strokeOpacity = layer.paint.get('circle-stroke-opacity');\n const sortFeaturesByKey = layer.layout.get('circle-sort-key').constantOr(1) !== undefined;\n\n if (opacity.constantOr(1) === 0 && (strokeWidth.constantOr(1) === 0 || strokeOpacity.constantOr(1) === 0)) {\n return;\n }\n\n const context = painter.context;\n const gl = context.gl;\n\n const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);\n // Turn off stencil testing to allow circles to be drawn across boundaries,\n // so that large circles are not clipped to tiles\n const stencilMode = StencilMode.disabled;\n const colorMode = painter.colorModeForRenderPass();\n\n const segmentsRenderStates: Array = [];\n\n for (let i = 0; i < coords.length; i++) {\n const coord = coords[i];\n\n const tile = sourceCache.getTile(coord);\n const bucket: ?CircleBucket<*> = (tile.getBucket(layer): any);\n if (!bucket) continue;\n\n const programConfiguration = bucket.programConfigurations.get(layer.id);\n const program = painter.useProgram('circle', programConfiguration);\n const layoutVertexBuffer = bucket.layoutVertexBuffer;\n const indexBuffer = bucket.indexBuffer;\n const uniformValues = circleUniformValues(painter, coord, tile, layer);\n\n const state: TileRenderState = {\n programConfiguration,\n program,\n layoutVertexBuffer,\n indexBuffer,\n uniformValues,\n };\n\n if (sortFeaturesByKey) {\n const oldSegments = bucket.segments.get();\n for (const segment of oldSegments) {\n segmentsRenderStates.push({\n segments: new SegmentVector([segment]),\n sortKey: ((segment.sortKey: any): number),\n state\n });\n }\n } else {\n segmentsRenderStates.push({\n segments: bucket.segments,\n sortKey: 0,\n state\n });\n }\n\n }\n\n if (sortFeaturesByKey) {\n segmentsRenderStates.sort((a, b) => a.sortKey - b.sortKey);\n }\n\n for (const segmentsState of segmentsRenderStates) {\n const {programConfiguration, program, layoutVertexBuffer, indexBuffer, uniformValues} = segmentsState.state;\n const segments = segmentsState.segments;\n\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, layer.id,\n layoutVertexBuffer, indexBuffer, segments,\n layer.paint, painter.transform.zoom, programConfiguration);\n }\n}\n","// @flow\n\nimport Texture from './texture';\nimport Color from '../style-spec/util/color';\nimport DepthMode from '../gl/depth_mode';\nimport StencilMode from '../gl/stencil_mode';\nimport ColorMode from '../gl/color_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport {\n heatmapUniformValues,\n heatmapTextureUniformValues\n} from './program/heatmap_program';\n\nimport type Painter from './painter';\nimport type SourceCache from '../source/source_cache';\nimport type HeatmapStyleLayer from '../style/style_layer/heatmap_style_layer';\nimport type HeatmapBucket from '../data/bucket/heatmap_bucket';\nimport type {OverscaledTileID} from '../source/tile_id';\n\nexport default drawHeatmap;\n\nfunction drawHeatmap(painter: Painter, sourceCache: SourceCache, layer: HeatmapStyleLayer, coords: Array) {\n if (layer.paint.get('heatmap-opacity') === 0) {\n return;\n }\n\n if (painter.renderPass === 'offscreen') {\n const context = painter.context;\n const gl = context.gl;\n\n // Allow kernels to be drawn across boundaries, so that\n // large kernels are not clipped to tiles\n const stencilMode = StencilMode.disabled;\n // Turn on additive blending for kernels, which is a key aspect of kernel density estimation formula\n const colorMode = new ColorMode([gl.ONE, gl.ONE], Color.transparent, [true, true, true, true]);\n\n bindFramebuffer(context, painter, layer);\n\n context.clear({color: Color.transparent});\n\n for (let i = 0; i < coords.length; i++) {\n const coord = coords[i];\n\n // Skip tiles that have uncovered parents to avoid flickering; we don't need\n // to use complex tile masking here because the change between zoom levels is subtle,\n // so it's fine to simply render the parent until all its 4 children are loaded\n if (sourceCache.hasRenderableParent(coord)) continue;\n\n const tile = sourceCache.getTile(coord);\n const bucket: ?HeatmapBucket = (tile.getBucket(layer): any);\n if (!bucket) continue;\n\n const programConfiguration = bucket.programConfigurations.get(layer.id);\n const program = painter.useProgram('heatmap', programConfiguration);\n const {zoom} = painter.transform;\n\n program.draw(context, gl.TRIANGLES, DepthMode.disabled, stencilMode, colorMode, CullFaceMode.disabled,\n heatmapUniformValues(coord.posMatrix,\n tile, zoom, layer.paint.get('heatmap-intensity')),\n layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer,\n bucket.segments, layer.paint, painter.transform.zoom,\n programConfiguration);\n }\n\n context.viewport.set([0, 0, painter.width, painter.height]);\n\n } else if (painter.renderPass === 'translucent') {\n painter.context.setColorMode(painter.colorModeForRenderPass());\n renderTextureToMap(painter, layer);\n }\n}\n\nfunction bindFramebuffer(context, painter, layer) {\n const gl = context.gl;\n context.activeTexture.set(gl.TEXTURE1);\n\n // Use a 4x downscaled screen texture for better performance\n context.viewport.set([0, 0, painter.width / 4, painter.height / 4]);\n\n let fbo = layer.heatmapFbo;\n\n if (!fbo) {\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n\n fbo = layer.heatmapFbo = context.createFramebuffer(painter.width / 4, painter.height / 4, false);\n\n bindTextureToFramebuffer(context, painter, texture, fbo);\n\n } else {\n gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());\n context.bindFramebuffer.set(fbo.framebuffer);\n }\n}\n\nfunction bindTextureToFramebuffer(context, painter, texture, fbo) {\n const gl = context.gl;\n // Use the higher precision half-float texture where available (producing much smoother looking heatmaps);\n // Otherwise, fall back to a low precision texture\n const internalFormat = context.extRenderToTextureHalfFloat ? context.extTextureHalfFloat.HALF_FLOAT_OES : gl.UNSIGNED_BYTE;\n gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, painter.width / 4, painter.height / 4, 0, gl.RGBA, internalFormat, null);\n fbo.colorAttachment.set(texture);\n}\n\nfunction renderTextureToMap(painter, layer) {\n const context = painter.context;\n const gl = context.gl;\n\n // Here we bind two different textures from which we'll sample in drawing\n // heatmaps: the kernel texture, prepared in the offscreen pass, and a\n // color ramp texture.\n const fbo = layer.heatmapFbo;\n if (!fbo) return;\n context.activeTexture.set(gl.TEXTURE0);\n gl.bindTexture(gl.TEXTURE_2D, fbo.colorAttachment.get());\n\n context.activeTexture.set(gl.TEXTURE1);\n let colorRampTexture = layer.colorRampTexture;\n if (!colorRampTexture) {\n colorRampTexture = layer.colorRampTexture = new Texture(context, layer.colorRamp, gl.RGBA);\n }\n colorRampTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n\n painter.useProgram('heatmapTexture').draw(context, gl.TRIANGLES,\n DepthMode.disabled, StencilMode.disabled, painter.colorModeForRenderPass(), CullFaceMode.disabled,\n heatmapTextureUniformValues(painter, layer, 0, 1),\n layer.id, painter.viewportBuffer, painter.quadTriangleIndexBuffer,\n painter.viewportSegments, layer.paint, painter.transform.zoom);\n}\n","// @flow\n\nimport DepthMode from '../gl/depth_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport Texture from './texture';\nimport {\n lineUniformValues,\n linePatternUniformValues,\n lineSDFUniformValues,\n lineGradientUniformValues\n} from './program/line_program';\n\nimport type Painter from './painter';\nimport type SourceCache from '../source/source_cache';\nimport type LineStyleLayer from '../style/style_layer/line_style_layer';\nimport type LineBucket from '../data/bucket/line_bucket';\nimport type {OverscaledTileID} from '../source/tile_id';\nimport {clamp, nextPowerOfTwo} from '../util/util';\nimport {renderColorRamp} from '../util/color_ramp';\nimport EXTENT from '../data/extent';\n\nexport default function drawLine(painter: Painter, sourceCache: SourceCache, layer: LineStyleLayer, coords: Array) {\n if (painter.renderPass !== 'translucent') return;\n\n const opacity = layer.paint.get('line-opacity');\n const width = layer.paint.get('line-width');\n if (opacity.constantOr(1) === 0 || width.constantOr(1) === 0) return;\n\n const depthMode = painter.depthModeForSublayer(0, DepthMode.ReadOnly);\n const colorMode = painter.colorModeForRenderPass();\n\n const dasharray = layer.paint.get('line-dasharray');\n const patternProperty = layer.paint.get('line-pattern');\n const image = patternProperty.constantOr((1: any));\n\n const gradient = layer.paint.get('line-gradient');\n const crossfade = layer.getCrossfadeParameters();\n\n const programId =\n image ? 'linePattern' :\n dasharray ? 'lineSDF' :\n gradient ? 'lineGradient' : 'line';\n\n const context = painter.context;\n const gl = context.gl;\n\n let firstTile = true;\n\n for (const coord of coords) {\n const tile = sourceCache.getTile(coord);\n\n if (image && !tile.patternsLoaded()) continue;\n\n const bucket: ?LineBucket = (tile.getBucket(layer): any);\n if (!bucket) continue;\n\n const programConfiguration = bucket.programConfigurations.get(layer.id);\n const prevProgram = painter.context.program.get();\n const program = painter.useProgram(programId, programConfiguration);\n const programChanged = firstTile || program.program !== prevProgram;\n\n const constantPattern = patternProperty.constantOr(null);\n if (constantPattern && tile.imageAtlas) {\n const atlas = tile.imageAtlas;\n const posTo = atlas.patternPositions[constantPattern.to.toString()];\n const posFrom = atlas.patternPositions[constantPattern.from.toString()];\n if (posTo && posFrom) programConfiguration.setConstantPatternPositions(posTo, posFrom);\n }\n\n const uniformValues = image ? linePatternUniformValues(painter, tile, layer, crossfade) :\n dasharray ? lineSDFUniformValues(painter, tile, layer, dasharray, crossfade) :\n gradient ? lineGradientUniformValues(painter, tile, layer, bucket.lineClipsArray.length) :\n lineUniformValues(painter, tile, layer);\n\n if (image) {\n context.activeTexture.set(gl.TEXTURE0);\n tile.imageAtlasTexture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n programConfiguration.updatePaintBuffers(crossfade);\n } else if (dasharray && (programChanged || painter.lineAtlas.dirty)) {\n context.activeTexture.set(gl.TEXTURE0);\n painter.lineAtlas.bind(context);\n } else if (gradient) {\n const layerGradient = bucket.gradients[layer.id];\n let gradientTexture = layerGradient.texture;\n if (layer.gradientVersion !== layerGradient.version) {\n let textureResolution = 256;\n if (layer.stepInterpolant) {\n const sourceMaxZoom = sourceCache.getSource().maxzoom;\n const potentialOverzoom = coord.canonical.z === sourceMaxZoom ?\n Math.ceil(1 << (painter.transform.maxZoom - coord.canonical.z)) : 1;\n const lineLength = bucket.maxLineLength / EXTENT;\n // Logical pixel tile size is 512px, and 1024px right before current zoom + 1\n const maxTilePixelSize = 1024;\n // Maximum possible texture coverage heuristic, bound by hardware max texture size\n const maxTextureCoverage = lineLength * maxTilePixelSize * potentialOverzoom;\n textureResolution = clamp(nextPowerOfTwo(maxTextureCoverage), 256, context.maxTextureSize);\n }\n layerGradient.gradient = renderColorRamp({\n expression: layer.gradientExpression(),\n evaluationKey: 'lineProgress',\n resolution: textureResolution,\n image: layerGradient.gradient || undefined,\n clips: bucket.lineClipsArray\n });\n if (layerGradient.texture) {\n layerGradient.texture.update(layerGradient.gradient);\n } else {\n layerGradient.texture = new Texture(context, layerGradient.gradient, gl.RGBA);\n }\n layerGradient.version = layer.gradientVersion;\n gradientTexture = layerGradient.texture;\n }\n context.activeTexture.set(gl.TEXTURE0);\n gradientTexture.bind(layer.stepInterpolant ? gl.NEAREST : gl.LINEAR, gl.CLAMP_TO_EDGE);\n }\n\n program.draw(context, gl.TRIANGLES, depthMode,\n painter.stencilModeForClipping(coord), colorMode, CullFaceMode.disabled, uniformValues,\n layer.id, bucket.layoutVertexBuffer, bucket.indexBuffer, bucket.segments,\n layer.paint, painter.transform.zoom, programConfiguration, bucket.layoutVertexBuffer2);\n\n firstTile = false;\n // once refactored so that bound texture state is managed, we'll also be able to remove this firstTile/programChanged logic\n }\n}\n","// @flow\n\nimport StencilMode from '../gl/stencil_mode';\nimport DepthMode from '../gl/depth_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport {\n backgroundUniformValues,\n backgroundPatternUniformValues\n} from './program/background_program';\n\nimport type Painter from './painter';\nimport type SourceCache from '../source/source_cache';\nimport type BackgroundStyleLayer from '../style/style_layer/background_style_layer';\n\nexport default drawBackground;\n\nfunction drawBackground(painter: Painter, sourceCache: SourceCache, layer: BackgroundStyleLayer) {\n const color = layer.paint.get('background-color');\n const opacity = layer.paint.get('background-opacity');\n\n if (opacity === 0) return;\n\n const context = painter.context;\n const gl = context.gl;\n const transform = painter.transform;\n const tileSize = transform.tileSize;\n const image = layer.paint.get('background-pattern');\n if (painter.isPatternMissing(image)) return;\n\n const pass = (!image && color.a === 1 && opacity === 1 && painter.opaquePassEnabledForLayer()) ? 'opaque' : 'translucent';\n if (painter.renderPass !== pass) return;\n\n const stencilMode = StencilMode.disabled;\n const depthMode = painter.depthModeForSublayer(0, pass === 'opaque' ? DepthMode.ReadWrite : DepthMode.ReadOnly);\n const colorMode = painter.colorModeForRenderPass();\n\n const program = painter.useProgram(image ? 'backgroundPattern' : 'background');\n\n const tileIDs = transform.coveringTiles({tileSize});\n\n if (image) {\n context.activeTexture.set(gl.TEXTURE0);\n painter.imageManager.bind(painter.context);\n }\n\n const crossfade = layer.getCrossfadeParameters();\n for (const tileID of tileIDs) {\n const matrix = painter.transform.calculatePosMatrix(tileID.toUnwrapped());\n const uniformValues = image ?\n backgroundPatternUniformValues(matrix, opacity, painter, image, {tileID, tileSize}, crossfade) :\n backgroundUniformValues(matrix, opacity, color);\n\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, layer.id, painter.tileExtentBuffer,\n painter.quadTriangleIndexBuffer, painter.tileExtentSegments);\n }\n}\n","// @flow\n\nexport default drawCustom;\n\nimport DepthMode from '../gl/depth_mode';\nimport StencilMode from '../gl/stencil_mode';\n\nimport type Painter from './painter';\nimport type SourceCache from '../source/source_cache';\nimport type CustomStyleLayer from '../style/style_layer/custom_style_layer';\n\nfunction drawCustom(painter: Painter, sourceCache: SourceCache, layer: CustomStyleLayer) {\n\n const context = painter.context;\n const implementation = layer.implementation;\n\n if (painter.renderPass === 'offscreen') {\n\n const prerender = implementation.prerender;\n if (prerender) {\n painter.setCustomLayerDefaults();\n context.setColorMode(painter.colorModeForRenderPass());\n\n prerender.call(implementation, context.gl, painter.transform.customLayerMatrix());\n\n context.setDirty();\n painter.setBaseState();\n }\n\n } else if (painter.renderPass === 'translucent') {\n\n painter.setCustomLayerDefaults();\n\n context.setColorMode(painter.colorModeForRenderPass());\n context.setStencilMode(StencilMode.disabled);\n\n const depthMode = implementation.renderingMode === '3d' ?\n new DepthMode(painter.context.gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D) :\n painter.depthModeForSublayer(0, DepthMode.ReadOnly);\n\n context.setDepthMode(depthMode);\n\n implementation.render(context.gl, painter.transform.customLayerMatrix());\n\n context.setDirty();\n painter.setBaseState();\n context.bindFramebuffer.set(null);\n }\n}\n","// @flow\n\nimport {vec3, vec4} from 'gl-matrix';\nimport assert from 'assert';\n\nclass Frustum {\n points: Array>;\n planes: Array>;\n\n constructor(points_: Array>, planes_: Array>) {\n this.points = points_;\n this.planes = planes_;\n }\n\n static fromInvProjectionMatrix(invProj: Float64Array, worldSize: number, zoom: number): Frustum {\n const clipSpaceCorners = [\n [-1, 1, -1, 1],\n [ 1, 1, -1, 1],\n [ 1, -1, -1, 1],\n [-1, -1, -1, 1],\n [-1, 1, 1, 1],\n [ 1, 1, 1, 1],\n [ 1, -1, 1, 1],\n [-1, -1, 1, 1]\n ];\n\n const scale = Math.pow(2, zoom);\n\n // Transform frustum corner points from clip space to tile space\n const frustumCoords = clipSpaceCorners\n .map(v => vec4.transformMat4([], v, invProj))\n .map(v => vec4.scale([], v, 1.0 / v[3] / worldSize * scale));\n\n const frustumPlanePointIndices = [\n [0, 1, 2], // near\n [6, 5, 4], // far\n [0, 3, 7], // left\n [2, 1, 5], // right\n [3, 2, 6], // bottom\n [0, 4, 5] // top\n ];\n\n const frustumPlanes = frustumPlanePointIndices.map((p: Array) => {\n const a = vec3.sub([], frustumCoords[p[0]], frustumCoords[p[1]]);\n const b = vec3.sub([], frustumCoords[p[2]], frustumCoords[p[1]]);\n const n = vec3.normalize([], vec3.cross([], a, b));\n const d = -vec3.dot(n, frustumCoords[p[1]]);\n return n.concat(d);\n });\n\n return new Frustum(frustumCoords, frustumPlanes);\n }\n}\n\nclass Aabb {\n min: vec3;\n max: vec3;\n center: vec3;\n\n constructor(min_: vec3, max_: vec3) {\n this.min = min_;\n this.max = max_;\n this.center = vec3.scale([], vec3.add([], this.min, this.max), 0.5);\n }\n\n quadrant(index: number): Aabb {\n const split = [(index % 2) === 0, index < 2];\n const qMin = vec3.clone(this.min);\n const qMax = vec3.clone(this.max);\n for (let axis = 0; axis < split.length; axis++) {\n qMin[axis] = split[axis] ? this.min[axis] : this.center[axis];\n qMax[axis] = split[axis] ? this.center[axis] : this.max[axis];\n }\n // Elevation is always constant, hence quadrant.max.z = this.max.z\n qMax[2] = this.max[2];\n return new Aabb(qMin, qMax);\n }\n\n distanceX(point: Array): number {\n const pointOnAabb = Math.max(Math.min(this.max[0], point[0]), this.min[0]);\n return pointOnAabb - point[0];\n }\n\n distanceY(point: Array): number {\n const pointOnAabb = Math.max(Math.min(this.max[1], point[1]), this.min[1]);\n return pointOnAabb - point[1];\n }\n\n // Performs a frustum-aabb intersection test. Returns 0 if there's no intersection,\n // 1 if shapes are intersecting and 2 if the aabb if fully inside the frustum.\n intersects(frustum: Frustum): number {\n // Execute separating axis test between two convex objects to find intersections\n // Each frustum plane together with 3 major axes define the separating axes\n // Note: test only 4 points as both min and max points have equal elevation\n assert(this.min[2] === 0 && this.max[2] === 0);\n\n const aabbPoints = [\n [this.min[0], this.min[1], 0.0, 1],\n [this.max[0], this.min[1], 0.0, 1],\n [this.max[0], this.max[1], 0.0, 1],\n [this.min[0], this.max[1], 0.0, 1]\n ];\n\n let fullyInside = true;\n\n for (let p = 0; p < frustum.planes.length; p++) {\n const plane = frustum.planes[p];\n let pointsInside = 0;\n\n for (let i = 0; i < aabbPoints.length; i++) {\n pointsInside += vec4.dot(plane, aabbPoints[i]) >= 0;\n }\n\n if (pointsInside === 0)\n return 0;\n\n if (pointsInside !== aabbPoints.length)\n fullyInside = false;\n }\n\n if (fullyInside)\n return 2;\n\n for (let axis = 0; axis < 3; axis++) {\n let projMin = Number.MAX_VALUE;\n let projMax = -Number.MAX_VALUE;\n\n for (let p = 0; p < frustum.points.length; p++) {\n const projectedPoint = frustum.points[p][axis] - this.min[axis];\n\n projMin = Math.min(projMin, projectedPoint);\n projMax = Math.max(projMax, projectedPoint);\n }\n\n if (projMax < 0 || projMin > this.max[axis] - this.min[axis])\n return 0;\n }\n\n return 1;\n }\n}\nexport {\n Aabb,\n Frustum\n};\n","// @flow\nimport {number} from \"../style-spec/util/interpolate\";\nimport Point from \"@mapbox/point-geometry\";\nimport {clamp} from \"../util/util\";\n\n/**\n * An `EdgeInset` object represents screen space padding applied to the edges of the viewport.\n * This shifts the apprent center or the vanishing point of the map. This is useful for adding floating UI elements\n * on top of the map and having the vanishing point shift as UI elements resize.\n *\n * @param {number} [top=0]\n * @param {number} [bottom=0]\n * @param {number} [left=0]\n * @param {number} [right=0]\n */\nclass EdgeInsets {\n top: number;\n bottom: number;\n left: number;\n right: number;\n\n constructor(top: number = 0, bottom: number = 0, left: number = 0, right: number = 0) {\n if (isNaN(top) || top < 0 ||\n isNaN(bottom) || bottom < 0 ||\n isNaN(left) || left < 0 ||\n isNaN(right) || right < 0\n ) {\n throw new Error('Invalid value for edge-insets, top, bottom, left and right must all be numbers');\n }\n\n this.top = top;\n this.bottom = bottom;\n this.left = left;\n this.right = right;\n }\n\n /**\n * Interpolates the inset in-place.\n * This maintains the current inset value for any inset not present in `target`.\n *\n * @param {PaddingOptions} target\n * @param {number} t\n * @returns {EdgeInsets}\n * @memberof EdgeInsets\n */\n interpolate(start: PaddingOptions | EdgeInsets, target: PaddingOptions, t: number): EdgeInsets {\n if (target.top != null && start.top != null) this.top = number(start.top, target.top, t);\n if (target.bottom != null && start.bottom != null) this.bottom = number(start.bottom, target.bottom, t);\n if (target.left != null && start.left != null) this.left = number(start.left, target.left, t);\n if (target.right != null && start.right != null) this.right = number(start.right, target.right, t);\n\n return this;\n }\n\n /**\n * Utility method that computes the new apprent center or vanishing point after applying insets.\n * This is in pixels and with the top left being (0.0) and +y being downwards.\n *\n * @param {number} width\n * @param {number} height\n * @returns {Point}\n * @memberof EdgeInsets\n */\n getCenter(width: number, height: number): Point {\n // Clamp insets so they never overflow width/height and always calculate a valid center\n const x = clamp((this.left + width - this.right) / 2, 0, width);\n const y = clamp((this.top + height - this.bottom) / 2, 0, height);\n\n return new Point(x, y);\n }\n\n equals(other: PaddingOptions): boolean {\n return this.top === other.top &&\n this.bottom === other.bottom &&\n this.left === other.left &&\n this.right === other.right;\n }\n\n clone(): EdgeInsets {\n return new EdgeInsets(this.top, this.bottom, this.left, this.right);\n }\n\n /**\n * Returns the current sdtate as json, useful when you want to have a\n * read-only representation of the inset.\n *\n * @returns {PaddingOptions}\n * @memberof EdgeInsets\n */\n toJSON(): PaddingOptions {\n return {\n top: this.top,\n bottom: this.bottom,\n left: this.left,\n right: this.right\n };\n }\n}\n\nexport type PaddingOptions = {top: ?number, bottom: ?number, right: ?number, left: ?number};\n\nexport default EdgeInsets;\n","// @flow\n\nimport LngLat from './lng_lat';\nimport LngLatBounds from './lng_lat_bounds';\nimport MercatorCoordinate, {mercatorXfromLng, mercatorYfromLat, mercatorZfromAltitude} from './mercator_coordinate';\nimport Point from '@mapbox/point-geometry';\nimport {wrap, clamp} from '../util/util';\nimport {number as interpolate} from '../style-spec/util/interpolate';\nimport EXTENT from '../data/extent';\nimport {vec4, mat4, mat2, vec2} from 'gl-matrix';\nimport {Aabb, Frustum} from '../util/primitives.js';\nimport EdgeInsets from './edge_insets';\n\nimport {UnwrappedTileID, OverscaledTileID, CanonicalTileID} from '../source/tile_id';\nimport type {PaddingOptions} from './edge_insets';\n\n/**\n * A single transform, generally used for a single tile to be\n * scaled, rotated, and zoomed.\n * @private\n */\nclass Transform {\n tileSize: number;\n tileZoom: number;\n lngRange: ?[number, number];\n latRange: ?[number, number];\n maxValidLatitude: number;\n scale: number;\n width: number;\n height: number;\n angle: number;\n rotationMatrix: Float64Array;\n zoomFraction: number;\n pixelsToGLUnits: [number, number];\n cameraToCenterDistance: number;\n mercatorMatrix: Array;\n projMatrix: Float64Array;\n invProjMatrix: Float64Array;\n alignedProjMatrix: Float64Array;\n pixelMatrix: Float64Array;\n pixelMatrixInverse: Float64Array;\n glCoordMatrix: Float32Array;\n labelPlaneMatrix: Float32Array;\n _fov: number;\n _pitch: number;\n _zoom: number;\n _unmodified: boolean;\n _renderWorldCopies: boolean;\n _minZoom: number;\n _maxZoom: number;\n _minPitch: number;\n _maxPitch: number;\n _center: LngLat;\n _edgeInsets: EdgeInsets;\n _constraining: boolean;\n _posMatrixCache: {[_: string]: Float32Array};\n _alignedPosMatrixCache: {[_: string]: Float32Array};\n\n constructor(minZoom: ?number, maxZoom: ?number, minPitch: ?number, maxPitch: ?number, renderWorldCopies: boolean | void) {\n this.tileSize = 512; // constant\n this.maxValidLatitude = 85.051129; // constant\n\n this._renderWorldCopies = renderWorldCopies === undefined ? true : renderWorldCopies;\n this._minZoom = minZoom || 0;\n this._maxZoom = maxZoom || 22;\n\n this._minPitch = (minPitch === undefined || minPitch === null) ? 0 : minPitch;\n this._maxPitch = (maxPitch === undefined || maxPitch === null) ? 60 : maxPitch;\n\n this.setMaxBounds();\n\n this.width = 0;\n this.height = 0;\n this._center = new LngLat(0, 0);\n this.zoom = 0;\n this.angle = 0;\n this._fov = 0.6435011087932844;\n this._pitch = 0;\n this._unmodified = true;\n this._edgeInsets = new EdgeInsets();\n this._posMatrixCache = {};\n this._alignedPosMatrixCache = {};\n }\n\n clone(): Transform {\n const clone = new Transform(this._minZoom, this._maxZoom, this._minPitch, this.maxPitch, this._renderWorldCopies);\n clone.tileSize = this.tileSize;\n clone.latRange = this.latRange;\n clone.width = this.width;\n clone.height = this.height;\n clone._center = this._center;\n clone.zoom = this.zoom;\n clone.angle = this.angle;\n clone._fov = this._fov;\n clone._pitch = this._pitch;\n clone._unmodified = this._unmodified;\n clone._edgeInsets = this._edgeInsets.clone();\n clone._calcMatrices();\n return clone;\n }\n\n get minZoom(): number { return this._minZoom; }\n set minZoom(zoom: number) {\n if (this._minZoom === zoom) return;\n this._minZoom = zoom;\n this.zoom = Math.max(this.zoom, zoom);\n }\n\n get maxZoom(): number { return this._maxZoom; }\n set maxZoom(zoom: number) {\n if (this._maxZoom === zoom) return;\n this._maxZoom = zoom;\n this.zoom = Math.min(this.zoom, zoom);\n }\n\n get minPitch(): number { return this._minPitch; }\n set minPitch(pitch: number) {\n if (this._minPitch === pitch) return;\n this._minPitch = pitch;\n this.pitch = Math.max(this.pitch, pitch);\n }\n\n get maxPitch(): number { return this._maxPitch; }\n set maxPitch(pitch: number) {\n if (this._maxPitch === pitch) return;\n this._maxPitch = pitch;\n this.pitch = Math.min(this.pitch, pitch);\n }\n\n get renderWorldCopies(): boolean { return this._renderWorldCopies; }\n set renderWorldCopies(renderWorldCopies?: ?boolean) {\n if (renderWorldCopies === undefined) {\n renderWorldCopies = true;\n } else if (renderWorldCopies === null) {\n renderWorldCopies = false;\n }\n\n this._renderWorldCopies = renderWorldCopies;\n }\n\n get worldSize(): number {\n return this.tileSize * this.scale;\n }\n\n get centerOffset(): Point {\n return this.centerPoint._sub(this.size._div(2));\n }\n\n get size(): Point {\n return new Point(this.width, this.height);\n }\n\n get bearing(): number {\n return -this.angle / Math.PI * 180;\n }\n set bearing(bearing: number) {\n const b = -wrap(bearing, -180, 180) * Math.PI / 180;\n if (this.angle === b) return;\n this._unmodified = false;\n this.angle = b;\n this._calcMatrices();\n\n // 2x2 matrix for rotating points\n this.rotationMatrix = mat2.create();\n mat2.rotate(this.rotationMatrix, this.rotationMatrix, this.angle);\n }\n\n get pitch(): number {\n return this._pitch / Math.PI * 180;\n }\n set pitch(pitch: number) {\n const p = clamp(pitch, this.minPitch, this.maxPitch) / 180 * Math.PI;\n if (this._pitch === p) return;\n this._unmodified = false;\n this._pitch = p;\n this._calcMatrices();\n }\n\n get fov(): number {\n return this._fov / Math.PI * 180;\n }\n set fov(fov: number) {\n fov = Math.max(0.01, Math.min(60, fov));\n if (this._fov === fov) return;\n this._unmodified = false;\n this._fov = fov / 180 * Math.PI;\n this._calcMatrices();\n }\n\n get zoom(): number { return this._zoom; }\n set zoom(zoom: number) {\n const z = Math.min(Math.max(zoom, this.minZoom), this.maxZoom);\n if (this._zoom === z) return;\n this._unmodified = false;\n this._zoom = z;\n this.scale = this.zoomScale(z);\n this.tileZoom = Math.floor(z);\n this.zoomFraction = z - this.tileZoom;\n this._constrain();\n this._calcMatrices();\n }\n\n get center(): LngLat { return this._center; }\n set center(center: LngLat) {\n if (center.lat === this._center.lat && center.lng === this._center.lng) return;\n this._unmodified = false;\n this._center = center;\n this._constrain();\n this._calcMatrices();\n }\n\n get padding(): PaddingOptions { return this._edgeInsets.toJSON(); }\n set padding(padding: PaddingOptions) {\n if (this._edgeInsets.equals(padding)) return;\n this._unmodified = false;\n //Update edge-insets inplace\n this._edgeInsets.interpolate(this._edgeInsets, padding, 1);\n this._calcMatrices();\n }\n\n /**\n * The center of the screen in pixels with the top-left corner being (0,0)\n * and +y axis pointing downwards. This accounts for padding.\n *\n * @readonly\n * @type {Point}\n * @memberof Transform\n */\n get centerPoint(): Point {\n return this._edgeInsets.getCenter(this.width, this.height);\n }\n\n /**\n * Returns if the padding params match\n *\n * @param {PaddingOptions} padding\n * @returns {boolean}\n * @memberof Transform\n */\n isPaddingEqual(padding: PaddingOptions): boolean {\n return this._edgeInsets.equals(padding);\n }\n\n /**\n * Helper method to upadte edge-insets inplace\n *\n * @param {PaddingOptions} target\n * @param {number} t\n * @memberof Transform\n */\n interpolatePadding(start: PaddingOptions, target: PaddingOptions, t: number) {\n this._unmodified = false;\n this._edgeInsets.interpolate(start, target, t);\n this._constrain();\n this._calcMatrices();\n }\n\n /**\n * Return a zoom level that will cover all tiles the transform\n * @param {Object} options options\n * @param {number} options.tileSize Tile size, expressed in screen pixels.\n * @param {boolean} options.roundZoom Target zoom level. If true, the value will be rounded to the closest integer. Otherwise the value will be floored.\n * @returns {number} zoom level An integer zoom level at which all tiles will be visible.\n */\n coveringZoomLevel(options: {roundZoom?: boolean, tileSize: number}) {\n const z = (options.roundZoom ? Math.round : Math.floor)(\n this.zoom + this.scaleZoom(this.tileSize / options.tileSize)\n );\n // At negative zoom levels load tiles from z0 because negative tile zoom levels don't exist.\n return Math.max(0, z);\n }\n\n /**\n * Return any \"wrapped\" copies of a given tile coordinate that are visible\n * in the current view.\n *\n * @private\n */\n getVisibleUnwrappedCoordinates(tileID: CanonicalTileID) {\n const result = [new UnwrappedTileID(0, tileID)];\n if (this._renderWorldCopies) {\n const utl = this.pointCoordinate(new Point(0, 0));\n const utr = this.pointCoordinate(new Point(this.width, 0));\n const ubl = this.pointCoordinate(new Point(this.width, this.height));\n const ubr = this.pointCoordinate(new Point(0, this.height));\n const w0 = Math.floor(Math.min(utl.x, utr.x, ubl.x, ubr.x));\n const w1 = Math.floor(Math.max(utl.x, utr.x, ubl.x, ubr.x));\n\n // Add an extra copy of the world on each side to properly render ImageSources and CanvasSources.\n // Both sources draw outside the tile boundaries of the tile that \"contains them\" so we need\n // to add extra copies on both sides in case offscreen tiles need to draw into on-screen ones.\n const extraWorldCopy = 1;\n\n for (let w = w0 - extraWorldCopy; w <= w1 + extraWorldCopy; w++) {\n if (w === 0) continue;\n result.push(new UnwrappedTileID(w, tileID));\n }\n }\n return result;\n }\n\n /**\n * Return all coordinates that could cover this transform for a covering\n * zoom level.\n * @param {Object} options\n * @param {number} options.tileSize\n * @param {number} options.minzoom\n * @param {number} options.maxzoom\n * @param {boolean} options.roundZoom\n * @param {boolean} options.reparseOverscaled\n * @param {boolean} options.renderWorldCopies\n * @returns {Array} OverscaledTileIDs\n * @private\n */\n coveringTiles(\n options: {\n tileSize: number,\n minzoom?: number,\n maxzoom?: number,\n roundZoom?: boolean,\n reparseOverscaled?: boolean,\n renderWorldCopies?: boolean\n }\n ): Array {\n let z = this.coveringZoomLevel(options);\n const actualZ = z;\n\n if (options.minzoom !== undefined && z < options.minzoom) return [];\n if (options.maxzoom !== undefined && z > options.maxzoom) z = options.maxzoom;\n\n const centerCoord = MercatorCoordinate.fromLngLat(this.center);\n const numTiles = Math.pow(2, z);\n const centerPoint = [numTiles * centerCoord.x, numTiles * centerCoord.y, 0];\n const cameraFrustum = Frustum.fromInvProjectionMatrix(this.invProjMatrix, this.worldSize, z);\n\n // No change of LOD behavior for pitch lower than 60 and when there is no top padding: return only tile ids from the requested zoom level\n let minZoom = options.minzoom || 0;\n // Use 0.1 as an epsilon to avoid for explicit == 0.0 floating point checks\n if (this.pitch <= 60.0 && this._edgeInsets.top < 0.1)\n minZoom = z;\n\n // There should always be a certain number of maximum zoom level tiles surrounding the center location\n const radiusOfMaxLvlLodInTiles = 3;\n\n const newRootTile = (wrap: number): any => {\n return {\n // All tiles are on zero elevation plane => z difference is zero\n aabb: new Aabb([wrap * numTiles, 0, 0], [(wrap + 1) * numTiles, numTiles, 0]),\n zoom: 0,\n x: 0,\n y: 0,\n wrap,\n fullyVisible: false\n };\n };\n\n // Do a depth-first traversal to find visible tiles and proper levels of detail\n const stack = [];\n const result = [];\n const maxZoom = z;\n const overscaledZ = options.reparseOverscaled ? actualZ : z;\n\n if (this._renderWorldCopies) {\n // Render copy of the globe thrice on both sides\n for (let i = 1; i <= 3; i++) {\n stack.push(newRootTile(-i));\n stack.push(newRootTile(i));\n }\n }\n\n stack.push(newRootTile(0));\n\n while (stack.length > 0) {\n const it = stack.pop();\n const x = it.x;\n const y = it.y;\n let fullyVisible = it.fullyVisible;\n\n // Visibility of a tile is not required if any of its ancestor if fully inside the frustum\n if (!fullyVisible) {\n const intersectResult = it.aabb.intersects(cameraFrustum);\n\n if (intersectResult === 0)\n continue;\n\n fullyVisible = intersectResult === 2;\n }\n\n const distanceX = it.aabb.distanceX(centerPoint);\n const distanceY = it.aabb.distanceY(centerPoint);\n const longestDim = Math.max(Math.abs(distanceX), Math.abs(distanceY));\n\n // We're using distance based heuristics to determine if a tile should be split into quadrants or not.\n // radiusOfMaxLvlLodInTiles defines that there's always a certain number of maxLevel tiles next to the map center.\n // Using the fact that a parent node in quadtree is twice the size of its children (per dimension)\n // we can define distance thresholds for each relative level:\n // f(k) = offset + 2 + 4 + 8 + 16 + ... + 2^k. This is the same as \"offset+2^(k+1)-2\"\n const distToSplit = radiusOfMaxLvlLodInTiles + (1 << (maxZoom - it.zoom)) - 2;\n\n // Have we reached the target depth or is the tile too far away to be any split further?\n if (it.zoom === maxZoom || (longestDim > distToSplit && it.zoom >= minZoom)) {\n result.push({\n tileID: new OverscaledTileID(it.zoom === maxZoom ? overscaledZ : it.zoom, it.wrap, it.zoom, x, y),\n distanceSq: vec2.sqrLen([centerPoint[0] - 0.5 - x, centerPoint[1] - 0.5 - y])\n });\n continue;\n }\n\n for (let i = 0; i < 4; i++) {\n const childX = (x << 1) + (i % 2);\n const childY = (y << 1) + (i >> 1);\n\n stack.push({aabb: it.aabb.quadrant(i), zoom: it.zoom + 1, x: childX, y: childY, wrap: it.wrap, fullyVisible});\n }\n }\n\n return result.sort((a, b) => a.distanceSq - b.distanceSq).map(a => a.tileID);\n }\n\n resize(width: number, height: number) {\n this.width = width;\n this.height = height;\n\n this.pixelsToGLUnits = [2 / width, -2 / height];\n this._constrain();\n this._calcMatrices();\n }\n\n get unmodified(): boolean { return this._unmodified; }\n\n zoomScale(zoom: number) { return Math.pow(2, zoom); }\n scaleZoom(scale: number) { return Math.log(scale) / Math.LN2; }\n\n project(lnglat: LngLat) {\n const lat = clamp(lnglat.lat, -this.maxValidLatitude, this.maxValidLatitude);\n return new Point(\n mercatorXfromLng(lnglat.lng) * this.worldSize,\n mercatorYfromLat(lat) * this.worldSize);\n }\n\n unproject(point: Point): LngLat {\n return new MercatorCoordinate(point.x / this.worldSize, point.y / this.worldSize).toLngLat();\n }\n\n get point(): Point { return this.project(this.center); }\n\n setLocationAtPoint(lnglat: LngLat, point: Point) {\n const a = this.pointCoordinate(point);\n const b = this.pointCoordinate(this.centerPoint);\n const loc = this.locationCoordinate(lnglat);\n const newCenter = new MercatorCoordinate(\n loc.x - (a.x - b.x),\n loc.y - (a.y - b.y));\n this.center = this.coordinateLocation(newCenter);\n if (this._renderWorldCopies) {\n this.center = this.center.wrap();\n }\n }\n\n /**\n * Given a location, return the screen point that corresponds to it\n * @param {LngLat} lnglat location\n * @returns {Point} screen point\n * @private\n */\n locationPoint(lnglat: LngLat) {\n return this.coordinatePoint(this.locationCoordinate(lnglat));\n }\n\n /**\n * Given a point on screen, return its lnglat\n * @param {Point} p screen point\n * @returns {LngLat} lnglat location\n * @private\n */\n pointLocation(p: Point) {\n return this.coordinateLocation(this.pointCoordinate(p));\n }\n\n /**\n * Given a geographical lnglat, return an unrounded\n * coordinate that represents it at this transform's zoom level.\n * @param {LngLat} lnglat\n * @returns {Coordinate}\n * @private\n */\n locationCoordinate(lnglat: LngLat) {\n return MercatorCoordinate.fromLngLat(lnglat);\n }\n\n /**\n * Given a Coordinate, return its geographical position.\n * @param {Coordinate} coord\n * @returns {LngLat} lnglat\n * @private\n */\n coordinateLocation(coord: MercatorCoordinate) {\n return coord.toLngLat();\n }\n\n pointCoordinate(p: Point) {\n const targetZ = 0;\n // since we don't know the correct projected z value for the point,\n // unproject two points to get a line and then find the point on that\n // line with z=0\n\n const coord0 = [p.x, p.y, 0, 1];\n const coord1 = [p.x, p.y, 1, 1];\n\n vec4.transformMat4(coord0, coord0, this.pixelMatrixInverse);\n vec4.transformMat4(coord1, coord1, this.pixelMatrixInverse);\n\n const w0 = coord0[3];\n const w1 = coord1[3];\n const x0 = coord0[0] / w0;\n const x1 = coord1[0] / w1;\n const y0 = coord0[1] / w0;\n const y1 = coord1[1] / w1;\n const z0 = coord0[2] / w0;\n const z1 = coord1[2] / w1;\n\n const t = z0 === z1 ? 0 : (targetZ - z0) / (z1 - z0);\n\n return new MercatorCoordinate(\n interpolate(x0, x1, t) / this.worldSize,\n interpolate(y0, y1, t) / this.worldSize);\n }\n\n /**\n * Given a coordinate, return the screen point that corresponds to it\n * @param {Coordinate} coord\n * @returns {Point} screen point\n * @private\n */\n coordinatePoint(coord: MercatorCoordinate) {\n const p = [coord.x * this.worldSize, coord.y * this.worldSize, 0, 1];\n vec4.transformMat4(p, p, this.pixelMatrix);\n return new Point(p[0] / p[3], p[1] / p[3]);\n }\n\n /**\n * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not\n * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.\n * @returns {LngLatBounds} Returns a {@link LngLatBounds} object describing the map's geographical bounds.\n */\n getBounds(): LngLatBounds {\n return new LngLatBounds()\n .extend(this.pointLocation(new Point(0, 0)))\n .extend(this.pointLocation(new Point(this.width, 0)))\n .extend(this.pointLocation(new Point(this.width, this.height)))\n .extend(this.pointLocation(new Point(0, this.height)));\n }\n\n /**\n * Returns the maximum geographical bounds the map is constrained to, or `null` if none set.\n * @returns {LngLatBounds} {@link LngLatBounds}\n */\n getMaxBounds(): LngLatBounds | null {\n if (!this.latRange || this.latRange.length !== 2 ||\n !this.lngRange || this.lngRange.length !== 2) return null;\n\n return new LngLatBounds([this.lngRange[0], this.latRange[0]], [this.lngRange[1], this.latRange[1]]);\n }\n\n /**\n * Sets or clears the map's geographical constraints.\n * @param {LngLatBounds} bounds A {@link LngLatBounds} object describing the new geographic boundaries of the map.\n */\n setMaxBounds(bounds?: LngLatBounds) {\n if (bounds) {\n this.lngRange = [bounds.getWest(), bounds.getEast()];\n this.latRange = [bounds.getSouth(), bounds.getNorth()];\n this._constrain();\n } else {\n this.lngRange = null;\n this.latRange = [-this.maxValidLatitude, this.maxValidLatitude];\n }\n }\n\n /**\n * Calculate the posMatrix that, given a tile coordinate, would be used to display the tile on a map.\n * @param {UnwrappedTileID} unwrappedTileID;\n * @private\n */\n calculatePosMatrix(unwrappedTileID: UnwrappedTileID, aligned: boolean = false): Float32Array {\n const posMatrixKey = unwrappedTileID.key;\n const cache = aligned ? this._alignedPosMatrixCache : this._posMatrixCache;\n if (cache[posMatrixKey]) {\n return cache[posMatrixKey];\n }\n\n const canonical = unwrappedTileID.canonical;\n const scale = this.worldSize / this.zoomScale(canonical.z);\n const unwrappedX = canonical.x + Math.pow(2, canonical.z) * unwrappedTileID.wrap;\n\n const posMatrix = mat4.identity(new Float64Array(16));\n mat4.translate(posMatrix, posMatrix, [unwrappedX * scale, canonical.y * scale, 0]);\n mat4.scale(posMatrix, posMatrix, [scale / EXTENT, scale / EXTENT, 1]);\n mat4.multiply(posMatrix, aligned ? this.alignedProjMatrix : this.projMatrix, posMatrix);\n\n cache[posMatrixKey] = new Float32Array(posMatrix);\n return cache[posMatrixKey];\n }\n\n customLayerMatrix(): Array {\n return this.mercatorMatrix.slice();\n }\n\n _constrain() {\n if (!this.center || !this.width || !this.height || this._constraining) return;\n\n this._constraining = true;\n\n let minY = -90;\n let maxY = 90;\n let minX = -180;\n let maxX = 180;\n let sy, sx, x2, y2;\n const size = this.size,\n unmodified = this._unmodified;\n\n if (this.latRange) {\n const latRange = this.latRange;\n minY = mercatorYfromLat(latRange[1]) * this.worldSize;\n maxY = mercatorYfromLat(latRange[0]) * this.worldSize;\n sy = maxY - minY < size.y ? size.y / (maxY - minY) : 0;\n }\n\n if (this.lngRange) {\n const lngRange = this.lngRange;\n minX = mercatorXfromLng(lngRange[0]) * this.worldSize;\n maxX = mercatorXfromLng(lngRange[1]) * this.worldSize;\n sx = maxX - minX < size.x ? size.x / (maxX - minX) : 0;\n }\n\n const point = this.point;\n\n // how much the map should scale to fit the screen into given latitude/longitude ranges\n const s = Math.max(sx || 0, sy || 0);\n\n if (s) {\n this.center = this.unproject(new Point(\n sx ? (maxX + minX) / 2 : point.x,\n sy ? (maxY + minY) / 2 : point.y));\n this.zoom += this.scaleZoom(s);\n this._unmodified = unmodified;\n this._constraining = false;\n return;\n }\n\n if (this.latRange) {\n const y = point.y,\n h2 = size.y / 2;\n\n if (y - h2 < minY) y2 = minY + h2;\n if (y + h2 > maxY) y2 = maxY - h2;\n }\n\n if (this.lngRange) {\n const x = point.x,\n w2 = size.x / 2;\n\n if (x - w2 < minX) x2 = minX + w2;\n if (x + w2 > maxX) x2 = maxX - w2;\n }\n\n // pan the map if the screen goes off the range\n if (x2 !== undefined || y2 !== undefined) {\n this.center = this.unproject(new Point(\n x2 !== undefined ? x2 : point.x,\n y2 !== undefined ? y2 : point.y));\n }\n\n this._unmodified = unmodified;\n this._constraining = false;\n }\n\n _calcMatrices() {\n if (!this.height) return;\n\n const halfFov = this._fov / 2;\n const offset = this.centerOffset;\n this.cameraToCenterDistance = 0.5 / Math.tan(halfFov) * this.height;\n\n // Find the distance from the center point [width/2 + offset.x, height/2 + offset.y] to the\n // center top point [width/2 + offset.x, 0] in Z units, using the law of sines.\n // 1 Z unit is equivalent to 1 horizontal px at the center of the map\n // (the distance between[width/2, height/2] and [width/2 + 1, height/2])\n const groundAngle = Math.PI / 2 + this._pitch;\n const fovAboveCenter = this._fov * (0.5 + offset.y / this.height);\n const topHalfSurfaceDistance = Math.sin(fovAboveCenter) * this.cameraToCenterDistance / Math.sin(clamp(Math.PI - groundAngle - fovAboveCenter, 0.01, Math.PI - 0.01));\n const point = this.point;\n const x = point.x, y = point.y;\n\n // Calculate z distance of the farthest fragment that should be rendered.\n const furthestDistance = Math.cos(Math.PI / 2 - this._pitch) * topHalfSurfaceDistance + this.cameraToCenterDistance;\n // Add a bit extra to avoid precision problems when a fragment's distance is exactly `furthestDistance`\n const farZ = furthestDistance * 1.01;\n\n // The larger the value of nearZ is\n // - the more depth precision is available for features (good)\n // - clipping starts appearing sooner when the camera is close to 3d features (bad)\n //\n // Smaller values worked well for mapbox-gl-js but deckgl was encountering precision issues\n // when rendering it's layers using custom layers. This value was experimentally chosen and\n // seems to solve z-fighting issues in deckgl while not clipping buildings too close to the camera.\n const nearZ = this.height / 50;\n\n // matrix for conversion from location to GL coordinates (-1 .. 1)\n let m = new Float64Array(16);\n mat4.perspective(m, this._fov, this.width / this.height, nearZ, farZ);\n\n //Apply center of perspective offset\n m[8] = -offset.x * 2 / this.width;\n m[9] = offset.y * 2 / this.height;\n\n mat4.scale(m, m, [1, -1, 1]);\n mat4.translate(m, m, [0, 0, -this.cameraToCenterDistance]);\n mat4.rotateX(m, m, this._pitch);\n mat4.rotateZ(m, m, this.angle);\n mat4.translate(m, m, [-x, -y, 0]);\n\n // The mercatorMatrix can be used to transform points from mercator coordinates\n // ([0, 0] nw, [1, 1] se) to GL coordinates.\n this.mercatorMatrix = mat4.scale([], m, [this.worldSize, this.worldSize, this.worldSize]);\n\n // scale vertically to meters per pixel (inverse of ground resolution):\n mat4.scale(m, m, [1, 1, mercatorZfromAltitude(1, this.center.lat) * this.worldSize, 1]);\n\n this.projMatrix = m;\n this.invProjMatrix = mat4.invert([], this.projMatrix);\n\n // Make a second projection matrix that is aligned to a pixel grid for rendering raster tiles.\n // We're rounding the (floating point) x/y values to achieve to avoid rendering raster images to fractional\n // coordinates. Additionally, we adjust by half a pixel in either direction in case that viewport dimension\n // is an odd integer to preserve rendering to the pixel grid. We're rotating this shift based on the angle\n // of the transformation so that 0°, 90°, 180°, and 270° rasters are crisp, and adjust the shift so that\n // it is always <= 0.5 pixels.\n const xShift = (this.width % 2) / 2, yShift = (this.height % 2) / 2,\n angleCos = Math.cos(this.angle), angleSin = Math.sin(this.angle),\n dx = x - Math.round(x) + angleCos * xShift + angleSin * yShift,\n dy = y - Math.round(y) + angleCos * yShift + angleSin * xShift;\n const alignedM = new Float64Array(m);\n mat4.translate(alignedM, alignedM, [ dx > 0.5 ? dx - 1 : dx, dy > 0.5 ? dy - 1 : dy, 0 ]);\n this.alignedProjMatrix = alignedM;\n\n m = mat4.create();\n mat4.scale(m, m, [this.width / 2, -this.height / 2, 1]);\n mat4.translate(m, m, [1, -1, 0]);\n this.labelPlaneMatrix = m;\n\n m = mat4.create();\n mat4.scale(m, m, [1, -1, 1]);\n mat4.translate(m, m, [-1, -1, 0]);\n mat4.scale(m, m, [2 / this.width, 2 / this.height, 1]);\n this.glCoordMatrix = m;\n\n // matrix for conversion from location to screen coordinates\n this.pixelMatrix = mat4.multiply(new Float64Array(16), this.labelPlaneMatrix, this.projMatrix);\n\n // inverse matrix for conversion from screen coordinaes to location\n m = mat4.invert(new Float64Array(16), this.pixelMatrix);\n if (!m) throw new Error(\"failed to invert matrix\");\n this.pixelMatrixInverse = m;\n\n this._posMatrixCache = {};\n this._alignedPosMatrixCache = {};\n }\n\n maxPitchScaleFactor() {\n // calcMatrices hasn't run yet\n if (!this.pixelMatrixInverse) return 1;\n\n const coord = this.pointCoordinate(new Point(0, 0));\n const p = [coord.x * this.worldSize, coord.y * this.worldSize, 0, 1];\n const topPoint = vec4.transformMat4(p, p, this.pixelMatrix);\n return topPoint[3] / this.cameraToCenterDistance;\n }\n\n /*\n * The camera looks at the map from a 3D (lng, lat, altitude) location. Let's use `cameraLocation`\n * as the name for the location under the camera and on the surface of the earth (lng, lat, 0).\n * `cameraPoint` is the projected position of the `cameraLocation`.\n *\n * This point is useful to us because only fill-extrusions that are between `cameraPoint` and\n * the query point on the surface of the earth can extend and intersect the query.\n *\n * When the map is not pitched the `cameraPoint` is equivalent to the center of the map because\n * the camera is right above the center of the map.\n */\n getCameraPoint() {\n const pitch = this._pitch;\n const yOffset = Math.tan(pitch) * (this.cameraToCenterDistance || 1);\n return this.centerPoint.add(new Point(0, yOffset));\n }\n\n /*\n * When the map is pitched, some of the 3D features that intersect a query will not intersect\n * the query at the surface of the earth. Instead the feature may be closer and only intersect\n * the query because it extrudes into the air.\n *\n * This returns a geometry that includes all of the original query as well as all possible ares of the\n * screen where the *base* of a visible extrusion could be.\n * - For point queries, the line from the query point to the \"camera point\"\n * - For other geometries, the envelope of the query geometry and the \"camera point\"\n */\n getCameraQueryGeometry(queryGeometry: Array): Array {\n const c = this.getCameraPoint();\n\n if (queryGeometry.length === 1) {\n return [queryGeometry[0], c];\n } else {\n let minX = c.x;\n let minY = c.y;\n let maxX = c.x;\n let maxY = c.y;\n for (const p of queryGeometry) {\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 [\n new Point(minX, minY),\n new Point(maxX, minY),\n new Point(maxX, maxY),\n new Point(minX, maxY),\n new Point(minX, minY)\n ];\n }\n }\n}\n\nexport default Transform;\n","import * as glMatrix from \"./common.js\";\n/**\r\n * 2x2 Matrix\r\n * @module mat2\r\n */\n\n/**\r\n * Creates a new identity mat2\r\n *\r\n * @returns {mat2} a new 2x2 matrix\r\n */\n\nexport function create() {\n var out = new glMatrix.ARRAY_TYPE(4);\n\n if (glMatrix.ARRAY_TYPE != Float32Array) {\n out[1] = 0;\n out[2] = 0;\n }\n\n out[0] = 1;\n out[3] = 1;\n return out;\n}\n/**\r\n * Creates a new mat2 initialized with values from an existing matrix\r\n *\r\n * @param {mat2} a matrix to clone\r\n * @returns {mat2} a new 2x2 matrix\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 * Copy the values from one mat2 to another\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the source matrix\r\n * @returns {mat2} 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 a mat2 to the identity matrix\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @returns {mat2} out\r\n */\n\nexport function identity(out) {\n out[0] = 1;\n out[1] = 0;\n out[2] = 0;\n out[3] = 1;\n return out;\n}\n/**\r\n * Create a new mat2 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} m10 Component in column 1, row 0 position (index 2)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 3)\r\n * @returns {mat2} out A new 2x2 matrix\r\n */\n\nexport function fromValues(m00, m01, m10, m11) {\n var out = new glMatrix.ARRAY_TYPE(4);\n out[0] = m00;\n out[1] = m01;\n out[2] = m10;\n out[3] = m11;\n return out;\n}\n/**\r\n * Set the components of a mat2 to the given values\r\n *\r\n * @param {mat2} 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} m10 Component in column 1, row 0 position (index 2)\r\n * @param {Number} m11 Component in column 1, row 1 position (index 3)\r\n * @returns {mat2} out\r\n */\n\nexport function set(out, m00, m01, m10, m11) {\n out[0] = m00;\n out[1] = m01;\n out[2] = m10;\n out[3] = m11;\n return out;\n}\n/**\r\n * Transpose the values of a mat2\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the source matrix\r\n * @returns {mat2} 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\n // some values\n if (out === a) {\n var a1 = a[1];\n out[1] = a[2];\n out[2] = a1;\n } else {\n out[0] = a[0];\n out[1] = a[2];\n out[2] = a[1];\n out[3] = a[3];\n }\n\n return out;\n}\n/**\r\n * Inverts a mat2\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the source matrix\r\n * @returns {mat2} out\r\n */\n\nexport function invert(out, a) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3]; // Calculate the determinant\n\n var det = a0 * a3 - a2 * a1;\n\n if (!det) {\n return null;\n }\n\n det = 1.0 / det;\n out[0] = a3 * det;\n out[1] = -a1 * det;\n out[2] = -a2 * det;\n out[3] = a0 * det;\n return out;\n}\n/**\r\n * Calculates the adjugate of a mat2\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the source matrix\r\n * @returns {mat2} out\r\n */\n\nexport function adjoint(out, a) {\n // Caching this value is nessecary if out == a\n var a0 = a[0];\n out[0] = a[3];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = a0;\n return out;\n}\n/**\r\n * Calculates the determinant of a mat2\r\n *\r\n * @param {mat2} a the source matrix\r\n * @returns {Number} determinant of a\r\n */\n\nexport function determinant(a) {\n return a[0] * a[3] - a[2] * a[1];\n}\n/**\r\n * Multiplies two mat2's\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the first operand\r\n * @param {mat2} b the second operand\r\n * @returns {mat2} out\r\n */\n\nexport function multiply(out, 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 out[0] = a0 * b0 + a2 * b1;\n out[1] = a1 * b0 + a3 * b1;\n out[2] = a0 * b2 + a2 * b3;\n out[3] = a1 * b2 + a3 * b3;\n return out;\n}\n/**\r\n * Rotates a mat2 by the given angle\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the matrix to rotate\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat2} out\r\n */\n\nexport function rotate(out, a, rad) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n out[0] = a0 * c + a2 * s;\n out[1] = a1 * c + a3 * s;\n out[2] = a0 * -s + a2 * c;\n out[3] = a1 * -s + a3 * c;\n return out;\n}\n/**\r\n * Scales the mat2 by the dimensions in the given vec2\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the matrix to rotate\r\n * @param {vec2} v the vec2 to scale the matrix by\r\n * @returns {mat2} out\r\n **/\n\nexport function scale(out, a, v) {\n var a0 = a[0],\n a1 = a[1],\n a2 = a[2],\n a3 = a[3];\n var v0 = v[0],\n v1 = v[1];\n out[0] = a0 * v0;\n out[1] = a1 * v0;\n out[2] = a2 * v1;\n out[3] = a3 * v1;\n return out;\n}\n/**\r\n * Creates a matrix from a given angle\r\n * This is equivalent to (but much faster than):\r\n *\r\n * mat2.identity(dest);\r\n * mat2.rotate(dest, dest, rad);\r\n *\r\n * @param {mat2} out mat2 receiving operation result\r\n * @param {Number} rad the angle to rotate the matrix by\r\n * @returns {mat2} out\r\n */\n\nexport function fromRotation(out, rad) {\n var s = Math.sin(rad);\n var c = Math.cos(rad);\n out[0] = c;\n out[1] = s;\n out[2] = -s;\n out[3] = c;\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 * mat2.identity(dest);\r\n * mat2.scale(dest, dest, vec);\r\n *\r\n * @param {mat2} out mat2 receiving operation result\r\n * @param {vec2} v Scaling vector\r\n * @returns {mat2} 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] = v[1];\n return out;\n}\n/**\r\n * Returns a string representation of a mat2\r\n *\r\n * @param {mat2} 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 \"mat2(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\r\n * Returns Frobenius norm of a mat2\r\n *\r\n * @param {mat2} 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]);\n}\n/**\r\n * Returns L, D and U matrices (Lower triangular, Diagonal and Upper triangular) by factorizing the input matrix\r\n * @param {mat2} L the lower triangular matrix\r\n * @param {mat2} D the diagonal matrix\r\n * @param {mat2} U the upper triangular matrix\r\n * @param {mat2} a the input matrix to factorize\r\n */\n\nexport function LDU(L, D, U, a) {\n L[2] = a[2] / a[0];\n U[0] = a[0];\n U[1] = a[1];\n U[3] = a[3] - L[2] * U[1];\n return [L, D, U];\n}\n/**\r\n * Adds two mat2's\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the first operand\r\n * @param {mat2} b the second operand\r\n * @returns {mat2} 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 matrix b from matrix a\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the first operand\r\n * @param {mat2} b the second operand\r\n * @returns {mat2} 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 * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {mat2} a The first matrix.\r\n * @param {mat2} 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];\n}\n/**\r\n * Returns whether or not the matrices have approximately the same elements in the same position.\r\n *\r\n * @param {mat2} a The first matrix.\r\n * @param {mat2} 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 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 * Multiply each element of the matrix by a scalar.\r\n *\r\n * @param {mat2} out the receiving matrix\r\n * @param {mat2} a the matrix to scale\r\n * @param {Number} b amount to scale the matrix's elements by\r\n * @returns {mat2} 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 return out;\n}\n/**\r\n * Adds two mat2's after multiplying each element of the second operand by a scalar value.\r\n *\r\n * @param {mat2} out the receiving vector\r\n * @param {mat2} a the first operand\r\n * @param {mat2} b the second operand\r\n * @param {Number} scale the amount to scale b's elements by before adding\r\n * @returns {mat2} 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 return out;\n}\n/**\r\n * Alias for {@link mat2.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Alias for {@link mat2.subtract}\r\n * @function\r\n */\n\nexport var sub = subtract;","// @flow\n\nimport {bindAll} from '../util/util';\nimport window from '../util/window';\nimport throttle from '../util/throttle';\n\nimport type Map from './map';\n\n/*\n * Adds the map's position to its page's location hash.\n * Passed as an option to the map object.\n *\n * @returns {Hash} `this`\n */\nclass Hash {\n _map: Map;\n _updateHash: () => ?TimeoutID;\n _hashName: ?string;\n\n constructor(hashName: ?string) {\n this._hashName = hashName && encodeURIComponent(hashName);\n bindAll([\n '_getCurrentHash',\n '_onHashChange',\n '_updateHash'\n ], this);\n\n // Mobile Safari doesn't allow updating the hash more than 100 times per 30 seconds.\n this._updateHash = throttle(this._updateHashUnthrottled.bind(this), 30 * 1000 / 100);\n }\n\n /*\n * Map element to listen for coordinate changes\n *\n * @param {Object} map\n * @returns {Hash} `this`\n */\n addTo(map: Map) {\n this._map = map;\n window.addEventListener('hashchange', this._onHashChange, false);\n this._map.on('moveend', this._updateHash);\n return this;\n }\n\n /*\n * Removes hash\n *\n * @returns {Popup} `this`\n */\n remove() {\n window.removeEventListener('hashchange', this._onHashChange, false);\n this._map.off('moveend', this._updateHash);\n clearTimeout(this._updateHash());\n\n delete this._map;\n return this;\n }\n\n getHashString(mapFeedback?: boolean) {\n const center = this._map.getCenter(),\n zoom = Math.round(this._map.getZoom() * 100) / 100,\n // derived from equation: 512px * 2^z / 360 / 10^d < 0.5px\n precision = Math.ceil((zoom * Math.LN2 + Math.log(512 / 360 / 0.5)) / Math.LN10),\n m = Math.pow(10, precision),\n lng = Math.round(center.lng * m) / m,\n lat = Math.round(center.lat * m) / m,\n bearing = this._map.getBearing(),\n pitch = this._map.getPitch();\n let hash = '';\n if (mapFeedback) {\n // new map feedback site has some constraints that don't allow\n // us to use the same hash format as we do for the Map hash option.\n hash += `/${lng}/${lat}/${zoom}`;\n } else {\n hash += `${zoom}/${lat}/${lng}`;\n }\n\n if (bearing || pitch) hash += (`/${Math.round(bearing * 10) / 10}`);\n if (pitch) hash += (`/${Math.round(pitch)}`);\n\n if (this._hashName) {\n const hashName = this._hashName;\n let found = false;\n const parts = window.location.hash.slice(1).split('&').map(part => {\n const key = part.split('=')[0];\n if (key === hashName) {\n found = true;\n return `${key}=${hash}`;\n }\n return part;\n }).filter(a => a);\n if (!found) {\n parts.push(`${hashName}=${hash}`);\n }\n return `#${parts.join('&')}`;\n }\n\n return `#${hash}`;\n }\n\n _getCurrentHash() {\n // Get the current hash from location, stripped from its number sign\n const hash = window.location.hash.replace('#', '');\n if (this._hashName) {\n // Split the parameter-styled hash into parts and find the value we need\n let keyval;\n hash.split('&').map(\n part => part.split('=')\n ).forEach(part => {\n if (part[0] === this._hashName) {\n keyval = part;\n }\n });\n return (keyval ? keyval[1] || '' : '').split('/');\n }\n return hash.split('/');\n }\n\n _onHashChange() {\n const loc = this._getCurrentHash();\n if (loc.length >= 3 && !loc.some(v => isNaN(v))) {\n const bearing = this._map.dragRotate.isEnabled() && this._map.touchZoomRotate.isEnabled() ? +(loc[3] || 0) : this._map.getBearing();\n this._map.jumpTo({\n center: [+loc[2], +loc[1]],\n zoom: +loc[0],\n bearing,\n pitch: +(loc[4] || 0)\n });\n return true;\n }\n return false;\n }\n\n _updateHashUnthrottled() {\n // Replace if already present, else append the updated hash string\n const location = window.location.href.replace(/(#.+)?$/, this.getHashString());\n try {\n window.history.replaceState(window.history.state, null, location);\n } catch (SecurityError) {\n // IE11 does not allow this if the page is within an iframe created\n // with iframe.contentWindow.document.write(...).\n // https://github.com/mapbox/mapbox-gl-js/issues/7410\n }\n }\n\n}\n\nexport default Hash;\n","// @flow strict\n\n/**\n * Throttle the given function to run at most every `period` milliseconds.\n * @private\n */\nexport default function throttle(fn: () => void, time: number): () => ?TimeoutID {\n let pending = false;\n let timerId: ?TimeoutID = null;\n\n const later = () => {\n timerId = null;\n if (pending) {\n fn();\n timerId = setTimeout(later, time);\n pending = false;\n }\n };\n\n return () => {\n pending = true;\n if (!timerId) {\n later();\n }\n return timerId;\n };\n}\n","// @flow\n\nimport browser from '../util/browser';\nimport type Map from './map';\nimport {bezier, clamp, extend} from '../util/util';\nimport Point from '@mapbox/point-geometry';\nimport type {DragPanOptions} from './handler/shim/drag_pan';\n\nconst defaultInertiaOptions = {\n linearity: 0.3,\n easing: bezier(0, 0, 0.3, 1),\n};\n\nconst defaultPanInertiaOptions = extend({\n deceleration: 2500,\n maxSpeed: 1400\n}, defaultInertiaOptions);\n\nconst defaultZoomInertiaOptions = extend({\n deceleration: 20,\n maxSpeed: 1400\n}, defaultInertiaOptions);\n\nconst defaultBearingInertiaOptions = extend({\n deceleration: 1000,\n maxSpeed: 360\n}, defaultInertiaOptions);\n\nconst defaultPitchInertiaOptions = extend({\n deceleration: 1000,\n maxSpeed: 90\n}, defaultInertiaOptions);\n\nexport type InertiaOptions = {\n linearity: number;\n easing: (t: number) => number;\n deceleration: number;\n maxSpeed: number;\n};\n\nexport type InputEvent = MouseEvent | TouchEvent | KeyboardEvent | WheelEvent;\n\nexport default class HandlerInertia {\n _map: Map;\n _inertiaBuffer: Array<{ time: number, settings: Object }>;\n\n constructor(map: Map) {\n this._map = map;\n this.clear();\n }\n\n clear() {\n this._inertiaBuffer = [];\n }\n\n record(settings: any) {\n this._drainInertiaBuffer();\n this._inertiaBuffer.push({time: browser.now(), settings});\n }\n\n _drainInertiaBuffer() {\n const inertia = this._inertiaBuffer,\n now = browser.now(),\n cutoff = 160; //msec\n\n while (inertia.length > 0 && now - inertia[0].time > cutoff)\n inertia.shift();\n }\n\n _onMoveEnd(panInertiaOptions?: DragPanOptions) {\n this._drainInertiaBuffer();\n if (this._inertiaBuffer.length < 2) {\n return;\n }\n\n const deltas = {\n zoom: 0,\n bearing: 0,\n pitch: 0,\n pan: new Point(0, 0),\n pinchAround: undefined,\n around: undefined\n };\n\n for (const {settings} of this._inertiaBuffer) {\n deltas.zoom += settings.zoomDelta || 0;\n deltas.bearing += settings.bearingDelta || 0;\n deltas.pitch += settings.pitchDelta || 0;\n if (settings.panDelta) deltas.pan._add(settings.panDelta);\n if (settings.around) deltas.around = settings.around;\n if (settings.pinchAround) deltas.pinchAround = settings.pinchAround;\n }\n\n const lastEntry = this._inertiaBuffer[this._inertiaBuffer.length - 1];\n const duration = (lastEntry.time - this._inertiaBuffer[0].time);\n\n const easeOptions = {};\n\n if (deltas.pan.mag()) {\n const result = calculateEasing(deltas.pan.mag(), duration, extend({}, defaultPanInertiaOptions, panInertiaOptions || {}));\n easeOptions.offset = deltas.pan.mult(result.amount / deltas.pan.mag());\n easeOptions.center = this._map.transform.center;\n extendDuration(easeOptions, result);\n }\n\n if (deltas.zoom) {\n const result = calculateEasing(deltas.zoom, duration, defaultZoomInertiaOptions);\n easeOptions.zoom = this._map.transform.zoom + result.amount;\n extendDuration(easeOptions, result);\n }\n\n if (deltas.bearing) {\n const result = calculateEasing(deltas.bearing, duration, defaultBearingInertiaOptions);\n easeOptions.bearing = this._map.transform.bearing + clamp(result.amount, -179, 179);\n extendDuration(easeOptions, result);\n }\n\n if (deltas.pitch) {\n const result = calculateEasing(deltas.pitch, duration, defaultPitchInertiaOptions);\n easeOptions.pitch = this._map.transform.pitch + result.amount;\n extendDuration(easeOptions, result);\n }\n\n if (easeOptions.zoom || easeOptions.bearing) {\n const last = deltas.pinchAround === undefined ? deltas.around : deltas.pinchAround;\n easeOptions.around = last ? this._map.unproject(last) : this._map.getCenter();\n }\n\n this.clear();\n return extend(easeOptions, {\n noMoveStart: true\n });\n\n }\n}\n\n// Unfortunately zoom, bearing, etc can't have different durations and easings so\n// we need to choose one. We use the longest duration and it's corresponding easing.\nfunction extendDuration(easeOptions, result) {\n if (!easeOptions.duration || easeOptions.duration < result.duration) {\n easeOptions.duration = result.duration;\n easeOptions.easing = result.easing;\n }\n}\n\nfunction calculateEasing(amount, inertiaDuration: number, inertiaOptions) {\n const {maxSpeed, linearity, deceleration} = inertiaOptions;\n const speed = clamp(\n amount * linearity / (inertiaDuration / 1000),\n -maxSpeed,\n maxSpeed);\n const duration = Math.abs(speed) / (deceleration * linearity);\n return {\n easing: inertiaOptions.easing,\n duration: duration * 1000,\n amount: speed * (duration / 2)\n };\n}\n","// @flow\n\nimport {Event} from '../util/evented';\n\nimport DOM from '../util/dom';\nimport Point from '@mapbox/point-geometry';\nimport {extend} from '../util/util';\n\nimport type Map from './map';\nimport type LngLat from '../geo/lng_lat';\n\n/**\n * `MapMouseEvent` is the event type for mouse-related map events.\n * @extends {Object}\n * @example\n * // The `click` event is an example of a `MapMouseEvent`.\n * // Set up an event listener on the map.\n * map.on('click', function(e) {\n * // The event object (e) contains information like the\n * // coordinates of the point on the map that was clicked.\n * console.log('A click event has occurred at ' + e.lngLat);\n * });\n */\nexport class MapMouseEvent extends Event {\n /**\n * The event type (one of {@link Map.event:mousedown},\n * {@link Map.event:mouseup},\n * {@link Map.event:click},\n * {@link Map.event:dblclick},\n * {@link Map.event:mousemove},\n * {@link Map.event:mouseover},\n * {@link Map.event:mouseenter},\n * {@link Map.event:mouseleave},\n * {@link Map.event:mouseout},\n * {@link Map.event:contextmenu}).\n */\n type: 'mousedown'\n | 'mouseup'\n | 'click'\n | 'dblclick'\n | 'mousemove'\n | 'mouseover'\n | 'mouseenter'\n | 'mouseleave'\n | 'mouseout'\n | 'contextmenu';\n\n /**\n * The `Map` object that fired the event.\n */\n target: Map;\n\n /**\n * The DOM event which caused the map event.\n */\n originalEvent: MouseEvent;\n\n /**\n * The pixel coordinates of the mouse cursor, relative to the map and measured from the top left corner.\n */\n point: Point;\n\n /**\n * The geographic location on the map of the mouse cursor.\n */\n lngLat: LngLat;\n\n /**\n * Prevents subsequent default processing of the event by the map.\n *\n * Calling this method will prevent the following default map behaviors:\n *\n * * On `mousedown` events, the behavior of {@link DragPanHandler}\n * * On `mousedown` events, the behavior of {@link DragRotateHandler}\n * * On `mousedown` events, the behavior of {@link BoxZoomHandler}\n * * On `dblclick` events, the behavior of {@link DoubleClickZoomHandler}\n *\n */\n preventDefault() {\n this._defaultPrevented = true;\n }\n\n /**\n * `true` if `preventDefault` has been called.\n * @private\n */\n get defaultPrevented(): boolean {\n return this._defaultPrevented;\n }\n\n _defaultPrevented: boolean;\n\n /**\n * @private\n */\n constructor(type: string, map: Map, originalEvent: MouseEvent, data: Object = {}) {\n const point = DOM.mousePos(map.getCanvasContainer(), originalEvent);\n const lngLat = map.unproject(point);\n super(type, extend({point, lngLat, originalEvent}, data));\n this._defaultPrevented = false;\n this.target = map;\n }\n}\n\n/**\n * `MapTouchEvent` is the event type for touch-related map events.\n * @extends {Object}\n */\nexport class MapTouchEvent extends Event {\n /**\n * The event type.\n */\n type: 'touchstart'\n | 'touchend'\n | 'touchcancel';\n\n /**\n * The `Map` object that fired the event.\n */\n target: Map;\n\n /**\n * The DOM event which caused the map event.\n */\n originalEvent: TouchEvent;\n\n /**\n * The geographic location on the map of the center of the touch event points.\n */\n lngLat: LngLat;\n\n /**\n * The pixel coordinates of the center of the touch event points, relative to the map and measured from the top left\n * corner.\n */\n point: Point;\n\n /**\n * The array of pixel coordinates corresponding to a\n * [touch event's `touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) property.\n */\n points: Array;\n\n /**\n * The geographical locations on the map corresponding to a\n * [touch event's `touches`](https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/touches) property.\n */\n lngLats: Array;\n\n /**\n * Prevents subsequent default processing of the event by the map.\n *\n * Calling this method will prevent the following default map behaviors:\n *\n * * On `touchstart` events, the behavior of {@link DragPanHandler}\n * * On `touchstart` events, the behavior of {@link TouchZoomRotateHandler}\n *\n */\n preventDefault() {\n this._defaultPrevented = true;\n }\n\n /**\n * `true` if `preventDefault` has been called.\n * @private\n */\n get defaultPrevented(): boolean {\n return this._defaultPrevented;\n }\n\n _defaultPrevented: boolean;\n\n /**\n * @private\n */\n constructor(type: string, map: Map, originalEvent: TouchEvent) {\n const touches = type === \"touchend\" ? originalEvent.changedTouches : originalEvent.touches;\n const points = DOM.touchPos(map.getCanvasContainer(), touches);\n const lngLats = points.map((t) => map.unproject(t));\n const point = points.reduce((prev, curr, i, arr) => {\n return prev.add(curr.div(arr.length));\n }, new Point(0, 0));\n const lngLat = map.unproject(point);\n super(type, {points, point, lngLats, lngLat, originalEvent});\n this._defaultPrevented = false;\n }\n}\n\n/**\n * `MapWheelEvent` is the event type for the `wheel` map event.\n * @extends {Object}\n */\nexport class MapWheelEvent extends Event {\n /**\n * The event type.\n */\n type: 'wheel';\n\n /**\n * The `Map` object that fired the event.\n */\n target: Map;\n\n /**\n * The DOM event which caused the map event.\n */\n originalEvent: WheelEvent;\n\n /**\n * Prevents subsequent default processing of the event by the map.\n *\n * Calling this method will prevent the the behavior of {@link ScrollZoomHandler}.\n */\n preventDefault() {\n this._defaultPrevented = true;\n }\n\n /**\n * `true` if `preventDefault` has been called.\n * @private\n */\n get defaultPrevented(): boolean {\n return this._defaultPrevented;\n }\n\n _defaultPrevented: boolean;\n\n /**\n * @private\n */\n constructor(type: string, map: Map, originalEvent: WheelEvent) {\n super(type, {originalEvent});\n this._defaultPrevented = false;\n }\n}\n\n/**\n * A `MapBoxZoomEvent` is the event type for the boxzoom-related map events emitted by the {@link BoxZoomHandler}.\n *\n * @typedef {Object} MapBoxZoomEvent\n * @property {MouseEvent} originalEvent The DOM event that triggered the boxzoom event. Can be a `MouseEvent` or `KeyboardEvent`\n * @property {string} type The type of boxzoom event. One of `boxzoomstart`, `boxzoomend` or `boxzoomcancel`\n * @property {Map} target The `Map` instance that triggerred the event\n */\nexport type MapBoxZoomEvent = {\n type: 'boxzoomstart'\n | 'boxzoomend'\n | 'boxzoomcancel',\n target: Map,\n originalEvent: MouseEvent\n};\n\n/**\n * A `MapDataEvent` object is emitted with the {@link Map.event:data}\n * and {@link Map.event:dataloading} events. Possible values for\n * `dataType`s are:\n *\n * - `'source'`: The non-tile data associated with any source\n * - `'style'`: The [style](https://www.mapbox.com/mapbox-gl-style-spec/) used by the map\n *\n * @typedef {Object} MapDataEvent\n * @property {string} type The event type.\n * @property {string} dataType The type of data that has changed. One of `'source'`, `'style'`.\n * @property {boolean} [isSourceLoaded] True if the event has a `dataType` of `source` and the source has no outstanding network requests.\n * @property {Object} [source] The [style spec representation of the source](https://www.mapbox.com/mapbox-gl-style-spec/#sources) if the event has a `dataType` of `source`.\n * @property {string} [sourceDataType] Included if the event has a `dataType` of `source` and the event signals\n * that internal data has been received or changed. Possible values are `metadata`, `content` and `visibility`.\n * @property {Object} [tile] The tile being loaded or changed, if the event has a `dataType` of `source` and\n * the event is related to loading of a tile.\n * @property {Coordinate} [coord] The coordinate of the tile if the event has a `dataType` of `source` and\n * the event is related to loading of a tile.\n * @example\n * // The sourcedata event is an example of MapDataEvent.\n * // Set up an event listener on the map.\n * map.on('sourcedata', function(e) {\n * if (e.isSourceLoaded) {\n * // Do something when the source has finished loading\n * }\n * });\n */\nexport type MapDataEvent = {\n type: string,\n dataType: string\n};\n\nexport type MapContextEvent = {\n type: 'webglcontextlost' | 'webglcontextrestored',\n originalEvent: WebGLContextEvent\n}\n\nexport type MapEvent =\n /**\n * Fired when a pointing device (usually a mouse) is pressed within the map.\n *\n * **Note:** This event is compatible with the optional `layerId` parameter.\n * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the\n * the cursor is pressed while inside a visible portion of the specifed layer.\n *\n * @event mousedown\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener\n * map.on('mousedown', function() {\n * console.log('A mousedown event has occurred.');\n * });\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener for a specific layer\n * map.on('mousedown', 'poi-label', function() {\n * console.log('A mousedown event has occurred on a visible portion of the poi-label layer.');\n * });\n * @see [Highlight features within a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)\n * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)\n */\n | 'mousedown'\n\n /**\n * Fired when a pointing device (usually a mouse) is released within the map.\n *\n * **Note:** This event is compatible with the optional `layerId` parameter.\n * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the\n * the cursor is released while inside a visible portion of the specifed layer.\n *\n * @event mouseup\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener\n * map.on('mouseup', function() {\n * console.log('A mouseup event has occurred.');\n * });\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener for a specific layer\n * map.on('mouseup', 'poi-label', function() {\n * console.log('A mouseup event has occurred on a visible portion of the poi-label layer.');\n * });\n * @see [Highlight features within a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)\n * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)\n */\n | 'mouseup'\n\n /**\n * Fired when a pointing device (usually a mouse) is moved within the map.\n * As you move the cursor across a web page containing a map,\n * the event will fire each time it enters the map or any child elements.\n *\n * **Note:** This event is compatible with the optional `layerId` parameter.\n * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the\n * the cursor is moved inside a visible portion of the specifed layer.\n *\n * @event mouseover\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener\n * map.on('mouseover', function() {\n * console.log('A mouseover event has occurred.');\n * });\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener for a specific layer\n * map.on('mouseover', 'poi-label', function() {\n * console.log('A mouseover event has occurred on a visible portion of the poi-label layer.');\n * });\n * @see [Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/)\n * @see [Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/)\n * @see [Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)\n */\n | 'mouseover'\n\n /**\n * Fired when a pointing device (usually a mouse) is moved while the cursor is inside the map.\n * As you move the cursor across the map, the event will fire every time the cursor changes position within the map.\n *\n * **Note:** This event is compatible with the optional `layerId` parameter.\n * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the\n * the cursor is inside a visible portion of the specified layer.\n *\n * @event mousemove\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener\n * map.on('mousemove', function() {\n * console.log('A mousemove event has occurred.');\n * });\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener for a specific layer\n * map.on('mousemove', 'poi-label', function() {\n * console.log('A mousemove event has occurred on a visible portion of the poi-label layer.');\n * });\n * @see [Get coordinates of the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/mouse-position/)\n * @see [Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/)\n * @see [Display a popup on over](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)\n */\n | 'mousemove'\n\n /**\n * Fired when a pointing device (usually a mouse) is pressed and released at the same point on the map.\n *\n * **Note:** This event is compatible with the optional `layerId` parameter.\n * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only when the\n * point that is pressed and released contains a visible portion of the specifed layer.\n *\n * @event click\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener\n * map.on('click', function(e) {\n * console.log('A click event has occurred at ' + e.lngLat);\n * });\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener for a specific layer\n * map.on('click', 'poi-label', function(e) {\n * console.log('A click event has occurred on a visible portion of the poi-label layer at ' + e.lngLat);\n * });\n * @see [Measure distances](https://www.mapbox.com/mapbox-gl-js/example/measure/)\n * @see [Center the map on a clicked symbol](https://www.mapbox.com/mapbox-gl-js/example/center-on-symbol/)\n */\n | 'click'\n\n /**\n * Fired when a pointing device (usually a mouse) is pressed and released twice at the same point on\n * the map in rapid succession.\n *\n * **Note:** This event is compatible with the optional `layerId` parameter.\n * If `layerId` is included as the second argument in {@link Map#on}, the event listener will fire only\n * when the point that is clicked twice contains a visible portion of the specifed layer.\n *\n * @event dblclick\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener\n * map.on('dblclick', function(e) {\n * console.log('A dblclick event has occurred at ' + e.lngLat);\n * });\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener for a specific layer\n * map.on('dblclick', 'poi-label', function(e) {\n * console.log('A dblclick event has occurred on a visible portion of the poi-label layer at ' + e.lngLat);\n * });\n */\n | 'dblclick'\n\n /**\n * Fired when a pointing device (usually a mouse) enters a visible portion of a specified layer from\n * outside that layer or outside the map canvas.\n *\n * **Important:** This event can only be listened for when {@link Map#on} includes three arguments,\n * where the second argument specifies the desired layer.\n *\n * @event mouseenter\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener\n * map.on('mouseenter', 'water', function() {\n * console.log('A mouseenter event occurred on a visible portion of the water layer.');\n * });\n * @see [Center the map on a clicked symbol](https://docs.mapbox.com/mapbox-gl-js/example/center-on-symbol/)\n * @see [Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/)\n */\n | 'mouseenter'\n\n /**\n * Fired when a pointing device (usually a mouse) leaves a visible portion of a specified layer, or leaves\n * the map canvas.\n *\n * **Important:** This event can only be listened for when {@link Map#on} includes three arguements,\n * where the second argument specifies the desired layer.\n *\n * @event mouseleave\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when the pointing device leaves\n * // a visible portion of the specified layer.\n * map.on('mouseleave', 'water', function() {\n * console.log('A mouseleave event occurred.');\n * });\n * @see [Highlight features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/hover-styles/)\n * @see [Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/)\n */\n | 'mouseleave'\n\n /**\n * Fired when a point device (usually a mouse) leaves the map's canvas.\n *\n * @event mouseout\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when the pointing device leave's\n * // the map's canvas.\n * map.on('mouseout', function() {\n * console.log('A mouseout event occurred.');\n * });\n */\n | 'mouseout'\n\n /**\n * Fired when the right button of the mouse is clicked or the context menu key is pressed within the map.\n *\n * @event contextmenu\n * @memberof Map\n * @instance\n * @property {MapMouseEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when the right mouse button is\n * // pressed within the map.\n * map.on('contextmenu', function() {\n * console.log('A contextmenu event occurred.');\n * });\n */\n | 'contextmenu'\n\n /**\n * Fired when a [`wheel`](https://developer.mozilla.org/en-US/docs/Web/Events/wheel) event occurs within the map.\n *\n * @event wheel\n * @memberof Map\n * @instance\n * @property {MapWheelEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when a wheel event occurs within the map.\n * map.on('wheel', function() {\n * console.log('A wheel event occurred.');\n * });\n */\n | 'wheel'\n\n /**\n * Fired when a [`touchstart`](https://developer.mozilla.org/en-US/docs/Web/Events/touchstart) event occurs within the map.\n *\n * @event touchstart\n * @memberof Map\n * @instance\n * @property {MapTouchEvent} data\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when a touchstart event occurs within the map.\n * map.on('touchstart', function() {\n * console.log('A touchstart event occurred.');\n * });\n * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)\n */\n | 'touchstart'\n\n /**\n * Fired when a [`touchend`](https://developer.mozilla.org/en-US/docs/Web/Events/touchend) event occurs within the map.\n *\n * @event touchend\n * @memberof Map\n * @instance\n * @property {MapTouchEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when a touchstart event occurs within the map.\n * map.on('touchstart', function() {\n * console.log('A touchstart event occurred.');\n * });\n * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)\n */\n | 'touchend'\n\n /**\n * Fired when a [`touchmove`](https://developer.mozilla.org/en-US/docs/Web/Events/touchmove) event occurs within the map.\n *\n * @event touchmove\n * @memberof Map\n * @instance\n * @property {MapTouchEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when a touchmove event occurs within the map.\n * map.on('touchmove', function() {\n * console.log('A touchmove event occurred.');\n * });\n * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)\n */\n | 'touchmove'\n\n /**\n * Fired when a [`touchcancel`](https://developer.mozilla.org/en-US/docs/Web/Events/touchcancel) event occurs within the map.\n *\n * @event touchcancel\n * @memberof Map\n * @instance\n * @property {MapTouchEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when a touchcancel event occurs within the map.\n * map.on('touchcancel', function() {\n * console.log('A touchcancel event occurred.');\n * });\n */\n | 'touchcancel'\n\n /**\n * Fired just before the map begins a transition from one\n * view to another, as the result of either user interaction or methods such as {@link Map#jumpTo}.\n *\n * @event movestart\n * @memberof Map\n * @instance\n * @property {{originalEvent: DragEvent}} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // just before the map begins a transition\n * // from one view to another.\n * map.on('movestart', function() {\n * console.log('A movestart` event occurred.');\n * });\n */\n | 'movestart'\n\n /**\n * Fired repeatedly during an animated transition from one view to\n * another, as the result of either user interaction or methods such as {@link Map#flyTo}.\n *\n * @event move\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // repeatedly during an animated transition.\n * map.on('move', function() {\n * console.log('A move event occurred.');\n * });\n * @see [Display HTML clusters with custom properties](https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/)\n * @see [Filter features within map view](https://docs.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)\n */\n | 'move'\n\n /**\n * Fired just after the map completes a transition from one\n * view to another, as the result of either user interaction or methods such as {@link Map#jumpTo}.\n *\n * @event moveend\n * @memberof Map\n * @instance\n * @property {{originalEvent: DragEvent}} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // just after the map completes a transition.\n * map.on('moveend', function() {\n * console.log('A moveend event occurred.');\n * });\n * @see [Play map locations as a slideshow](https://www.mapbox.com/mapbox-gl-js/example/playback-locations/)\n * @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)\n * @see [Display HTML clusters with custom properties](https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/)\n */\n | 'moveend'\n\n /**\n * Fired when a \"drag to pan\" interaction starts. See {@link DragPanHandler}.\n *\n * @event dragstart\n * @memberof Map\n * @instance\n * @property {{originalEvent: DragEvent}} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when a \"drag to pan\" interaction starts.\n * map.on('dragstart', function() {\n * console.log('A dragstart event occurred.');\n * });\n */\n | 'dragstart'\n\n /**\n * Fired repeatedly during a \"drag to pan\" interaction. See {@link DragPanHandler}.\n *\n * @event drag\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // repeatedly during a \"drag to pan\" interaction.\n * map.on('drag', function() {\n * console.log('A drag event occurred.');\n * });\n */\n | 'drag'\n\n /**\n * Fired when a \"drag to pan\" interaction ends. See {@link DragPanHandler}.\n *\n * @event dragend\n * @memberof Map\n * @instance\n * @property {{originalEvent: DragEvent}} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when a \"drag to pan\" interaction ends.\n * map.on('dragend', function() {\n * console.log('A dragend event occurred.');\n * });\n * @see [Create a draggable marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-marker/)\n */\n | 'dragend'\n\n /**\n * Fired just before the map begins a transition from one zoom level to another,\n * as the result of either user interaction or methods such as {@link Map#flyTo}.\n *\n * @event zoomstart\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // just before a zoom transition starts.\n * map.on('zoomstart', function() {\n * console.log('A zoomstart event occurred.');\n * });\n */\n | 'zoomstart'\n\n /**\n * Fired repeatedly during an animated transition from one zoom level to another,\n * as the result of either user interaction or methods such as {@link Map#flyTo}.\n *\n * @event zoom\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // repeatedly during a zoom transition.\n * map.on('zoom', function() {\n * console.log('A zoom event occurred.');\n * });\n * @see [Update a choropleth layer by zoom level](https://www.mapbox.com/mapbox-gl-js/example/updating-choropleth/)\n */\n | 'zoom'\n\n /**\n * Fired just after the map completes a transition from one zoom level to another,\n * as the result of either user interaction or methods such as {@link Map#flyTo}.\n *\n * @event zoomend\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // just after a zoom transition finishes.\n * map.on('zoomend', function() {\n * console.log('A zoomend event occurred.');\n * });\n */\n | 'zoomend'\n\n /**\n * Fired when a \"drag to rotate\" interaction starts. See {@link DragRotateHandler}.\n *\n * @event rotatestart\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // just before a \"drag to rotate\" interaction starts.\n * map.on('rotatestart', function() {\n * console.log('A rotatestart event occurred.');\n * });\n */\n | 'rotatestart'\n\n /**\n * Fired repeatedly during a \"drag to rotate\" interaction. See {@link DragRotateHandler}.\n *\n * @event rotate\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // repeatedly during \"drag to rotate\" interaction.\n * map.on('rotate', function() {\n * console.log('A rotate event occurred.');\n * });\n */\n | 'rotate'\n\n /**\n * Fired when a \"drag to rotate\" interaction ends. See {@link DragRotateHandler}.\n *\n * @event rotateend\n * @memberof Map\n * @instance\n * @property {MapMouseEvent | MapTouchEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // just after a \"drag to rotate\" interaction ends.\n * map.on('rotateend', function() {\n * console.log('A rotateend event occurred.');\n * });\n */\n | 'rotateend'\n\n /**\n * Fired whenever the map's pitch (tilt) begins a change as\n * the result of either user interaction or methods such as {@link Map#flyTo} .\n *\n * @event pitchstart\n * @memberof Map\n * @instance\n * @property {MapEventData} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // just before a pitch (tilt) transition starts.\n * map.on('pitchstart', function() {\n * console.log('A pitchstart event occurred.');\n * });\n */\n | 'pitchstart'\n\n /**\n * Fired repeatedly during the map's pitch (tilt) animation between\n * one state and another as the result of either user interaction\n * or methods such as {@link Map#flyTo}.\n *\n * @event pitch\n * @memberof Map\n * @instance\n * @property {MapEventData} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // repeatedly during a pitch (tilt) transition.\n * map.on('pitch', function() {\n * console.log('A pitch event occurred.');\n * });\n */\n | 'pitch'\n\n /**\n * Fired immediately after the map's pitch (tilt) finishes changing as\n * the result of either user interaction or methods such as {@link Map#flyTo}.\n *\n * @event pitchend\n * @memberof Map\n * @instance\n * @property {MapEventData} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // just after a pitch (tilt) transition ends.\n * map.on('pitchend', function() {\n * console.log('A pitchend event occurred.');\n * });\n */\n | 'pitchend'\n\n /**\n * Fired when a \"box zoom\" interaction starts. See {@link BoxZoomHandler}.\n *\n * @event boxzoomstart\n * @memberof Map\n * @instance\n * @property {MapBoxZoomEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // just before a \"box zoom\" interaction starts.\n * map.on('boxzoomstart', function() {\n * console.log('A boxzoomstart event occurred.');\n * });\n */\n | 'boxzoomstart'\n\n /**\n * Fired when a \"box zoom\" interaction ends. See {@link BoxZoomHandler}.\n *\n * @event boxzoomend\n * @memberof Map\n * @instance\n * @type {Object}\n * @property {MapBoxZoomEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // just after a \"box zoom\" interaction ends.\n * map.on('boxzoomend', function() {\n * console.log('A boxzoomend event occurred.');\n * });\n */\n | 'boxzoomend'\n\n /**\n * Fired when the user cancels a \"box zoom\" interaction, or when the bounding box does not meet the minimum size threshold.\n * See {@link BoxZoomHandler}.\n *\n * @event boxzoomcancel\n * @memberof Map\n * @instance\n * @property {MapBoxZoomEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // the user cancels a \"box zoom\" interaction.\n * map.on('boxzoomcancel', function() {\n * console.log('A boxzoomcancel event occurred.');\n * });\n */\n | 'boxzoomcancel'\n\n /**\n * Fired immediately after the map has been resized.\n *\n * @event resize\n * @memberof Map\n * @instance\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // immediately after the map has been resized.\n * map.on('resize', function() {\n * console.log('A resize event occurred.');\n * });\n */\n | 'resize'\n\n /**\n * Fired when the WebGL context is lost.\n *\n * @event webglcontextlost\n * @memberof Map\n * @instance\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when the WebGL context is lost.\n * map.on('webglcontextlost', function() {\n * console.log('A webglcontextlost event occurred.');\n * });\n */\n | 'webglcontextlost'\n\n /**\n * Fired when the WebGL context is restored.\n *\n * @event webglcontextrestored\n * @memberof Map\n * @instance\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when the WebGL context is restored.\n * map.on('webglcontextrestored', function() {\n * console.log('A webglcontextrestored event occurred.');\n * });\n */\n | 'webglcontextrestored'\n\n /**\n * Fired immediately after all necessary resources have been downloaded\n * and the first visually complete rendering of the map has occurred.\n *\n * @event load\n * @memberof Map\n * @instance\n * @type {Object}\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when the map has finished loading.\n * map.on('load', function() {\n * console.log('A load event occurred.');\n * });\n * @see [Draw GeoJSON points](https://www.mapbox.com/mapbox-gl-js/example/geojson-markers/)\n * @see [Add live realtime data](https://www.mapbox.com/mapbox-gl-js/example/live-geojson/)\n * @see [Animate a point](https://www.mapbox.com/mapbox-gl-js/example/animate-point-along-line/)\n */\n | 'load'\n\n /**\n * Fired whenever the map is drawn to the screen, as the result of\n *\n * - a change to the map's position, zoom, pitch, or bearing\n * - a change to the map's style\n * - a change to a GeoJSON source\n * - the loading of a vector tile, GeoJSON file, glyph, or sprite\n *\n * @event render\n * @memberof Map\n * @instance\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // whenever the map is drawn to the screen.\n * map.on('render', function() {\n * console.log('A render event occurred.');\n * });\n */\n | 'render'\n\n /**\n * Fired after the last frame rendered before the map enters an\n * \"idle\" state:\n *\n * - No camera transitions are in progress\n * - All currently requested tiles have loaded\n * - All fade/transition animations have completed\n *\n * @event idle\n * @memberof Map\n * @instance\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // just before the map enters an \"idle\" state.\n * map.on('idle', function() {\n * console.log('A idle event occurred.');\n * });\n */\n | 'idle'\n\n /**\n * Fired immediately after the map has been removed with {@link Map.event:remove}.\n *\n * @event remove\n * @memberof Map\n * @instance\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // just after the map is removed.\n * map.on('remove', function() {\n * console.log('A remove event occurred.');\n * });\n */\n | 'remove'\n\n /**\n * Fired when an error occurs. This is GL JS's primary error reporting\n * mechanism. We use an event instead of `throw` to better accommodate\n * asyncronous operations. If no listeners are bound to the `error` event, the\n * error will be printed to the console.\n *\n * @event error\n * @memberof Map\n * @instance\n * @property {{error: {message: string}}} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when an error occurs.\n * map.on('error', function() {\n * console.log('A error event occurred.');\n * });\n */\n | 'error'\n\n /**\n * Fired when any map data loads or changes. See {@link MapDataEvent}\n * for more information.\n *\n * @event data\n * @memberof Map\n * @instance\n * @property {MapDataEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when map data loads or changes.\n * map.on('data', function() {\n * console.log('A data event occurred.');\n * });\n * @see [Display HTML clusters with custom properties](https://docs.mapbox.com/mapbox-gl-js/example/cluster-html/)\n */\n | 'data'\n\n /**\n * Fired when the map's style loads or changes. See\n * {@link MapDataEvent} for more information.\n *\n * @event styledata\n * @memberof Map\n * @instance\n * @property {MapDataEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when the map's style loads or changes.\n * map.on('styledata', function() {\n * console.log('A styledata event occurred.');\n * });\n */\n | 'styledata'\n\n /**\n * Fired when one of the map's sources loads or changes, including if a tile belonging\n * to a source loads or changes. See {@link MapDataEvent} for more information.\n *\n * @event sourcedata\n * @memberof Map\n * @instance\n * @property {MapDataEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when one of the map's sources loads or changes.\n * map.on('sourcedata', function() {\n * console.log('A sourcedata event occurred.');\n * });\n */\n | 'sourcedata'\n\n /**\n * Fired when any map data (style, source, tile, etc) begins loading or\n * changing asyncronously. All `dataloading` events are followed by a `data`\n * or `error` event. See {@link MapDataEvent} for more information.\n *\n * @event dataloading\n * @memberof Map\n * @instance\n * @property {MapDataEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // when any map data begins loading\n * // or changing asynchronously.\n * map.on('dataloading', function() {\n * console.log('A dataloading event occurred.');\n * });\n */\n | 'dataloading'\n\n /**\n * Fired when the map's style begins loading or changing asyncronously.\n * All `styledataloading` events are followed by a `styledata`\n * or `error` event. See {@link MapDataEvent} for more information.\n *\n * @event styledataloading\n * @memberof Map\n * @instance\n * @property {MapDataEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // map's style begins loading or\n * // changing asyncronously.\n * map.on('styledataloading', function() {\n * console.log('A styledataloading event occurred.');\n * });\n */\n | 'styledataloading'\n\n /**\n * Fired when one of the map's sources begins loading or changing asyncronously.\n * All `sourcedataloading` events are followed by a `sourcedata` or `error` event.\n * See {@link MapDataEvent} for more information.\n *\n * @event sourcedataloading\n * @memberof Map\n * @instance\n * @property {MapDataEvent} data\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // map's sources begin loading or\n * // changing asyncronously.\n * map.on('sourcedataloading', function() {\n * console.log('A sourcedataloading event occurred.');\n * });\n */\n | 'sourcedataloading'\n\n /**\n * Fired when an icon or pattern needed by the style is missing. The missing image can\n * be added with {@link Map#addImage} within this event listener callback to prevent the image from\n * being skipped. This event can be used to dynamically generate icons and patterns.\n *\n * @event styleimagemissing\n * @memberof Map\n * @instance\n * @property {string} id The id of the missing image.\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * // Set an event listener that fires\n * // an icon or pattern is missing.\n * map.on('styleimagemissing', function() {\n * console.log('A styleimagemissing event occurred.');\n * });\n * @see [Generate and add a missing icon to the map](https://mapbox.com/mapbox-gl-js/example/add-image-missing-generated/)\n */\n | 'styleimagemissing'\n\n /**\n * @event style.load\n * @memberof Map\n * @instance\n * @private\n */\n | 'style.load';\n","// @flow\n\nimport {MapMouseEvent, MapTouchEvent, MapWheelEvent} from '../events';\nimport type Map from '../map';\n\nexport class MapEventHandler {\n\n _mousedownPos: Point;\n _clickTolerance: number;\n _map: Map;\n\n constructor(map: Map, options: { clickTolerance: number }) {\n this._map = map;\n this._clickTolerance = options.clickTolerance;\n }\n\n reset() {\n delete this._mousedownPos;\n }\n\n wheel(e: WheelEvent) {\n // If mapEvent.preventDefault() is called by the user, prevent handlers such as:\n // - ScrollZoom\n return this._firePreventable(new MapWheelEvent(e.type, this._map, e));\n }\n\n mousedown(e: MouseEvent, point: Point) {\n this._mousedownPos = point;\n // If mapEvent.preventDefault() is called by the user, prevent handlers such as:\n // - MousePan\n // - MouseRotate\n // - MousePitch\n // - DblclickHandler\n return this._firePreventable(new MapMouseEvent(e.type, this._map, e));\n }\n\n mouseup(e: MouseEvent) {\n this._map.fire(new MapMouseEvent(e.type, this._map, e));\n }\n\n click(e: MouseEvent, point: Point) {\n if (this._mousedownPos && this._mousedownPos.dist(point) >= this._clickTolerance) return;\n this._map.fire(new MapMouseEvent(e.type, this._map, e));\n }\n\n dblclick(e: MouseEvent) {\n // If mapEvent.preventDefault() is called by the user, prevent handlers such as:\n // - DblClickZoom\n return this._firePreventable(new MapMouseEvent(e.type, this._map, e));\n }\n\n mouseover(e: MouseEvent) {\n this._map.fire(new MapMouseEvent(e.type, this._map, e));\n }\n\n mouseout(e: MouseEvent) {\n this._map.fire(new MapMouseEvent(e.type, this._map, e));\n }\n\n touchstart(e: TouchEvent) {\n // If mapEvent.preventDefault() is called by the user, prevent handlers such as:\n // - TouchPan\n // - TouchZoom\n // - TouchRotate\n // - TouchPitch\n // - TapZoom\n // - SwipeZoom\n return this._firePreventable(new MapTouchEvent(e.type, this._map, e));\n }\n\n touchmove(e: TouchEvent) {\n this._map.fire(new MapTouchEvent(e.type, this._map, e));\n }\n\n touchend(e: TouchEvent) {\n this._map.fire(new MapTouchEvent(e.type, this._map, e));\n }\n\n touchcancel(e: TouchEvent) {\n this._map.fire(new MapTouchEvent(e.type, this._map, e));\n }\n\n _firePreventable(mapEvent: MapMouseEvent | MapTouchEvent | MapWheelEvent) {\n this._map.fire(mapEvent);\n if (mapEvent.defaultPrevented) {\n // returning an object marks the handler as active and resets other handlers\n return {};\n }\n }\n\n isEnabled() {\n return true;\n }\n\n isActive() {\n return false;\n }\n enable() {}\n disable() {}\n}\n\nexport class BlockableMapEventHandler {\n _map: Map;\n _delayContextMenu: boolean;\n _contextMenuEvent: MouseEvent;\n\n constructor(map: Map) {\n this._map = map;\n }\n\n reset() {\n this._delayContextMenu = false;\n delete this._contextMenuEvent;\n }\n\n mousemove(e: MouseEvent) {\n // mousemove map events should not be fired when interaction handlers (pan, rotate, etc) are active\n this._map.fire(new MapMouseEvent(e.type, this._map, e));\n }\n\n mousedown() {\n this._delayContextMenu = true;\n }\n\n mouseup() {\n this._delayContextMenu = false;\n if (this._contextMenuEvent) {\n this._map.fire(new MapMouseEvent('contextmenu', this._map, this._contextMenuEvent));\n delete this._contextMenuEvent;\n }\n }\n contextmenu(e: MouseEvent) {\n if (this._delayContextMenu) {\n // Mac: contextmenu fired on mousedown; we save it until mouseup for consistency's sake\n this._contextMenuEvent = e;\n } else {\n // Windows: contextmenu fired on mouseup, so fire event now\n this._map.fire(new MapMouseEvent(e.type, this._map, e));\n }\n\n // prevent browser context menu when necessary\n if (this._map.listens('contextmenu')) {\n e.preventDefault();\n }\n }\n\n isEnabled() {\n return true;\n }\n\n isActive() {\n return false;\n }\n enable() {}\n disable() {}\n}\n","// @flow\n\nimport DOM from '../../util/dom';\n\nimport {Event} from '../../util/evented';\n\nimport type Map from '../map';\n\n/**\n * The `BoxZoomHandler` allows the user to zoom the map to fit within a bounding box.\n * The bounding box is defined by clicking and holding `shift` while dragging the cursor.\n */\nclass BoxZoomHandler {\n _map: Map;\n _el: HTMLElement;\n _container: HTMLElement;\n _enabled: boolean;\n _active: boolean;\n _startPos: Point;\n _lastPos: Point;\n _box: HTMLElement;\n _clickTolerance: number;\n\n /**\n * @private\n */\n constructor(map: Map, options: {\n clickTolerance: number\n }) {\n this._map = map;\n this._el = map.getCanvasContainer();\n this._container = map.getContainer();\n this._clickTolerance = options.clickTolerance || 1;\n }\n\n /**\n * Returns a Boolean indicating whether the \"box zoom\" interaction is enabled.\n *\n * @returns {boolean} `true` if the \"box zoom\" interaction is enabled.\n */\n isEnabled() {\n return !!this._enabled;\n }\n\n /**\n * Returns a Boolean indicating whether the \"box zoom\" interaction is active, i.e. currently being used.\n *\n * @returns {boolean} `true` if the \"box zoom\" interaction is active.\n */\n isActive() {\n return !!this._active;\n }\n\n /**\n * Enables the \"box zoom\" interaction.\n *\n * @example\n * map.boxZoom.enable();\n */\n enable() {\n if (this.isEnabled()) return;\n this._enabled = true;\n }\n\n /**\n * Disables the \"box zoom\" interaction.\n *\n * @example\n * map.boxZoom.disable();\n */\n disable() {\n if (!this.isEnabled()) return;\n this._enabled = false;\n }\n\n mousedown(e: MouseEvent, point: Point) {\n if (!this.isEnabled()) return;\n if (!(e.shiftKey && e.button === 0)) return;\n\n DOM.disableDrag();\n this._startPos = this._lastPos = point;\n this._active = true;\n }\n\n mousemoveWindow(e: MouseEvent, point: Point) {\n if (!this._active) return;\n\n const pos = point;\n\n if (this._lastPos.equals(pos) || (!this._box && pos.dist(this._startPos) < this._clickTolerance)) {\n return;\n }\n\n const p0 = this._startPos;\n this._lastPos = pos;\n\n if (!this._box) {\n this._box = DOM.create('div', 'mapboxgl-boxzoom', this._container);\n this._container.classList.add('mapboxgl-crosshair');\n this._fireEvent('boxzoomstart', e);\n }\n\n const minX = Math.min(p0.x, pos.x),\n maxX = Math.max(p0.x, pos.x),\n minY = Math.min(p0.y, pos.y),\n maxY = Math.max(p0.y, pos.y);\n\n DOM.setTransform(this._box, `translate(${minX}px,${minY}px)`);\n\n this._box.style.width = `${maxX - minX}px`;\n this._box.style.height = `${maxY - minY}px`;\n }\n\n mouseupWindow(e: MouseEvent, point: Point) {\n if (!this._active) return;\n\n if (e.button !== 0) return;\n\n const p0 = this._startPos,\n p1 = point;\n\n this.reset();\n\n DOM.suppressClick();\n\n if (p0.x === p1.x && p0.y === p1.y) {\n this._fireEvent('boxzoomcancel', e);\n } else {\n this._map.fire(new Event('boxzoomend', {originalEvent: e}));\n return {\n cameraAnimation: map => map.fitScreenCoordinates(p0, p1, this._map.getBearing(), {linear: true})\n };\n }\n }\n\n keydown(e: KeyboardEvent) {\n if (!this._active) return;\n\n if (e.keyCode === 27) {\n this.reset();\n this._fireEvent('boxzoomcancel', e);\n }\n }\n\n blur() {\n this.reset();\n }\n\n reset() {\n this._active = false;\n\n this._container.classList.remove('mapboxgl-crosshair');\n\n if (this._box) {\n DOM.remove(this._box);\n this._box = (null: any);\n }\n\n DOM.enableDrag();\n\n delete this._startPos;\n delete this._lastPos;\n }\n\n _fireEvent(type: string, e: *) {\n return this._map.fire(new Event(type, {originalEvent: e}));\n }\n}\n\nexport default BoxZoomHandler;\n","// @flow\n\nimport assert from 'assert';\n\nexport function indexTouches(touches: Array, points: Array) {\n assert(touches.length === points.length);\n const obj = {};\n for (let i = 0; i < touches.length; i++) {\n obj[touches[i].identifier] = points[i];\n }\n return obj;\n}\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\nimport {indexTouches} from './handler_util';\n\nfunction getCentroid(points: Array) {\n const sum = new Point(0, 0);\n for (const point of points) {\n sum._add(point);\n }\n return sum.div(points.length);\n}\n\nexport const MAX_TAP_INTERVAL = 500;\nconst MAX_TOUCH_TIME = 500;\nconst MAX_DIST = 30;\n\nexport class SingleTapRecognizer {\n\n numTouches: number;\n centroid: Point;\n startTime: number;\n aborted: boolean;\n touches: { [number | string]: Point };\n\n constructor(options: { numTouches: number }) {\n this.reset();\n this.numTouches = options.numTouches;\n }\n\n reset() {\n delete this.centroid;\n delete this.startTime;\n delete this.touches;\n this.aborted = false;\n }\n\n touchstart(e: TouchEvent, points: Array, mapTouches: Array) {\n\n if (this.centroid || mapTouches.length > this.numTouches) {\n this.aborted = true;\n }\n if (this.aborted) {\n return;\n }\n\n if (this.startTime === undefined) {\n this.startTime = e.timeStamp;\n }\n\n if (mapTouches.length === this.numTouches) {\n this.centroid = getCentroid(points);\n this.touches = indexTouches(mapTouches, points);\n }\n }\n\n touchmove(e: TouchEvent, points: Array, mapTouches: Array) {\n if (this.aborted || !this.centroid) return;\n\n const newTouches = indexTouches(mapTouches, points);\n for (const id in this.touches) {\n const prevPos = this.touches[id];\n const pos = newTouches[id];\n if (!pos || pos.dist(prevPos) > MAX_DIST) {\n this.aborted = true;\n }\n }\n }\n\n touchend(e: TouchEvent, points: Array, mapTouches: Array) {\n if (!this.centroid || e.timeStamp - this.startTime > MAX_TOUCH_TIME) {\n this.aborted = true;\n }\n\n if (mapTouches.length === 0) {\n const centroid = !this.aborted && this.centroid;\n this.reset();\n if (centroid) return centroid;\n }\n }\n\n}\n\nexport class TapRecognizer {\n\n singleTap: SingleTapRecognizer;\n numTaps: number;\n lastTime: number;\n lastTap: Point;\n count: number;\n\n constructor(options: { numTaps: number, numTouches: number }) {\n this.singleTap = new SingleTapRecognizer(options);\n this.numTaps = options.numTaps;\n this.reset();\n }\n\n reset() {\n this.lastTime = Infinity;\n delete this.lastTap;\n this.count = 0;\n this.singleTap.reset();\n }\n\n touchstart(e: TouchEvent, points: Array, mapTouches: Array) {\n this.singleTap.touchstart(e, points, mapTouches);\n }\n\n touchmove(e: TouchEvent, points: Array, mapTouches: Array) {\n this.singleTap.touchmove(e, points, mapTouches);\n }\n\n touchend(e: TouchEvent, points: Array, mapTouches: Array) {\n const tap = this.singleTap.touchend(e, points, mapTouches);\n if (tap) {\n const soonEnough = e.timeStamp - this.lastTime < MAX_TAP_INTERVAL;\n const closeEnough = !this.lastTap || this.lastTap.dist(tap) < MAX_DIST;\n\n if (!soonEnough || !closeEnough) {\n this.reset();\n }\n\n this.count++;\n this.lastTime = e.timeStamp;\n this.lastTap = tap;\n\n if (this.count === this.numTaps) {\n this.reset();\n return tap;\n }\n }\n }\n}\n","// @flow\n\nimport {TapRecognizer} from './tap_recognizer';\nimport type Point from '@mapbox/point-geometry';\nimport type Map from '../map';\n\nexport default class TapZoomHandler {\n\n _enabled: boolean;\n _active: boolean;\n _zoomIn: TapRecognizer;\n _zoomOut: TapRecognizer;\n\n constructor() {\n this._zoomIn = new TapRecognizer({\n numTouches: 1,\n numTaps: 2\n });\n\n this._zoomOut = new TapRecognizer({\n numTouches: 2,\n numTaps: 1\n });\n\n this.reset();\n }\n\n reset() {\n this._active = false;\n this._zoomIn.reset();\n this._zoomOut.reset();\n }\n\n touchstart(e: TouchEvent, points: Array, mapTouches: Array) {\n this._zoomIn.touchstart(e, points, mapTouches);\n this._zoomOut.touchstart(e, points, mapTouches);\n }\n\n touchmove(e: TouchEvent, points: Array, mapTouches: Array) {\n this._zoomIn.touchmove(e, points, mapTouches);\n this._zoomOut.touchmove(e, points, mapTouches);\n }\n\n touchend(e: TouchEvent, points: Array, mapTouches: Array) {\n const zoomInPoint = this._zoomIn.touchend(e, points, mapTouches);\n const zoomOutPoint = this._zoomOut.touchend(e, points, mapTouches);\n\n if (zoomInPoint) {\n this._active = true;\n e.preventDefault();\n setTimeout(() => this.reset(), 0);\n return {\n cameraAnimation: (map: Map) => map.easeTo({\n duration: 300,\n zoom: map.getZoom() + 1,\n around: map.unproject(zoomInPoint)\n }, {originalEvent: e})\n };\n } else if (zoomOutPoint) {\n this._active = true;\n e.preventDefault();\n setTimeout(() => this.reset(), 0);\n return {\n cameraAnimation: (map: Map) => map.easeTo({\n duration: 300,\n zoom: map.getZoom() - 1,\n around: map.unproject(zoomOutPoint)\n }, {originalEvent: e})\n };\n }\n }\n\n touchcancel() {\n this.reset();\n }\n\n enable() {\n this._enabled = true;\n }\n\n disable() {\n this._enabled = false;\n this.reset();\n }\n\n isEnabled() {\n return this._enabled;\n }\n\n isActive() {\n return this._active;\n }\n}\n","// @flow\n\nimport DOM from '../../util/dom';\nimport type Point from '@mapbox/point-geometry';\n\nconst LEFT_BUTTON = 0;\nconst RIGHT_BUTTON = 2;\n\n// the values for each button in MouseEvent.buttons\nconst BUTTONS_FLAGS = {\n [LEFT_BUTTON]: 1,\n [RIGHT_BUTTON]: 2\n};\n\nfunction buttonStillPressed(e: MouseEvent, button: number) {\n const flag = BUTTONS_FLAGS[button];\n return e.buttons === undefined || (e.buttons & flag) !== flag;\n}\n\nclass MouseHandler {\n\n _enabled: boolean;\n _active: boolean;\n _lastPoint: Point;\n _eventButton: number;\n _moved: boolean;\n _clickTolerance: number;\n\n constructor(options: { clickTolerance: number }) {\n this.reset();\n this._clickTolerance = options.clickTolerance || 1;\n }\n\n blur() {\n this.reset();\n }\n\n reset() {\n this._active = false;\n this._moved = false;\n delete this._lastPoint;\n delete this._eventButton;\n }\n\n _correctButton(e: MouseEvent, button: number) { //eslint-disable-line\n return false; // implemented by child\n }\n\n _move(lastPoint: Point, point: Point) { //eslint-disable-line\n return {}; // implemented by child\n }\n\n mousedown(e: MouseEvent, point: Point) {\n if (this._lastPoint) return;\n\n const eventButton = DOM.mouseButton(e);\n if (!this._correctButton(e, eventButton)) return;\n\n this._lastPoint = point;\n this._eventButton = eventButton;\n }\n\n mousemoveWindow(e: MouseEvent, point: Point) {\n const lastPoint = this._lastPoint;\n if (!lastPoint) return;\n e.preventDefault();\n\n if (buttonStillPressed(e, this._eventButton)) {\n // Some browsers don't fire a `mouseup` when the mouseup occurs outside\n // the window or iframe:\n // https://github.com/mapbox/mapbox-gl-js/issues/4622\n //\n // If the button is no longer pressed during this `mousemove` it may have\n // been released outside of the window or iframe.\n this.reset();\n return;\n }\n\n if (!this._moved && point.dist(lastPoint) < this._clickTolerance) return;\n this._moved = true;\n this._lastPoint = point;\n\n // implemented by child class\n return this._move(lastPoint, point);\n }\n\n mouseupWindow(e: MouseEvent) {\n if (!this._lastPoint) return;\n const eventButton = DOM.mouseButton(e);\n if (eventButton !== this._eventButton) return;\n if (this._moved) DOM.suppressClick();\n this.reset();\n }\n\n enable() {\n this._enabled = true;\n }\n\n disable() {\n this._enabled = false;\n this.reset();\n }\n\n isEnabled() {\n return this._enabled;\n }\n\n isActive() {\n return this._active;\n }\n}\n\nexport class MousePanHandler extends MouseHandler {\n\n mousedown(e: MouseEvent, point: Point) {\n super.mousedown(e, point);\n if (this._lastPoint) this._active = true;\n }\n _correctButton(e: MouseEvent, button: number) {\n return button === LEFT_BUTTON && !e.ctrlKey;\n }\n\n _move(lastPoint: Point, point: Point) {\n return {\n around: point,\n panDelta: point.sub(lastPoint)\n };\n }\n}\n\nexport class MouseRotateHandler extends MouseHandler {\n _correctButton(e: MouseEvent, button: number) {\n return (button === LEFT_BUTTON && e.ctrlKey) || (button === RIGHT_BUTTON);\n }\n\n _move(lastPoint: Point, point: Point) {\n const degreesPerPixelMoved = 0.8;\n const bearingDelta = (point.x - lastPoint.x) * degreesPerPixelMoved;\n if (bearingDelta) {\n this._active = true;\n return {bearingDelta};\n }\n }\n\n contextmenu(e: MouseEvent) {\n // prevent browser context menu when necessary; we don't allow it with rotation\n // because we can't discern rotation gesture start from contextmenu on Mac\n e.preventDefault();\n }\n}\n\nexport class MousePitchHandler extends MouseHandler {\n _correctButton(e: MouseEvent, button: number) {\n return (button === LEFT_BUTTON && e.ctrlKey) || (button === RIGHT_BUTTON);\n }\n\n _move(lastPoint: Point, point: Point) {\n const degreesPerPixelMoved = -0.5;\n const pitchDelta = (point.y - lastPoint.y) * degreesPerPixelMoved;\n if (pitchDelta) {\n this._active = true;\n return {pitchDelta};\n }\n }\n\n contextmenu(e: MouseEvent) {\n // prevent browser context menu when necessary; we don't allow it with rotation\n // because we can't discern rotation gesture start from contextmenu on Mac\n e.preventDefault();\n }\n}\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\nimport {indexTouches} from './handler_util';\n\nexport default class TouchPanHandler {\n\n _enabled: boolean;\n _active: boolean;\n _touches: { [string | number]: Point };\n _minTouches: number;\n _clickTolerance: number;\n _sum: Point;\n\n constructor(options: { clickTolerance: number }) {\n this._minTouches = 1;\n this._clickTolerance = options.clickTolerance || 1;\n this.reset();\n }\n\n reset() {\n this._active = false;\n this._touches = {};\n this._sum = new Point(0, 0);\n }\n\n touchstart(e: TouchEvent, points: Array, mapTouches: Array) {\n return this._calculateTransform(e, points, mapTouches);\n }\n\n touchmove(e: TouchEvent, points: Array, mapTouches: Array) {\n if (!this._active || mapTouches.length < this._minTouches) return;\n e.preventDefault();\n return this._calculateTransform(e, points, mapTouches);\n }\n\n touchend(e: TouchEvent, points: Array, mapTouches: Array) {\n this._calculateTransform(e, points, mapTouches);\n\n if (this._active && mapTouches.length < this._minTouches) {\n this.reset();\n }\n }\n\n touchcancel() {\n this.reset();\n }\n\n _calculateTransform(e: TouchEvent, points: Array, mapTouches: Array) {\n if (mapTouches.length > 0) this._active = true;\n\n const touches = indexTouches(mapTouches, points);\n\n const touchPointSum = new Point(0, 0);\n const touchDeltaSum = new Point(0, 0);\n let touchDeltaCount = 0;\n\n for (const identifier in touches) {\n const point = touches[identifier];\n const prevPoint = this._touches[identifier];\n if (prevPoint) {\n touchPointSum._add(point);\n touchDeltaSum._add(point.sub(prevPoint));\n touchDeltaCount++;\n touches[identifier] = point;\n }\n }\n\n this._touches = touches;\n\n if (touchDeltaCount < this._minTouches || !touchDeltaSum.mag()) return;\n\n const panDelta = touchDeltaSum.div(touchDeltaCount);\n this._sum._add(panDelta);\n if (this._sum.mag() < this._clickTolerance) return;\n\n const around = touchPointSum.div(touchDeltaCount);\n\n return {\n around,\n panDelta\n };\n }\n\n enable() {\n this._enabled = true;\n }\n\n disable() {\n this._enabled = false;\n this.reset();\n }\n\n isEnabled() {\n return this._enabled;\n }\n\n isActive() {\n return this._active;\n }\n}\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\nimport DOM from '../../util/dom';\n\nclass TwoTouchHandler {\n\n _enabled: boolean;\n _active: boolean;\n _firstTwoTouches: [number, number];\n _vector: Point;\n _startVector: Point;\n _aroundCenter: boolean;\n\n constructor() {\n this.reset();\n }\n\n reset() {\n this._active = false;\n delete this._firstTwoTouches;\n }\n\n _start(points: [Point, Point]) {} //eslint-disable-line\n _move(points: [Point, Point], pinchAround: Point, e: TouchEvent) { return {}; } //eslint-disable-line\n\n touchstart(e: TouchEvent, points: Array, mapTouches: Array) {\n //console.log(e.target, e.targetTouches.length ? e.targetTouches[0].target : null);\n //log('touchstart', points, e.target.innerHTML, e.targetTouches.length ? e.targetTouches[0].target.innerHTML: undefined);\n if (this._firstTwoTouches || mapTouches.length < 2) return;\n\n this._firstTwoTouches = [\n mapTouches[0].identifier,\n mapTouches[1].identifier\n ];\n\n // implemented by child classes\n this._start([points[0], points[1]]);\n }\n\n touchmove(e: TouchEvent, points: Array, mapTouches: Array) {\n if (!this._firstTwoTouches) return;\n\n e.preventDefault();\n\n const [idA, idB] = this._firstTwoTouches;\n const a = getTouchById(mapTouches, points, idA);\n const b = getTouchById(mapTouches, points, idB);\n if (!a || !b) return;\n const pinchAround = this._aroundCenter ? null : a.add(b).div(2);\n\n // implemented by child classes\n return this._move([a, b], pinchAround, e);\n\n }\n\n touchend(e: TouchEvent, points: Array, mapTouches: Array) {\n if (!this._firstTwoTouches) return;\n\n const [idA, idB] = this._firstTwoTouches;\n const a = getTouchById(mapTouches, points, idA);\n const b = getTouchById(mapTouches, points, idB);\n if (a && b) return;\n\n if (this._active) DOM.suppressClick();\n\n this.reset();\n }\n\n touchcancel() {\n this.reset();\n }\n\n enable(options: ?{around?: 'center'}) {\n this._enabled = true;\n this._aroundCenter = !!options && options.around === 'center';\n }\n\n disable() {\n this._enabled = false;\n this.reset();\n }\n\n isEnabled() {\n return this._enabled;\n }\n\n isActive() {\n return this._active;\n }\n}\n\nfunction getTouchById(mapTouches: Array, points: Array, identifier: number) {\n for (let i = 0; i < mapTouches.length; i++) {\n if (mapTouches[i].identifier === identifier) return points[i];\n }\n}\n\n/* ZOOM */\n\nconst ZOOM_THRESHOLD = 0.1;\n\nfunction getZoomDelta(distance, lastDistance) {\n return Math.log(distance / lastDistance) / Math.LN2;\n}\n\nexport class TouchZoomHandler extends TwoTouchHandler {\n\n _distance: number;\n _startDistance: number;\n\n reset() {\n super.reset();\n delete this._distance;\n delete this._startDistance;\n }\n\n _start(points: [Point, Point]) {\n this._startDistance = this._distance = points[0].dist(points[1]);\n }\n\n _move(points: [Point, Point], pinchAround: Point) {\n const lastDistance = this._distance;\n this._distance = points[0].dist(points[1]);\n if (!this._active && Math.abs(getZoomDelta(this._distance, this._startDistance)) < ZOOM_THRESHOLD) return;\n this._active = true;\n return {\n zoomDelta: getZoomDelta(this._distance, lastDistance),\n pinchAround\n };\n }\n}\n\n/* ROTATE */\n\nconst ROTATION_THRESHOLD = 25; // pixels along circumference of touch circle\n\nfunction getBearingDelta(a, b) {\n return a.angleWith(b) * 180 / Math.PI;\n}\n\nexport class TouchRotateHandler extends TwoTouchHandler {\n _minDiameter: number;\n\n reset() {\n super.reset();\n delete this._minDiameter;\n delete this._startVector;\n delete this._vector;\n }\n\n _start(points: [Point, Point]) {\n this._startVector = this._vector = points[0].sub(points[1]);\n this._minDiameter = points[0].dist(points[1]);\n }\n\n _move(points: [Point, Point], pinchAround: Point) {\n const lastVector = this._vector;\n this._vector = points[0].sub(points[1]);\n\n if (!this._active && this._isBelowThreshold(this._vector)) return;\n this._active = true;\n\n return {\n bearingDelta: getBearingDelta(this._vector, lastVector),\n pinchAround\n };\n }\n\n _isBelowThreshold(vector: Point) {\n /*\n * The threshold before a rotation actually happens is configured in\n * pixels alongth circumference of the circle formed by the two fingers.\n * This makes the threshold in degrees larger when the fingers are close\n * together and smaller when the fingers are far apart.\n *\n * Use the smallest diameter from the whole gesture to reduce sensitivity\n * when pinching in and out.\n */\n\n this._minDiameter = Math.min(this._minDiameter, vector.mag());\n const circumference = Math.PI * this._minDiameter;\n const threshold = ROTATION_THRESHOLD / circumference * 360;\n\n const bearingDeltaSinceStart = getBearingDelta(vector, this._startVector);\n return Math.abs(bearingDeltaSinceStart) < threshold;\n }\n}\n\n/* PITCH */\n\nfunction isVertical(vector) {\n return Math.abs(vector.y) > Math.abs(vector.x);\n}\n\nconst ALLOWED_SINGLE_TOUCH_TIME = 100;\n\n/**\n * The `TouchPitchHandler` allows the user to pitch the map by dragging up and down with two fingers.\n */\nexport class TouchPitchHandler extends TwoTouchHandler {\n\n _valid: boolean | void;\n _firstMove: number;\n _lastPoints: [Point, Point];\n\n reset() {\n super.reset();\n this._valid = undefined;\n delete this._firstMove;\n delete this._lastPoints;\n }\n\n _start(points: [Point, Point]) {\n this._lastPoints = points;\n if (isVertical(points[0].sub(points[1]))) {\n // fingers are more horizontal than vertical\n this._valid = false;\n\n }\n }\n\n _move(points: [Point, Point], center: Point, e: TouchEvent) {\n const vectorA = points[0].sub(this._lastPoints[0]);\n const vectorB = points[1].sub(this._lastPoints[1]);\n\n this._valid = this.gestureBeginsVertically(vectorA, vectorB, e.timeStamp);\n if (!this._valid) return;\n\n this._lastPoints = points;\n this._active = true;\n const yDeltaAverage = (vectorA.y + vectorB.y) / 2;\n const degreesPerPixelMoved = -0.5;\n return {\n pitchDelta: yDeltaAverage * degreesPerPixelMoved\n };\n }\n\n gestureBeginsVertically(vectorA: Point, vectorB: Point, timeStamp: number) {\n if (this._valid !== undefined) return this._valid;\n\n const threshold = 2;\n const movedA = vectorA.mag() >= threshold;\n const movedB = vectorB.mag() >= threshold;\n\n // neither finger has moved a meaningful amount, wait\n if (!movedA && !movedB) return;\n\n // One finger has moved and the other has not.\n // If enough time has passed, decide it is not a pitch.\n if (!movedA || !movedB) {\n if (this._firstMove === undefined) {\n this._firstMove = timeStamp;\n }\n\n if (timeStamp - this._firstMove < ALLOWED_SINGLE_TOUCH_TIME) {\n // still waiting for a movement from the second finger\n return undefined;\n } else {\n return false;\n }\n }\n\n const isSameDirection = vectorA.y > 0 === vectorB.y > 0;\n return isVertical(vectorA) && isVertical(vectorB) && isSameDirection;\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to pitch\" interaction is enabled.\n *\n * @memberof TouchPitchHandler\n * @name isEnabled\n * @instance\n * @returns {boolean} `true` if the \"drag to pitch\" interaction is enabled.\n */\n\n /**\n * Returns a Boolean indicating whether the \"drag to pitch\" interaction is active, i.e. currently being used.\n *\n * @memberof TouchPitchHandler\n * @name isActive\n * @instance\n * @returns {boolean} `true` if the \"drag to pitch\" interaction is active.\n */\n\n /**\n * Enables the \"drag to pitch\" interaction.\n *\n * @memberof TouchPitchHandler\n * @name enable\n * @instance\n * @example\n * map.touchPitch.enable();\n */\n\n /**\n * Disables the \"drag to pitch\" interaction.\n *\n * @memberof TouchPitchHandler\n * @name disable\n * @instance\n * @example\n * map.touchPitch.disable();\n */\n}\n","// @flow\n\nimport type Map from '../map';\n\nconst defaultOptions = {\n panStep: 100,\n bearingStep: 15,\n pitchStep: 10\n};\n\n/**\n * The `KeyboardHandler` allows the user to zoom, rotate, and pan the map using\n * the following keyboard shortcuts:\n *\n * - `=` / `+`: Increase the zoom level by 1.\n * - `Shift-=` / `Shift-+`: Increase the zoom level by 2.\n * - `-`: Decrease the zoom level by 1.\n * - `Shift--`: Decrease the zoom level by 2.\n * - Arrow keys: Pan by 100 pixels.\n * - `Shift+⇢`: Increase the rotation by 15 degrees.\n * - `Shift+⇠`: Decrease the rotation by 15 degrees.\n * - `Shift+⇡`: Increase the pitch by 10 degrees.\n * - `Shift+⇣`: Decrease the pitch by 10 degrees.\n */\nclass KeyboardHandler {\n _enabled: boolean;\n _active: boolean;\n _panStep: number;\n _bearingStep: number;\n _pitchStep: number;\n _rotationDisabled: boolean;\n\n /**\n * @private\n */\n constructor() {\n const stepOptions = defaultOptions;\n this._panStep = stepOptions.panStep;\n this._bearingStep = stepOptions.bearingStep;\n this._pitchStep = stepOptions.pitchStep;\n this._rotationDisabled = false;\n }\n\n blur() {\n this.reset();\n }\n\n reset() {\n this._active = false;\n }\n\n keydown(e: KeyboardEvent) {\n if (e.altKey || e.ctrlKey || e.metaKey) return;\n\n let zoomDir = 0;\n let bearingDir = 0;\n let pitchDir = 0;\n let xDir = 0;\n let yDir = 0;\n\n switch (e.keyCode) {\n case 61:\n case 107:\n case 171:\n case 187:\n zoomDir = 1;\n break;\n\n case 189:\n case 109:\n case 173:\n zoomDir = -1;\n break;\n\n case 37:\n if (e.shiftKey) {\n bearingDir = -1;\n } else {\n e.preventDefault();\n xDir = -1;\n }\n break;\n\n case 39:\n if (e.shiftKey) {\n bearingDir = 1;\n } else {\n e.preventDefault();\n xDir = 1;\n }\n break;\n\n case 38:\n if (e.shiftKey) {\n pitchDir = 1;\n } else {\n e.preventDefault();\n yDir = -1;\n }\n break;\n\n case 40:\n if (e.shiftKey) {\n pitchDir = -1;\n } else {\n e.preventDefault();\n yDir = 1;\n }\n break;\n\n default:\n return;\n }\n\n if (this._rotationDisabled) {\n bearingDir = 0;\n pitchDir = 0;\n }\n\n return {\n cameraAnimation: (map: Map) => {\n const zoom = map.getZoom();\n map.easeTo({\n duration: 300,\n easeId: 'keyboardHandler',\n easing: easeOut,\n\n zoom: zoomDir ? Math.round(zoom) + zoomDir * (e.shiftKey ? 2 : 1) : zoom,\n bearing: map.getBearing() + bearingDir * this._bearingStep,\n pitch: map.getPitch() + pitchDir * this._pitchStep,\n offset: [-xDir * this._panStep, -yDir * this._panStep],\n center: map.getCenter()\n }, {originalEvent: e});\n }\n };\n }\n\n /**\n * Enables the \"keyboard rotate and zoom\" interaction.\n *\n * @example\n * map.keyboard.enable();\n */\n enable() {\n this._enabled = true;\n }\n\n /**\n * Disables the \"keyboard rotate and zoom\" interaction.\n *\n * @example\n * map.keyboard.disable();\n */\n disable() {\n this._enabled = false;\n this.reset();\n }\n\n /**\n * Returns a Boolean indicating whether the \"keyboard rotate and zoom\"\n * interaction is enabled.\n *\n * @returns {boolean} `true` if the \"keyboard rotate and zoom\"\n * interaction is enabled.\n */\n isEnabled() {\n return this._enabled;\n }\n\n /**\n * Returns true if the handler is enabled and has detected the start of a\n * zoom/rotate gesture.\n *\n * @returns {boolean} `true` if the handler is enabled and has detected the\n * start of a zoom/rotate gesture.\n */\n isActive() {\n return this._active;\n }\n\n /**\n * Disables the \"keyboard pan/rotate\" interaction, leaving the\n * \"keyboard zoom\" interaction enabled.\n *\n * @example\n * map.keyboard.disableRotation();\n */\n disableRotation() {\n this._rotationDisabled = true;\n }\n\n /**\n * Enables the \"keyboard pan/rotate\" interaction.\n *\n * @example\n * map.keyboard.enable();\n * map.keyboard.enableRotation();\n */\n enableRotation() {\n this._rotationDisabled = false;\n }\n}\n\nfunction easeOut(t: number) {\n return t * (2 - t);\n}\n\nexport default KeyboardHandler;\n","// @flow\n\nimport assert from 'assert';\nimport DOM from '../../util/dom';\n\nimport {ease as _ease, bindAll, bezier} from '../../util/util';\nimport browser from '../../util/browser';\nimport window from '../../util/window';\nimport {number as interpolate} from '../../style-spec/util/interpolate';\nimport LngLat from '../../geo/lng_lat';\n\nimport type Map from '../map';\nimport type HandlerManager from '../handler_manager';\nimport type Point from '@mapbox/point-geometry';\n\n// deltaY value for mouse scroll wheel identification\nconst wheelZoomDelta = 4.000244140625;\n\n// These magic numbers control the rate of zoom. Trackpad events fire at a greater\n// frequency than mouse scroll wheel, so reduce the zoom rate per wheel tick\nconst defaultZoomRate = 1 / 100;\nconst wheelZoomRate = 1 / 450;\n\n// upper bound on how much we scale the map in any single render frame; this\n// is used to limit zoom rate in the case of very fast scrolling\nconst maxScalePerFrame = 2;\n\n/**\n * The `ScrollZoomHandler` allows the user to zoom the map by scrolling.\n */\nclass ScrollZoomHandler {\n _map: Map;\n _el: HTMLElement;\n _enabled: boolean;\n _active: boolean;\n _zooming: boolean;\n _aroundCenter: boolean;\n _around: Point;\n _aroundPoint: Point;\n _type: 'wheel' | 'trackpad' | null;\n _lastValue: number;\n _timeout: ?TimeoutID; // used for delayed-handling of a single wheel movement\n _finishTimeout: ?TimeoutID; // used to delay final '{move,zoom}end' events\n\n _lastWheelEvent: any;\n _lastWheelEventTime: number;\n\n _startZoom: ?number;\n _targetZoom: ?number;\n _delta: number;\n _easing: ?((number) => number);\n _prevEase: ?{start: number, duration: number, easing: (_: number) => number};\n\n _frameId: ?boolean;\n _handler: HandlerManager;\n\n _defaultZoomRate: number;\n _wheelZoomRate: number;\n\n /**\n * @private\n */\n constructor(map: Map, handler: HandlerManager) {\n this._map = map;\n this._el = map.getCanvasContainer();\n this._handler = handler;\n\n this._delta = 0;\n\n this._defaultZoomRate = defaultZoomRate;\n this._wheelZoomRate = wheelZoomRate;\n\n bindAll(['_onTimeout'], this);\n }\n\n /**\n * Set the zoom rate of a trackpad\n * @param {number} [zoomRate=1/100] The rate used to scale trackpad movement to a zoom value.\n * @example\n * // Speed up trackpad zoom\n * map.scrollZoom.setZoomRate(1/25);\n */\n setZoomRate(zoomRate: number) {\n this._defaultZoomRate = zoomRate;\n }\n\n /**\n * Set the zoom rate of a mouse wheel\n * @param {number} [wheelZoomRate=1/450] The rate used to scale mouse wheel movement to a zoom value.\n * @example\n * // Slow down zoom of mouse wheel\n * map.scrollZoom.setWheelZoomRate(1/600);\n */\n setWheelZoomRate(wheelZoomRate: number) {\n this._wheelZoomRate = wheelZoomRate;\n }\n\n /**\n * Returns a Boolean indicating whether the \"scroll to zoom\" interaction is enabled.\n *\n * @returns {boolean} `true` if the \"scroll to zoom\" interaction is enabled.\n */\n isEnabled() {\n return !!this._enabled;\n }\n\n /*\n * Active state is turned on and off with every scroll wheel event and is set back to false before the map\n * render is called, so _active is not a good candidate for determining if a scroll zoom animation is in\n * progress.\n */\n isActive() {\n return !!this._active || this._finishTimeout !== undefined;\n }\n\n isZooming() {\n return !!this._zooming;\n }\n\n /**\n * Enables the \"scroll to zoom\" interaction.\n *\n * @param {Object} [options] Options object.\n * @param {string} [options.around] If \"center\" is passed, map will zoom around center of map\n *\n * @example\n * map.scrollZoom.enable();\n * @example\n * map.scrollZoom.enable({ around: 'center' })\n */\n enable(options: any) {\n if (this.isEnabled()) return;\n this._enabled = true;\n this._aroundCenter = options && options.around === 'center';\n }\n\n /**\n * Disables the \"scroll to zoom\" interaction.\n *\n * @example\n * map.scrollZoom.disable();\n */\n disable() {\n if (!this.isEnabled()) return;\n this._enabled = false;\n }\n\n wheel(e: WheelEvent) {\n if (!this.isEnabled()) return;\n\n // Remove `any` cast when https://github.com/facebook/flow/issues/4879 is fixed.\n let value = e.deltaMode === (window.WheelEvent: any).DOM_DELTA_LINE ? e.deltaY * 40 : e.deltaY;\n const now = browser.now(),\n timeDelta = now - (this._lastWheelEventTime || 0);\n\n this._lastWheelEventTime = now;\n\n if (value !== 0 && (value % wheelZoomDelta) === 0) {\n // This one is definitely a mouse wheel event.\n this._type = 'wheel';\n\n } else if (value !== 0 && Math.abs(value) < 4) {\n // This one is definitely a trackpad event because it is so small.\n this._type = 'trackpad';\n\n } else if (timeDelta > 400) {\n // This is likely a new scroll action.\n this._type = null;\n this._lastValue = value;\n\n // Start a timeout in case this was a singular event, and dely it by up to 40ms.\n this._timeout = setTimeout(this._onTimeout, 40, e);\n\n } else if (!this._type) {\n // This is a repeating event, but we don't know the type of event just yet.\n // If the delta per time is small, we assume it's a fast trackpad; otherwise we switch into wheel mode.\n this._type = (Math.abs(timeDelta * value) < 200) ? 'trackpad' : 'wheel';\n\n // Make sure our delayed event isn't fired again, because we accumulate\n // the previous event (which was less than 40ms ago) into this event.\n if (this._timeout) {\n clearTimeout(this._timeout);\n this._timeout = null;\n value += this._lastValue;\n }\n }\n\n // Slow down zoom if shift key is held for more precise zooming\n if (e.shiftKey && value) value = value / 4;\n\n // Only fire the callback if we actually know what type of scrolling device the user uses.\n if (this._type) {\n this._lastWheelEvent = e;\n this._delta -= value;\n if (!this._active) {\n this._start(e);\n }\n }\n\n e.preventDefault();\n }\n\n _onTimeout(initialEvent: any) {\n this._type = 'wheel';\n this._delta -= this._lastValue;\n if (!this._active) {\n this._start(initialEvent);\n }\n }\n\n _start(e: any) {\n if (!this._delta) return;\n\n if (this._frameId) {\n this._frameId = null;\n }\n\n this._active = true;\n if (!this.isZooming()) {\n this._zooming = true;\n }\n\n if (this._finishTimeout) {\n clearTimeout(this._finishTimeout);\n delete this._finishTimeout;\n }\n\n const pos = DOM.mousePos(this._el, e);\n\n this._around = LngLat.convert(this._aroundCenter ? this._map.getCenter() : this._map.unproject(pos));\n this._aroundPoint = this._map.transform.locationPoint(this._around);\n if (!this._frameId) {\n this._frameId = true;\n this._handler._triggerRenderFrame();\n }\n }\n\n renderFrame() {\n if (!this._frameId) return;\n this._frameId = null;\n\n if (!this.isActive()) return;\n const tr = this._map.transform;\n\n // if we've had scroll events since the last render frame, consume the\n // accumulated delta, and update the target zoom level accordingly\n if (this._delta !== 0) {\n // For trackpad events and single mouse wheel ticks, use the default zoom rate\n const zoomRate = (this._type === 'wheel' && Math.abs(this._delta) > wheelZoomDelta) ? this._wheelZoomRate : this._defaultZoomRate;\n // Scale by sigmoid of scroll wheel delta.\n let scale = maxScalePerFrame / (1 + Math.exp(-Math.abs(this._delta * zoomRate)));\n\n if (this._delta < 0 && scale !== 0) {\n scale = 1 / scale;\n }\n\n const fromScale = typeof this._targetZoom === 'number' ? tr.zoomScale(this._targetZoom) : tr.scale;\n this._targetZoom = Math.min(tr.maxZoom, Math.max(tr.minZoom, tr.scaleZoom(fromScale * scale)));\n\n // if this is a mouse wheel, refresh the starting zoom and easing\n // function we're using to smooth out the zooming between wheel\n // events\n if (this._type === 'wheel') {\n this._startZoom = tr.zoom;\n this._easing = this._smoothOutEasing(200);\n }\n\n this._delta = 0;\n }\n\n const targetZoom = typeof this._targetZoom === 'number' ?\n this._targetZoom : tr.zoom;\n const startZoom = this._startZoom;\n const easing = this._easing;\n\n let finished = false;\n let zoom;\n if (this._type === 'wheel' && startZoom && easing) {\n assert(easing && typeof startZoom === 'number');\n\n const t = Math.min((browser.now() - this._lastWheelEventTime) / 200, 1);\n const k = easing(t);\n zoom = interpolate(startZoom, targetZoom, k);\n if (t < 1) {\n if (!this._frameId) {\n this._frameId = true;\n }\n } else {\n finished = true;\n }\n } else {\n zoom = targetZoom;\n finished = true;\n }\n\n this._active = true;\n\n if (finished) {\n this._active = false;\n this._finishTimeout = setTimeout(() => {\n this._zooming = false;\n this._handler._triggerRenderFrame();\n delete this._targetZoom;\n delete this._finishTimeout;\n }, 200);\n }\n\n return {\n noInertia: true,\n needsRenderFrame: !finished,\n zoomDelta: zoom - tr.zoom,\n around: this._aroundPoint,\n originalEvent: this._lastWheelEvent\n };\n }\n\n _smoothOutEasing(duration: number) {\n let easing = _ease;\n\n if (this._prevEase) {\n const ease = this._prevEase,\n t = (browser.now() - ease.start) / ease.duration,\n speed = ease.easing(t + 0.01) - ease.easing(t),\n\n // Quick hack to make new bezier that is continuous with last\n x = 0.27 / Math.sqrt(speed * speed + 0.0001) * 0.01,\n y = Math.sqrt(0.27 * 0.27 - x * x);\n\n easing = bezier(x, y, 0.25, 1);\n }\n\n this._prevEase = {\n start: browser.now(),\n duration,\n easing\n };\n\n return easing;\n }\n\n blur() {\n this.reset();\n }\n\n reset() {\n this._active = false;\n }\n}\n\nexport default ScrollZoomHandler;\n","// @flow\n\nimport type ClickZoomHandler from '../click_zoom';\nimport type TapZoomHandler from './../tap_zoom';\n\n/**\n * The `DoubleClickZoomHandler` allows the user to zoom the map at a point by\n * double clicking or double tapping.\n */\nexport default class DoubleClickZoomHandler {\n\n _clickZoom: ClickZoomHandler;\n _tapZoom: TapZoomHandler;\n\n /**\n * @private\n */\n constructor(clickZoom: ClickZoomHandler, TapZoom: TapZoomHandler) {\n this._clickZoom = clickZoom;\n this._tapZoom = TapZoom;\n }\n\n /**\n * Enables the \"double click to zoom\" interaction.\n *\n * @example\n * map.doubleClickZoom.enable();\n */\n enable() {\n this._clickZoom.enable();\n this._tapZoom.enable();\n }\n\n /**\n * Disables the \"double click to zoom\" interaction.\n *\n * @example\n * map.doubleClickZoom.disable();\n */\n disable() {\n this._clickZoom.disable();\n this._tapZoom.disable();\n }\n\n /**\n * Returns a Boolean indicating whether the \"double click to zoom\" interaction is enabled.\n *\n * @returns {boolean} `true` if the \"double click to zoom\" interaction is enabled.\n */\n isEnabled() {\n return this._clickZoom.isEnabled() && this._tapZoom.isEnabled();\n }\n\n /**\n * Returns a Boolean indicating whether the \"double click to zoom\" interaction is active, i.e. currently being used.\n *\n * @returns {boolean} `true` if the \"double click to zoom\" interaction is active.\n */\n isActive() {\n return this._clickZoom.isActive() || this._tapZoom.isActive();\n }\n}\n","// @flow\n\nimport type Point from '@mapbox/point-geometry';\nimport type Map from '../map';\n\nexport default class ClickZoomHandler {\n\n _enabled: boolean;\n _active: boolean;\n\n constructor() {\n this.reset();\n }\n\n reset() {\n this._active = false;\n }\n\n blur() {\n this.reset();\n }\n\n dblclick(e: MouseEvent, point: Point) {\n e.preventDefault();\n return {\n cameraAnimation: (map: Map) => {\n map.easeTo({\n duration: 300,\n zoom: map.getZoom() + (e.shiftKey ? -1 : 1),\n around: map.unproject(point)\n }, {originalEvent: e});\n }\n };\n }\n\n enable() {\n this._enabled = true;\n }\n\n disable() {\n this._enabled = false;\n this.reset();\n }\n\n isEnabled() {\n return this._enabled;\n }\n\n isActive() {\n return this._active;\n }\n}\n","// @flow\n\nimport {TapRecognizer, MAX_TAP_INTERVAL} from './tap_recognizer';\nimport type Point from '@mapbox/point-geometry';\n\nexport default class TapDragZoomHandler {\n\n _enabled: boolean;\n _active: boolean;\n _swipePoint: Point;\n _swipeTouch: number;\n _tapTime: number;\n _tap: TapRecognizer;\n\n constructor() {\n\n this._tap = new TapRecognizer({\n numTouches: 1,\n numTaps: 1\n });\n\n this.reset();\n }\n\n reset() {\n this._active = false;\n delete this._swipePoint;\n delete this._swipeTouch;\n delete this._tapTime;\n this._tap.reset();\n }\n\n touchstart(e: TouchEvent, points: Array, mapTouches: Array) {\n if (this._swipePoint) return;\n\n if (this._tapTime && e.timeStamp - this._tapTime > MAX_TAP_INTERVAL) {\n this.reset();\n }\n\n if (!this._tapTime) {\n this._tap.touchstart(e, points, mapTouches);\n } else if (mapTouches.length > 0) {\n this._swipePoint = points[0];\n this._swipeTouch = mapTouches[0].identifier;\n }\n\n }\n\n touchmove(e: TouchEvent, points: Array, mapTouches: Array) {\n if (!this._tapTime) {\n this._tap.touchmove(e, points, mapTouches);\n } else if (this._swipePoint) {\n if (mapTouches[0].identifier !== this._swipeTouch) {\n return;\n }\n\n const newSwipePoint = points[0];\n const dist = newSwipePoint.y - this._swipePoint.y;\n this._swipePoint = newSwipePoint;\n\n e.preventDefault();\n this._active = true;\n\n return {\n zoomDelta: dist / 128\n };\n }\n }\n\n touchend(e: TouchEvent, points: Array, mapTouches: Array) {\n if (!this._tapTime) {\n const point = this._tap.touchend(e, points, mapTouches);\n if (point) {\n this._tapTime = e.timeStamp;\n }\n } else if (this._swipePoint) {\n if (mapTouches.length === 0) {\n this.reset();\n }\n }\n }\n\n touchcancel() {\n this.reset();\n }\n\n enable() {\n this._enabled = true;\n }\n\n disable() {\n this._enabled = false;\n this.reset();\n }\n\n isEnabled() {\n return this._enabled;\n }\n\n isActive() {\n return this._active;\n }\n}\n","// @flow\n\nimport type {MousePanHandler} from '../mouse';\nimport type TouchPanHandler from './../touch_pan';\n\nexport type DragPanOptions = {\n linearity?: number;\n easing?: (t: number) => number;\n deceleration?: number;\n maxSpeed?: number;\n};\n\n/**\n * The `DragPanHandler` allows the user to pan the map by clicking and dragging\n * the cursor.\n */\nexport default class DragPanHandler {\n\n _el: HTMLElement;\n _mousePan: MousePanHandler;\n _touchPan: TouchPanHandler;\n _inertiaOptions: DragPanOptions\n\n /**\n * @private\n */\n constructor(el: HTMLElement, mousePan: MousePanHandler, touchPan: TouchPanHandler) {\n this._el = el;\n this._mousePan = mousePan;\n this._touchPan = touchPan;\n }\n\n /**\n * Enables the \"drag to pan\" interaction.\n *\n * @param {Object} [options] Options object\n * @param {number} [options.linearity=0] factor used to scale the drag velocity\n * @param {Function} [options.easing=bezier(0, 0, 0.3, 1)] easing function applled to `map.panTo` when applying the drag.\n * @param {number} [options.maxSpeed=1400] the maximum value of the drag velocity.\n * @param {number} [options.deceleration=2500] the rate at which the speed reduces after the pan ends.\n *\n * @example\n * map.dragPan.enable();\n * @example\n * map.dragPan.enable({\n * linearity: 0.3,\n * easing: bezier(0, 0, 0.3, 1),\n * maxSpeed: 1400,\n * deceleration: 2500,\n * });\n */\n enable(options?: DragPanOptions) {\n this._inertiaOptions = options || {};\n this._mousePan.enable();\n this._touchPan.enable();\n this._el.classList.add('mapboxgl-touch-drag-pan');\n }\n\n /**\n * Disables the \"drag to pan\" interaction.\n *\n * @example\n * map.dragPan.disable();\n */\n disable() {\n this._mousePan.disable();\n this._touchPan.disable();\n this._el.classList.remove('mapboxgl-touch-drag-pan');\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to pan\" interaction is enabled.\n *\n * @returns {boolean} `true` if the \"drag to pan\" interaction is enabled.\n */\n isEnabled() {\n return this._mousePan.isEnabled() && this._touchPan.isEnabled();\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to pan\" interaction is active, i.e. currently being used.\n *\n * @returns {boolean} `true` if the \"drag to pan\" interaction is active.\n */\n isActive() {\n return this._mousePan.isActive() || this._touchPan.isActive();\n }\n}\n","// @flow\n\nimport type {MouseRotateHandler, MousePitchHandler} from '../mouse';\n\n/**\n * The `DragRotateHandler` allows the user to rotate the map by clicking and\n * dragging the cursor while holding the right mouse button or `ctrl` key.\n */\nexport default class DragRotateHandler {\n\n _mouseRotate: MouseRotateHandler;\n _mousePitch: MousePitchHandler;\n _pitchWithRotate: boolean;\n\n /**\n * @param {Object} [options]\n * @param {number} [options.bearingSnap] The threshold, measured in degrees, that determines when the map's\n * bearing will snap to north.\n * @param {bool} [options.pitchWithRotate=true] Control the map pitch in addition to the bearing\n * @private\n */\n constructor(options: {pitchWithRotate: boolean}, mouseRotate: MouseRotateHandler, mousePitch: MousePitchHandler) {\n this._pitchWithRotate = options.pitchWithRotate;\n this._mouseRotate = mouseRotate;\n this._mousePitch = mousePitch;\n }\n\n /**\n * Enables the \"drag to rotate\" interaction.\n *\n * @example\n * map.dragRotate.enable();\n */\n enable() {\n this._mouseRotate.enable();\n if (this._pitchWithRotate) this._mousePitch.enable();\n }\n\n /**\n * Disables the \"drag to rotate\" interaction.\n *\n * @example\n * map.dragRotate.disable();\n */\n disable() {\n this._mouseRotate.disable();\n this._mousePitch.disable();\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to rotate\" interaction is enabled.\n *\n * @returns {boolean} `true` if the \"drag to rotate\" interaction is enabled.\n */\n isEnabled() {\n return this._mouseRotate.isEnabled() && (!this._pitchWithRotate || this._mousePitch.isEnabled());\n }\n\n /**\n * Returns a Boolean indicating whether the \"drag to rotate\" interaction is active, i.e. currently being used.\n *\n * @returns {boolean} `true` if the \"drag to rotate\" interaction is active.\n */\n isActive() {\n return this._mouseRotate.isActive() || this._mousePitch.isActive();\n }\n}\n","// @flow\n\nimport type {TouchZoomHandler, TouchRotateHandler} from '../touch_zoom_rotate';\nimport type TapDragZoomHandler from '../tap_drag_zoom';\n\n/**\n * The `TouchZoomRotateHandler` allows the user to zoom and rotate the map by\n * pinching on a touchscreen.\n *\n * They can zoom with one finger by double tapping and dragging. On the second tap,\n * hold the finger down and drag up or down to zoom in or out.\n */\nexport default class TouchZoomRotateHandler {\n\n _el: HTMLElement;\n _touchZoom: TouchZoomHandler;\n _touchRotate: TouchRotateHandler;\n _tapDragZoom: TapDragZoomHandler;\n _rotationDisabled: boolean;\n _enabled: boolean;\n\n /**\n * @private\n */\n constructor(el: HTMLElement, touchZoom: TouchZoomHandler, touchRotate: TouchRotateHandler, tapDragZoom: TapDragZoomHandler) {\n this._el = el;\n this._touchZoom = touchZoom;\n this._touchRotate = touchRotate;\n this._tapDragZoom = tapDragZoom;\n this._rotationDisabled = false;\n this._enabled = true;\n }\n\n /**\n * Enables the \"pinch to rotate and zoom\" interaction.\n *\n * @param {Object} [options] Options object.\n * @param {string} [options.around] If \"center\" is passed, map will zoom around the center\n *\n * @example\n * map.touchZoomRotate.enable();\n * @example\n * map.touchZoomRotate.enable({ around: 'center' });\n */\n enable(options: ?{around?: 'center'}) {\n this._touchZoom.enable(options);\n if (!this._rotationDisabled) this._touchRotate.enable(options);\n this._tapDragZoom.enable();\n this._el.classList.add('mapboxgl-touch-zoom-rotate');\n }\n\n /**\n * Disables the \"pinch to rotate and zoom\" interaction.\n *\n * @example\n * map.touchZoomRotate.disable();\n */\n disable() {\n this._touchZoom.disable();\n this._touchRotate.disable();\n this._tapDragZoom.disable();\n this._el.classList.remove('mapboxgl-touch-zoom-rotate');\n }\n\n /**\n * Returns a Boolean indicating whether the \"pinch to rotate and zoom\" interaction is enabled.\n *\n * @returns {boolean} `true` if the \"pinch to rotate and zoom\" interaction is enabled.\n */\n isEnabled() {\n return this._touchZoom.isEnabled() &&\n (this._rotationDisabled || this._touchRotate.isEnabled()) &&\n this._tapDragZoom.isEnabled();\n }\n\n /**\n * Returns true if the handler is enabled and has detected the start of a zoom/rotate gesture.\n *\n * @returns {boolean} //eslint-disable-line\n */\n isActive() {\n return this._touchZoom.isActive() || this._touchRotate.isActive() || this._tapDragZoom.isActive();\n }\n\n /**\n * Disables the \"pinch to rotate\" interaction, leaving the \"pinch to zoom\"\n * interaction enabled.\n *\n * @example\n * map.touchZoomRotate.disableRotation();\n */\n disableRotation() {\n this._rotationDisabled = true;\n this._touchRotate.disable();\n }\n\n /**\n * Enables the \"pinch to rotate\" interaction.\n *\n * @example\n * map.touchZoomRotate.enable();\n * map.touchZoomRotate.enableRotation();\n */\n enableRotation() {\n this._rotationDisabled = false;\n if (this._touchZoom.isEnabled()) this._touchRotate.enable();\n }\n}\n","// @flow\n\nimport {Event} from '../util/evented';\nimport DOM from '../util/dom';\nimport type Map from './map';\nimport HandlerInertia from './handler_inertia';\nimport {MapEventHandler, BlockableMapEventHandler} from './handler/map_event';\nimport BoxZoomHandler from './handler/box_zoom';\nimport TapZoomHandler from './handler/tap_zoom';\nimport {MousePanHandler, MouseRotateHandler, MousePitchHandler} from './handler/mouse';\nimport TouchPanHandler from './handler/touch_pan';\nimport {TouchZoomHandler, TouchRotateHandler, TouchPitchHandler} from './handler/touch_zoom_rotate';\nimport KeyboardHandler from './handler/keyboard';\nimport ScrollZoomHandler from './handler/scroll_zoom';\nimport DoubleClickZoomHandler from './handler/shim/dblclick_zoom';\nimport ClickZoomHandler from './handler/click_zoom';\nimport TapDragZoomHandler from './handler/tap_drag_zoom';\nimport DragPanHandler from './handler/shim/drag_pan';\nimport DragRotateHandler from './handler/shim/drag_rotate';\nimport TouchZoomRotateHandler from './handler/shim/touch_zoom_rotate';\nimport {bindAll, extend} from '../util/util';\nimport window from '../util/window';\nimport Point from '@mapbox/point-geometry';\nimport assert from 'assert';\n\nexport type InputEvent = MouseEvent | TouchEvent | KeyboardEvent | WheelEvent;\n\nconst isMoving = p => p.zoom || p.drag || p.pitch || p.rotate;\n\nclass RenderFrameEvent extends Event {\n type: 'renderFrame';\n timeStamp: number;\n}\n\n// Handlers interpret dom events and return camera changes that should be\n// applied to the map (`HandlerResult`s). The camera changes are all deltas.\n// The handler itself should have no knowledge of the map's current state.\n// This makes it easier to merge multiple results and keeps handlers simpler.\n// For example, if there is a mousedown and mousemove, the mousePan handler\n// would return a `panDelta` on the mousemove.\nexport interface Handler {\n enable(): void;\n disable(): void;\n isEnabled(): boolean;\n isActive(): boolean;\n\n // `reset` can be called by the manager at any time and must reset everything to it's original state\n reset(): void;\n\n // Handlers can optionally implement these methods.\n // They are called with dom events whenever those dom evens are received.\n +touchstart?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void;\n +touchmove?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void;\n +touchend?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void;\n +touchcancel?: (e: TouchEvent, points: Array, mapTouches: Array) => HandlerResult | void;\n +mousedown?: (e: MouseEvent, point: Point) => HandlerResult | void;\n +mousemove?: (e: MouseEvent, point: Point) => HandlerResult | void;\n +mouseup?: (e: MouseEvent, point: Point) => HandlerResult | void;\n +dblclick?: (e: MouseEvent, point: Point) => HandlerResult | void;\n +wheel?: (e: WheelEvent, point: Point) => HandlerResult | void;\n +keydown?: (e: KeyboardEvent) => HandlerResult | void;\n +keyup?: (e: KeyboardEvent) => HandlerResult | void;\n\n // `renderFrame` is the only non-dom event. It is called during render\n // frames and can be used to smooth camera changes (see scroll handler).\n +renderFrame?: () => HandlerResult | void;\n}\n\n// All handler methods that are called with events can optionally return a `HandlerResult`.\nexport type HandlerResult = {|\n panDelta?: Point,\n zoomDelta?: number,\n bearingDelta?: number,\n pitchDelta?: number,\n // the point to not move when changing the camera\n around?: Point | null,\n // same as above, except for pinch actions, which are given higher priority\n pinchAround?: Point | null,\n // A method that can fire a one-off easing by directly changing the map's camera.\n cameraAnimation?: (map: Map) => any;\n\n // The last three properties are needed by only one handler: scrollzoom.\n // The DOM event to be used as the `originalEvent` on any camera change events.\n originalEvent?: any,\n // Makes the manager trigger a frame, allowing the handler to return multiple results over time (see scrollzoom).\n needsRenderFrame?: boolean,\n // The camera changes won't get recorded for inertial zooming.\n noInertia?: boolean\n|};\n\nfunction hasChange(result: HandlerResult) {\n return (result.panDelta && result.panDelta.mag()) || result.zoomDelta || result.bearingDelta || result.pitchDelta;\n}\n\nclass HandlerManager {\n _map: Map;\n _el: HTMLElement;\n _handlers: Array<{ handlerName: string, handler: Handler, allowed: any }>;\n _eventsInProgress: Object;\n _frameId: number;\n _inertia: HandlerInertia;\n _bearingSnap: number;\n _handlersById: { [string]: Handler };\n _updatingCamera: boolean;\n _changes: Array<[HandlerResult, Object, any]>;\n _previousActiveHandlers: { [string]: Handler };\n _listeners: Array<[HTMLElement, string, void | {passive?: boolean, capture?: boolean}]>;\n\n constructor(map: Map, options: { interactive: boolean, pitchWithRotate: boolean, clickTolerance: number, bearingSnap: number}) {\n this._map = map;\n this._el = this._map.getCanvasContainer();\n this._handlers = [];\n this._handlersById = {};\n this._changes = [];\n\n this._inertia = new HandlerInertia(map);\n this._bearingSnap = options.bearingSnap;\n this._previousActiveHandlers = {};\n\n // Track whether map is currently moving, to compute start/move/end events\n this._eventsInProgress = {};\n\n this._addDefaultHandlers(options);\n\n bindAll(['handleEvent', 'handleWindowEvent'], this);\n\n const el = this._el;\n\n this._listeners = [\n // This needs to be `passive: true` so that a double tap fires two\n // pairs of touchstart/end events in iOS Safari 13. If this is set to\n // `passive: false` then the second pair of events is only fired if\n // preventDefault() is called on the first touchstart. Calling preventDefault()\n // undesirably prevents click events.\n [el, 'touchstart', {passive: true}],\n // This needs to be `passive: false` so that scrolls and pinches can be\n // prevented in browsers that don't support `touch-actions: none`, for example iOS Safari 12.\n [el, 'touchmove', {passive: false}],\n [el, 'touchend', undefined],\n [el, 'touchcancel', undefined],\n\n [el, 'mousedown', undefined],\n [el, 'mousemove', undefined],\n [el, 'mouseup', undefined],\n\n // Bind window-level event listeners for move and up/end events. In the absence of\n // the pointer capture API, which is not supported by all necessary platforms,\n // window-level event listeners give us the best shot at capturing events that\n // fall outside the map canvas element. Use `{capture: true}` for the move event\n // to prevent map move events from being fired during a drag.\n [window.document, 'mousemove', {capture: true}],\n [window.document, 'mouseup', undefined],\n\n [el, 'mouseover', undefined],\n [el, 'mouseout', undefined],\n [el, 'dblclick', undefined],\n [el, 'click', undefined],\n\n [el, 'keydown', {capture: false}],\n [el, 'keyup', undefined],\n\n [el, 'wheel', {passive: false}],\n [el, 'contextmenu', undefined],\n\n [window, 'blur', undefined]\n ];\n\n for (const [target, type, listenerOptions] of this._listeners) {\n DOM.addEventListener(target, type, target === window.document ? this.handleWindowEvent : this.handleEvent, listenerOptions);\n }\n }\n\n destroy() {\n for (const [target, type, listenerOptions] of this._listeners) {\n DOM.removeEventListener(target, type, target === window.document ? this.handleWindowEvent : this.handleEvent, listenerOptions);\n }\n }\n\n _addDefaultHandlers(options: { interactive: boolean, pitchWithRotate: boolean, clickTolerance: number }) {\n const map = this._map;\n const el = map.getCanvasContainer();\n this._add('mapEvent', new MapEventHandler(map, options));\n\n const boxZoom = map.boxZoom = new BoxZoomHandler(map, options);\n this._add('boxZoom', boxZoom);\n\n const tapZoom = new TapZoomHandler();\n const clickZoom = new ClickZoomHandler();\n map.doubleClickZoom = new DoubleClickZoomHandler(clickZoom, tapZoom);\n this._add('tapZoom', tapZoom);\n this._add('clickZoom', clickZoom);\n\n const tapDragZoom = new TapDragZoomHandler();\n this._add('tapDragZoom', tapDragZoom);\n\n const touchPitch = map.touchPitch = new TouchPitchHandler();\n this._add('touchPitch', touchPitch);\n\n const mouseRotate = new MouseRotateHandler(options);\n const mousePitch = new MousePitchHandler(options);\n map.dragRotate = new DragRotateHandler(options, mouseRotate, mousePitch);\n this._add('mouseRotate', mouseRotate, ['mousePitch']);\n this._add('mousePitch', mousePitch, ['mouseRotate']);\n\n const mousePan = new MousePanHandler(options);\n const touchPan = new TouchPanHandler(options);\n map.dragPan = new DragPanHandler(el, mousePan, touchPan);\n this._add('mousePan', mousePan);\n this._add('touchPan', touchPan, ['touchZoom', 'touchRotate']);\n\n const touchRotate = new TouchRotateHandler();\n const touchZoom = new TouchZoomHandler();\n map.touchZoomRotate = new TouchZoomRotateHandler(el, touchZoom, touchRotate, tapDragZoom);\n this._add('touchRotate', touchRotate, ['touchPan', 'touchZoom']);\n this._add('touchZoom', touchZoom, ['touchPan', 'touchRotate']);\n\n const scrollZoom = map.scrollZoom = new ScrollZoomHandler(map, this);\n this._add('scrollZoom', scrollZoom, ['mousePan']);\n\n const keyboard = map.keyboard = new KeyboardHandler();\n this._add('keyboard', keyboard);\n\n this._add('blockableMapEvent', new BlockableMapEventHandler(map));\n\n for (const name of ['boxZoom', 'doubleClickZoom', 'tapDragZoom', 'touchPitch', 'dragRotate', 'dragPan', 'touchZoomRotate', 'scrollZoom', 'keyboard']) {\n if (options.interactive && (options: any)[name]) {\n (map: any)[name].enable((options: any)[name]);\n }\n }\n }\n\n _add(handlerName: string, handler: Handler, allowed?: Array) {\n this._handlers.push({handlerName, handler, allowed});\n this._handlersById[handlerName] = handler;\n }\n\n stop(allowEndAnimation: boolean) {\n // do nothing if this method was triggered by a gesture update\n if (this._updatingCamera) return;\n\n for (const {handler} of this._handlers) {\n handler.reset();\n }\n this._inertia.clear();\n this._fireEvents({}, {}, allowEndAnimation);\n this._changes = [];\n }\n\n isActive() {\n for (const {handler} of this._handlers) {\n if (handler.isActive()) return true;\n }\n return false;\n }\n\n isZooming() {\n return !!this._eventsInProgress.zoom || this._map.scrollZoom.isZooming();\n }\n isRotating() {\n return !!this._eventsInProgress.rotate;\n }\n\n isMoving() {\n return Boolean(isMoving(this._eventsInProgress)) || this.isZooming();\n }\n\n _blockedByActive(activeHandlers: { [string]: Handler }, allowed: Array, myName: string) {\n for (const name in activeHandlers) {\n if (name === myName) continue;\n if (!allowed || allowed.indexOf(name) < 0) {\n return true;\n }\n }\n return false;\n }\n\n handleWindowEvent(e: InputEvent) {\n this.handleEvent(e, `${e.type}Window`);\n }\n\n _getMapTouches(touches: TouchList) {\n const mapTouches = [];\n for (const t of touches) {\n const target = ((t.target: any): Node);\n if (this._el.contains(target)) {\n mapTouches.push(t);\n }\n }\n return ((mapTouches: any): TouchList);\n }\n\n handleEvent(e: InputEvent | RenderFrameEvent, eventName?: string) {\n\n this._updatingCamera = true;\n assert(e.timeStamp !== undefined);\n\n const inputEvent = e.type === 'renderFrame' ? undefined : ((e: any): InputEvent);\n\n /*\n * We don't call e.preventDefault() for any events by default.\n * Handlers are responsible for calling it where necessary.\n */\n\n const mergedHandlerResult: HandlerResult = {needsRenderFrame: false};\n const eventsInProgress = {};\n const activeHandlers = {};\n\n const mapTouches = e.touches ? this._getMapTouches(((e: any): TouchEvent).touches) : undefined;\n const points = mapTouches ? DOM.touchPos(this._el, mapTouches) : DOM.mousePos(this._el, ((e: any): MouseEvent));\n\n for (const {handlerName, handler, allowed} of this._handlers) {\n if (!handler.isEnabled()) continue;\n\n let data: HandlerResult | void;\n if (this._blockedByActive(activeHandlers, allowed, handlerName)) {\n handler.reset();\n\n } else {\n if ((handler: any)[eventName || e.type]) {\n data = (handler: any)[eventName || e.type](e, points, mapTouches);\n this.mergeHandlerResult(mergedHandlerResult, eventsInProgress, data, handlerName, inputEvent);\n if (data && data.needsRenderFrame) {\n this._triggerRenderFrame();\n }\n }\n }\n\n if (data || handler.isActive()) {\n activeHandlers[handlerName] = handler;\n }\n }\n\n const deactivatedHandlers = {};\n for (const name in this._previousActiveHandlers) {\n if (!activeHandlers[name]) {\n deactivatedHandlers[name] = inputEvent;\n }\n }\n this._previousActiveHandlers = activeHandlers;\n\n if (Object.keys(deactivatedHandlers).length || hasChange(mergedHandlerResult)) {\n this._changes.push([mergedHandlerResult, eventsInProgress, deactivatedHandlers]);\n this._triggerRenderFrame();\n }\n\n if (Object.keys(activeHandlers).length || hasChange(mergedHandlerResult)) {\n this._map._stop(true);\n }\n\n this._updatingCamera = false;\n\n const {cameraAnimation} = mergedHandlerResult;\n if (cameraAnimation) {\n this._inertia.clear();\n this._fireEvents({}, {}, true);\n this._changes = [];\n cameraAnimation(this._map);\n }\n }\n\n mergeHandlerResult(mergedHandlerResult: HandlerResult, eventsInProgress: Object, handlerResult: HandlerResult, name: string, e?: InputEvent) {\n if (!handlerResult) return;\n\n extend(mergedHandlerResult, handlerResult);\n\n const eventData = {handlerName: name, originalEvent: handlerResult.originalEvent || e};\n\n // track which handler changed which camera property\n if (handlerResult.zoomDelta !== undefined) {\n eventsInProgress.zoom = eventData;\n }\n if (handlerResult.panDelta !== undefined) {\n eventsInProgress.drag = eventData;\n }\n if (handlerResult.pitchDelta !== undefined) {\n eventsInProgress.pitch = eventData;\n }\n if (handlerResult.bearingDelta !== undefined) {\n eventsInProgress.rotate = eventData;\n }\n\n }\n\n _applyChanges() {\n const combined = {};\n const combinedEventsInProgress = {};\n const combinedDeactivatedHandlers = {};\n\n for (const [change, eventsInProgress, deactivatedHandlers] of this._changes) {\n\n if (change.panDelta) combined.panDelta = (combined.panDelta || new Point(0, 0))._add(change.panDelta);\n if (change.zoomDelta) combined.zoomDelta = (combined.zoomDelta || 0) + change.zoomDelta;\n if (change.bearingDelta) combined.bearingDelta = (combined.bearingDelta || 0) + change.bearingDelta;\n if (change.pitchDelta) combined.pitchDelta = (combined.pitchDelta || 0) + change.pitchDelta;\n if (change.around !== undefined) combined.around = change.around;\n if (change.pinchAround !== undefined) combined.pinchAround = change.pinchAround;\n if (change.noInertia) combined.noInertia = change.noInertia;\n\n extend(combinedEventsInProgress, eventsInProgress);\n extend(combinedDeactivatedHandlers, deactivatedHandlers);\n }\n\n this._updateMapTransform(combined, combinedEventsInProgress, combinedDeactivatedHandlers);\n this._changes = [];\n }\n\n _updateMapTransform(combinedResult: any, combinedEventsInProgress: Object, deactivatedHandlers: Object) {\n\n const map = this._map;\n const tr = map.transform;\n\n if (!hasChange(combinedResult)) {\n return this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);\n }\n\n let {panDelta, zoomDelta, bearingDelta, pitchDelta, around, pinchAround} = combinedResult;\n\n if (pinchAround !== undefined) {\n around = pinchAround;\n }\n\n // stop any ongoing camera animations (easeTo, flyTo)\n map._stop(true);\n\n around = around || map.transform.centerPoint;\n const loc = tr.pointLocation(panDelta ? around.sub(panDelta) : around);\n if (bearingDelta) tr.bearing += bearingDelta;\n if (pitchDelta) tr.pitch += pitchDelta;\n if (zoomDelta) tr.zoom += zoomDelta;\n tr.setLocationAtPoint(loc, around);\n\n this._map._update();\n if (!combinedResult.noInertia) this._inertia.record(combinedResult);\n this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);\n\n }\n\n _fireEvents(newEventsInProgress: { [string]: Object }, deactivatedHandlers: Object, allowEndAnimation: boolean) {\n\n const wasMoving = isMoving(this._eventsInProgress);\n const nowMoving = isMoving(newEventsInProgress);\n\n const startEvents = {};\n\n for (const eventName in newEventsInProgress) {\n const {originalEvent} = newEventsInProgress[eventName];\n if (!this._eventsInProgress[eventName]) {\n startEvents[`${eventName}start`] = originalEvent;\n }\n this._eventsInProgress[eventName] = newEventsInProgress[eventName];\n }\n\n // fire start events only after this._eventsInProgress has been updated\n if (!wasMoving && nowMoving) {\n this._fireEvent('movestart', nowMoving.originalEvent);\n }\n\n for (const name in startEvents) {\n this._fireEvent(name, startEvents[name]);\n }\n\n if (nowMoving) {\n this._fireEvent('move', nowMoving.originalEvent);\n }\n\n for (const eventName in newEventsInProgress) {\n const {originalEvent} = newEventsInProgress[eventName];\n this._fireEvent(eventName, originalEvent);\n }\n\n const endEvents = {};\n\n let originalEndEvent;\n for (const eventName in this._eventsInProgress) {\n const {handlerName, originalEvent} = this._eventsInProgress[eventName];\n if (!this._handlersById[handlerName].isActive()) {\n delete this._eventsInProgress[eventName];\n originalEndEvent = deactivatedHandlers[handlerName] || originalEvent;\n endEvents[`${eventName}end`] = originalEndEvent;\n }\n }\n\n for (const name in endEvents) {\n this._fireEvent(name, endEvents[name]);\n }\n\n const stillMoving = isMoving(this._eventsInProgress);\n if (allowEndAnimation && (wasMoving || nowMoving) && !stillMoving) {\n this._updatingCamera = true;\n const inertialEase = this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions);\n\n const shouldSnapToNorth = bearing => bearing !== 0 && -this._bearingSnap < bearing && bearing < this._bearingSnap;\n\n if (inertialEase) {\n if (shouldSnapToNorth(inertialEase.bearing || this._map.getBearing())) {\n inertialEase.bearing = 0;\n }\n this._map.easeTo(inertialEase, {originalEvent: originalEndEvent});\n } else {\n this._map.fire(new Event('moveend', {originalEvent: originalEndEvent}));\n if (shouldSnapToNorth(this._map.getBearing())) {\n this._map.resetNorth();\n }\n }\n this._updatingCamera = false;\n }\n\n }\n\n _fireEvent(type: string, e: *) {\n this._map.fire(new Event(type, e ? {originalEvent: e} : {}));\n }\n\n _requestFrame() {\n this._map.triggerRepaint();\n return this._map._renderTaskQueue.add(timeStamp => {\n delete this._frameId;\n this.handleEvent(new RenderFrameEvent('renderFrame', {timeStamp}));\n this._applyChanges();\n });\n }\n\n _triggerRenderFrame() {\n if (this._frameId === undefined) {\n this._frameId = this._requestFrame();\n }\n }\n\n}\n\nexport default HandlerManager;\n","// @flow\n\nimport {\n bindAll,\n extend,\n warnOnce,\n clamp,\n wrap,\n ease as defaultEasing,\n pick\n} from '../util/util';\nimport {number as interpolate} from '../style-spec/util/interpolate';\nimport browser from '../util/browser';\nimport LngLat from '../geo/lng_lat';\nimport LngLatBounds from '../geo/lng_lat_bounds';\nimport Point from '@mapbox/point-geometry';\nimport {Event, Evented} from '../util/evented';\nimport assert from 'assert';\nimport {Debug} from '../util/debug';\n\nimport type Transform from '../geo/transform';\nimport type {LngLatLike} from '../geo/lng_lat';\nimport type {LngLatBoundsLike} from '../geo/lng_lat_bounds';\nimport type {TaskID} from '../util/task_queue';\nimport type {PointLike} from '@mapbox/point-geometry';\nimport type {PaddingOptions} from '../geo/edge_insets';\n\n/**\n * Options common to {@link Map#jumpTo}, {@link Map#easeTo}, and {@link Map#flyTo}, controlling the desired location,\n * zoom, bearing, and pitch of the camera. All properties are optional, and when a property is omitted, the current\n * camera value for that property will remain unchanged.\n *\n * @typedef {Object} CameraOptions\n * @property {LngLatLike} center The desired center.\n * @property {number} zoom The desired zoom level.\n * @property {number} bearing The desired bearing in degrees. The bearing is the compass direction that\n * is \"up\". For example, `bearing: 90` orients the map so that east is up.\n * @property {number} pitch The desired pitch in degrees. The pitch is the angle towards the horizon\n * measured in degrees with a range between 0 and 60 degrees. For example, pitch: 0 provides the appearance\n * of looking straight down at the map, while pitch: 60 tilts the user's perspective towards the horizon.\n * Increasing the pitch value is often used to display 3D objects.\n * @property {LngLatLike} around If `zoom` is specified, `around` determines the point around which the zoom is centered.\n * @property {PaddingOptions} padding Dimensions in pixels applied on each side of the viewport for shifting the vanishing point.\n * @example\n * // set the map's initial perspective with CameraOptions\n * var map = new mapboxgl.Map({\n * container: 'map',\n * style: 'mapbox://styles/mapbox/streets-v11',\n * center: [-73.5804, 45.53483],\n * pitch: 60,\n * bearing: -60,\n * zoom: 10\n * });\n * @see [Set pitch and bearing](https://docs.mapbox.com/mapbox-gl-js/example/set-perspective/)\n * @see [Jump to a series of locations](https://docs.mapbox.com/mapbox-gl-js/example/jump-to/)\n * @see [Fly to a location](https://docs.mapbox.com/mapbox-gl-js/example/flyto/)\n * @see [Display buildings in 3D](https://docs.mapbox.com/mapbox-gl-js/example/3d-buildings/)\n */\nexport type CameraOptions = {\n center?: LngLatLike,\n zoom?: number,\n bearing?: number,\n pitch?: number,\n around?: LngLatLike,\n padding?: PaddingOptions\n};\n\n/**\n * Options common to map movement methods that involve animation, such as {@link Map#panBy} and\n * {@link Map#easeTo}, controlling the duration and easing function of the animation. All properties\n * are optional.\n *\n * @typedef {Object} AnimationOptions\n * @property {number} duration The animation's duration, measured in milliseconds.\n * @property {Function} easing A function taking a time in the range 0..1 and returning a number where 0 is\n * the initial state and 1 is the final state.\n * @property {PointLike} offset of the target center relative to real map container center at the end of animation.\n * @property {boolean} animate If `false`, no animation will occur.\n * @property {boolean} essential If `true`, then the animation is considered essential and will not be affected by\n * [`prefers-reduced-motion`](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion).\n */\nexport type AnimationOptions = {\n duration?: number,\n easing?: (_: number) => number,\n offset?: PointLike,\n animate?: boolean,\n essential?: boolean\n};\n\n/**\n * Options for setting padding on calls to methods such as {@link Map#fitBounds}, {@link Map#fitScreenCoordinates}, and {@link Map#setPadding}. Adjust these options to set the amount of padding in pixels added to the edges of the canvas. Set a uniform padding on all edges or individual values for each edge. All properties of this object must be\n * non-negative integers.\n *\n * @typedef {Object} PaddingOptions\n * @property {number} top Padding in pixels from the top of the map canvas.\n * @property {number} bottom Padding in pixels from the bottom of the map canvas.\n * @property {number} left Padding in pixels from the left of the map canvas.\n * @property {number} right Padding in pixels from the right of the map canvas.\n *\n * @example\n * var bbox = [[-79, 43], [-73, 45]];\n * map.fitBounds(bbox, {\n * padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n *\n * @example\n * var bbox = [[-79, 43], [-73, 45]];\n * map.fitBounds(bbox, {\n * padding: 20\n * });\n * @see [Fit to the bounds of a LineString](https://docs.mapbox.com/mapbox-gl-js/example/zoomto-linestring/)\n * @see [Fit a map to a bounding box](https://docs.mapbox.com/mapbox-gl-js/example/fitbounds/)\n */\n\nclass Camera extends Evented {\n transform: Transform;\n _moving: boolean;\n _zooming: boolean;\n _rotating: boolean;\n _pitching: boolean;\n _padding: boolean;\n\n _bearingSnap: number;\n _easeStart: number;\n _easeOptions: {duration: number, easing: (_: number) => number};\n _easeId: string | void;\n\n _onEaseFrame: (_: number) => void;\n _onEaseEnd: (easeId?: string) => void;\n _easeFrameId: ?TaskID;\n\n +_requestRenderFrame: (() => void) => TaskID;\n +_cancelRenderFrame: (_: TaskID) => void;\n\n constructor(transform: Transform, options: {bearingSnap: number}) {\n super();\n this._moving = false;\n this._zooming = false;\n this.transform = transform;\n this._bearingSnap = options.bearingSnap;\n\n bindAll(['_renderFrameCallback'], this);\n\n //addAssertions(this);\n }\n\n /**\n * Returns the map's geographical centerpoint.\n *\n * @memberof Map#\n * @returns The map's geographical centerpoint.\n * @example\n * // return a LngLat object such as {lng: 0, lat: 0}\n * var center = map.getCenter();\n * // access longitude and latitude values directly\n * var {longitude, latitude} = map.getCenter();\n * @see Tutorial: [Use Mapbox GL JS in a React app](https://docs.mapbox.com/help/tutorials/use-mapbox-gl-js-with-react/#store-the-new-coordinates)\n */\n getCenter(): LngLat { return new LngLat(this.transform.center.lng, this.transform.center.lat); }\n\n /**\n * Sets the map's geographical centerpoint. Equivalent to `jumpTo({center: center})`.\n *\n * @memberof Map#\n * @param center The centerpoint to set.\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n * @example\n * map.setCenter([-74, 38]);\n */\n setCenter(center: LngLatLike, eventData?: Object) {\n return this.jumpTo({center}, eventData);\n }\n\n /**\n * Pans the map by the specified offset.\n *\n * @memberof Map#\n * @param offset `x` and `y` coordinates by which to pan the map.\n * @param options Options object\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/)\n */\n panBy(offset: PointLike, options?: AnimationOptions, eventData?: Object) {\n offset = Point.convert(offset).mult(-1);\n return this.panTo(this.transform.center, extend({offset}, options), eventData);\n }\n\n /**\n * Pans the map to the specified location with an animated transition.\n *\n * @memberof Map#\n * @param lnglat The location to pan the map to.\n * @param options Options describing the destination and animation of the transition.\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n * @example\n * map.panTo([-74, 38]);\n * @example\n * // Specify that the panTo animation should last 5000 milliseconds.\n * map.panTo([-74, 38], {duration: 5000});\n * @see [Update a feature in realtime](https://docs.mapbox.com/mapbox-gl-js/example/live-update-feature/)\n */\n panTo(lnglat: LngLatLike, options?: AnimationOptions, eventData?: Object) {\n return this.easeTo(extend({\n center: lnglat\n }, options), eventData);\n }\n\n /**\n * Returns the map's current zoom level.\n *\n * @memberof Map#\n * @returns The map's current zoom level.\n * @example\n * map.getZoom();\n */\n getZoom(): number { return this.transform.zoom; }\n\n /**\n * Sets the map's zoom level. Equivalent to `jumpTo({zoom: zoom})`.\n *\n * @memberof Map#\n * @param zoom The zoom level to set (0-20).\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires zoomstart\n * @fires move\n * @fires zoom\n * @fires moveend\n * @fires zoomend\n * @returns {Map} `this`\n * @example\n * // Zoom to the zoom level 5 without an animated transition\n * map.setZoom(5);\n */\n setZoom(zoom: number, eventData?: Object) {\n this.jumpTo({zoom}, eventData);\n return this;\n }\n\n /**\n * Zooms the map to the specified zoom level, with an animated transition.\n *\n * @memberof Map#\n * @param zoom The zoom level to transition to.\n * @param options Options object\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires zoomstart\n * @fires move\n * @fires zoom\n * @fires moveend\n * @fires zoomend\n * @returns {Map} `this`\n * @example\n * // Zoom to the zoom level 5 without an animated transition\n * map.zoomTo(5);\n * // Zoom to the zoom level 8 with an animated transition\n * map.zoomTo(8, {\n * duration: 2000,\n * offset: [100, 50]\n * });\n */\n zoomTo(zoom: number, options: ? AnimationOptions, eventData?: Object) {\n return this.easeTo(extend({\n zoom\n }, options), eventData);\n }\n\n /**\n * Increases the map's zoom level by 1.\n *\n * @memberof Map#\n * @param options Options object\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires zoomstart\n * @fires move\n * @fires zoom\n * @fires moveend\n * @fires zoomend\n * @returns {Map} `this`\n * @example\n * // zoom the map in one level with a custom animation duration\n * map.zoomIn({duration: 1000});\n */\n zoomIn(options?: AnimationOptions, eventData?: Object) {\n this.zoomTo(this.getZoom() + 1, options, eventData);\n return this;\n }\n\n /**\n * Decreases the map's zoom level by 1.\n *\n * @memberof Map#\n * @param options Options object\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires zoomstart\n * @fires move\n * @fires zoom\n * @fires moveend\n * @fires zoomend\n * @returns {Map} `this`\n * @example\n * // zoom the map out one level with a custom animation offset\n * map.zoomOut({offset: [80, 60]});\n */\n zoomOut(options?: AnimationOptions, eventData?: Object) {\n this.zoomTo(this.getZoom() - 1, options, eventData);\n return this;\n }\n\n /**\n * Returns the map's current bearing. The bearing is the compass direction that is \"up\"; for example, a bearing\n * of 90° orients the map so that east is up.\n *\n * @memberof Map#\n * @returns The map's current bearing.\n * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/)\n */\n getBearing(): number { return this.transform.bearing; }\n\n /**\n * Sets the map's bearing (rotation). The bearing is the compass direction that is \"up\"; for example, a bearing\n * of 90° orients the map so that east is up.\n *\n * Equivalent to `jumpTo({bearing: bearing})`.\n *\n * @memberof Map#\n * @param bearing The desired bearing.\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n * @example\n * // rotate the map to 90 degrees\n * map.setBearing(90);\n */\n setBearing(bearing: number, eventData?: Object) {\n this.jumpTo({bearing}, eventData);\n return this;\n }\n\n /**\n * Returns the current padding applied around the map viewport.\n *\n * @memberof Map#\n * @returns The current padding around the map viewport.\n */\n getPadding(): PaddingOptions { return this.transform.padding; }\n\n /**\n * Sets the padding in pixels around the viewport.\n *\n * Equivalent to `jumpTo({padding: padding})`.\n *\n * @memberof Map#\n * @param padding The desired padding. Format: { left: number, right: number, top: number, bottom: number }\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n * @example\n * // Sets a left padding of 300px, and a top padding of 50px\n * map.setPadding({ left: 300, top: 50 });\n */\n setPadding(padding: PaddingOptions, eventData?: Object) {\n this.jumpTo({padding}, eventData);\n return this;\n }\n\n /**\n * Rotates the map to the specified bearing, with an animated transition. The bearing is the compass direction\n * that is \\\"up\\\"; for example, a bearing of 90° orients the map so that east is up.\n *\n * @memberof Map#\n * @param bearing The desired bearing.\n * @param options Options object\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n */\n rotateTo(bearing: number, options?: AnimationOptions, eventData?: Object) {\n return this.easeTo(extend({\n bearing\n }, options), eventData);\n }\n\n /**\n * Rotates the map so that north is up (0° bearing), with an animated transition.\n *\n * @memberof Map#\n * @param options Options object\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n */\n resetNorth(options?: AnimationOptions, eventData?: Object) {\n this.rotateTo(0, extend({duration: 1000}, options), eventData);\n return this;\n }\n\n /**\n * Rotates and pitches the map so that north is up (0° bearing) and pitch is 0°, with an animated transition.\n *\n * @memberof Map#\n * @param options Options object\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n */\n resetNorthPitch(options?: AnimationOptions, eventData?: Object) {\n this.easeTo(extend({\n bearing: 0,\n pitch: 0,\n duration: 1000\n }, options), eventData);\n return this;\n }\n\n /**\n * Snaps the map so that north is up (0° bearing), if the current bearing is close enough to it (i.e. within the\n * `bearingSnap` threshold).\n *\n * @memberof Map#\n * @param options Options object\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n */\n snapToNorth(options?: AnimationOptions, eventData?: Object) {\n if (Math.abs(this.getBearing()) < this._bearingSnap) {\n return this.resetNorth(options, eventData);\n }\n return this;\n }\n\n /**\n * Returns the map's current pitch (tilt).\n *\n * @memberof Map#\n * @returns The map's current pitch, measured in degrees away from the plane of the screen.\n */\n getPitch(): number { return this.transform.pitch; }\n\n /**\n * Sets the map's pitch (tilt). Equivalent to `jumpTo({pitch: pitch})`.\n *\n * @memberof Map#\n * @param pitch The pitch to set, measured in degrees away from the plane of the screen (0-60).\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires pitchstart\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n */\n setPitch(pitch: number, eventData?: Object) {\n this.jumpTo({pitch}, eventData);\n return this;\n }\n\n /**\n * @memberof Map#\n * @param {LngLatBoundsLike} bounds Calculate the center for these bounds in the viewport and use\n * the highest zoom level up to and including `Map#getMaxZoom()` that fits\n * in the viewport. LngLatBounds represent a box that is always axis-aligned with bearing 0.\n * @param options Options object\n * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds.\n * @param {number} [options.bearing=0] Desired map bearing at end of animation, in degrees.\n * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels.\n * @param {number} [options.maxZoom] The maximum zoom level to allow when the camera would transition to the specified bounds.\n * @returns {CameraOptions | void} If map is able to fit to provided bounds, returns `CameraOptions` with\n * `center`, `zoom`, and `bearing`. If map is unable to fit, method will warn and return undefined.\n * @example\n * var bbox = [[-79, 43], [-73, 45]];\n * var newCameraTransform = map.cameraForBounds(bbox, {\n * padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n */\n cameraForBounds(bounds: LngLatBoundsLike, options?: CameraOptions): void | CameraOptions & AnimationOptions {\n bounds = LngLatBounds.convert(bounds);\n const bearing = options && options.bearing || 0;\n return this._cameraForBoxAndBearing(bounds.getNorthWest(), bounds.getSouthEast(), bearing, options);\n }\n\n /**\n * Calculate the center of these two points in the viewport and use\n * the highest zoom level up to and including `Map#getMaxZoom()` that fits\n * the points in the viewport at the specified bearing.\n * @memberof Map#\n * @param {LngLatLike} p0 First point\n * @param {LngLatLike} p1 Second point\n * @param bearing Desired map bearing at end of animation, in degrees\n * @param options\n * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds.\n * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels.\n * @param {number} [options.maxZoom] The maximum zoom level to allow when the camera would transition to the specified bounds.\n * @returns {CameraOptions | void} If map is able to fit to provided bounds, returns `CameraOptions` with\n * `center`, `zoom`, and `bearing`. If map is unable to fit, method will warn and return undefined.\n * @private\n * @example\n * var p0 = [-79, 43];\n * var p1 = [-73, 45];\n * var bearing = 90;\n * var newCameraTransform = map._cameraForBoxAndBearing(p0, p1, bearing, {\n * padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n */\n _cameraForBoxAndBearing(p0: LngLatLike, p1: LngLatLike, bearing: number, options?: CameraOptions): void | CameraOptions & AnimationOptions {\n const defaultPadding = {\n top: 0,\n bottom: 0,\n right: 0,\n left: 0\n };\n options = extend({\n padding: defaultPadding,\n offset: [0, 0],\n maxZoom: this.transform.maxZoom\n }, options);\n\n if (typeof options.padding === 'number') {\n const p = options.padding;\n options.padding = {\n top: p,\n bottom: p,\n right: p,\n left: p\n };\n }\n\n options.padding = extend(defaultPadding, options.padding);\n const tr = this.transform;\n const edgePadding = tr.padding;\n\n // We want to calculate the upper right and lower left of the box defined by p0 and p1\n // in a coordinate system rotate to match the destination bearing.\n const p0world = tr.project(LngLat.convert(p0));\n const p1world = tr.project(LngLat.convert(p1));\n const p0rotated = p0world.rotate(-bearing * Math.PI / 180);\n const p1rotated = p1world.rotate(-bearing * Math.PI / 180);\n\n const upperRight = new Point(Math.max(p0rotated.x, p1rotated.x), Math.max(p0rotated.y, p1rotated.y));\n const lowerLeft = new Point(Math.min(p0rotated.x, p1rotated.x), Math.min(p0rotated.y, p1rotated.y));\n\n // Calculate zoom: consider the original bbox and padding.\n const size = upperRight.sub(lowerLeft);\n const scaleX = (tr.width - (edgePadding.left + edgePadding.right + options.padding.left + options.padding.right)) / size.x;\n const scaleY = (tr.height - (edgePadding.top + edgePadding.bottom + options.padding.top + options.padding.bottom)) / size.y;\n\n if (scaleY < 0 || scaleX < 0) {\n warnOnce(\n 'Map cannot fit within canvas with the given bounds, padding, and/or offset.'\n );\n return;\n }\n\n const zoom = Math.min(tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY)), options.maxZoom);\n\n // Calculate center: apply the zoom, the configured offset, as well as offset that exists as a result of padding.\n const offset = (typeof options.offset.x === 'number') ? new Point(options.offset.x, options.offset.y) : Point.convert(options.offset);\n const paddingOffsetX = (options.padding.left - options.padding.right) / 2;\n const paddingOffsetY = (options.padding.top - options.padding.bottom) / 2;\n const paddingOffset = new Point(paddingOffsetX, paddingOffsetY);\n const rotatedPaddingOffset = paddingOffset.rotate(bearing * Math.PI / 180);\n const offsetAtInitialZoom = offset.add(rotatedPaddingOffset);\n const offsetAtFinalZoom = offsetAtInitialZoom.mult(tr.scale / tr.zoomScale(zoom));\n\n const center = tr.unproject(p0world.add(p1world).div(2).sub(offsetAtFinalZoom));\n\n return {\n center,\n zoom,\n bearing\n };\n }\n\n /**\n * Pans and zooms the map to contain its visible area within the specified geographical bounds.\n * This function will also reset the map's bearing to 0 if bearing is nonzero.\n *\n * @memberof Map#\n * @param bounds Center these bounds in the viewport and use the highest\n * zoom level up to and including `Map#getMaxZoom()` that fits them in the viewport.\n * @param {Object} [options] Options supports all properties from {@link AnimationOptions} and {@link CameraOptions} in addition to the fields below.\n * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds.\n * @param {boolean} [options.linear=false] If `true`, the map transitions using\n * {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}. See\n * those functions and {@link AnimationOptions} for information about options available.\n * @param {Function} [options.easing] An easing function for the animated transition. See {@link AnimationOptions}.\n * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels.\n * @param {number} [options.maxZoom] The maximum zoom level to allow when the map view transitions to the specified bounds.\n * @param {Object} [eventData] Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n\t * @example\n * var bbox = [[-79, 43], [-73, 45]];\n * map.fitBounds(bbox, {\n * padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n * @see [Fit a map to a bounding box](https://www.mapbox.com/mapbox-gl-js/example/fitbounds/)\n */\n fitBounds(bounds: LngLatBoundsLike, options?: AnimationOptions & CameraOptions, eventData?: Object) {\n return this._fitInternal(\n this.cameraForBounds(bounds, options),\n options,\n eventData);\n }\n\n /**\n * Pans, rotates and zooms the map to to fit the box made by points p0 and p1\n * once the map is rotated to the specified bearing. To zoom without rotating,\n * pass in the current map bearing.\n *\n * @memberof Map#\n * @param p0 First point on screen, in pixel coordinates\n * @param p1 Second point on screen, in pixel coordinates\n * @param bearing Desired map bearing at end of animation, in degrees\n * @param options Options object\n * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds.\n * @param {boolean} [options.linear=false] If `true`, the map transitions using\n * {@link Map#easeTo}. If `false`, the map transitions using {@link Map#flyTo}. See\n * those functions and {@link AnimationOptions} for information about options available.\n * @param {Function} [options.easing] An easing function for the animated transition. See {@link AnimationOptions}.\n * @param {PointLike} [options.offset=[0, 0]] The center of the given bounds relative to the map's center, measured in pixels.\n * @param {number} [options.maxZoom] The maximum zoom level to allow when the map view transitions to the specified bounds.\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires moveend\n * @returns {Map} `this`\n\t * @example\n * var p0 = [220, 400];\n * var p1 = [500, 900];\n * map.fitScreenCoordinates(p0, p1, map.getBearing(), {\n * padding: {top: 10, bottom:25, left: 15, right: 5}\n * });\n * @see Used by {@link BoxZoomHandler}\n */\n fitScreenCoordinates(p0: PointLike, p1: PointLike, bearing: number, options?: AnimationOptions & CameraOptions, eventData?: Object) {\n return this._fitInternal(\n this._cameraForBoxAndBearing(\n this.transform.pointLocation(Point.convert(p0)),\n this.transform.pointLocation(Point.convert(p1)),\n bearing,\n options),\n options,\n eventData);\n }\n\n _fitInternal(calculatedOptions?: CameraOptions & AnimationOptions, options?: AnimationOptions & CameraOptions, eventData?: Object) {\n // cameraForBounds warns + returns undefined if unable to fit:\n if (!calculatedOptions) return this;\n\n options = extend(calculatedOptions, options);\n // Explictly remove the padding field because, calculatedOptions already accounts for padding by setting zoom and center accordingly.\n delete options.padding;\n\n return options.linear ?\n this.easeTo(options, eventData) :\n this.flyTo(options, eventData);\n }\n\n /**\n * Changes any combination of center, zoom, bearing, and pitch, without\n * an animated transition. The map will retain its current values for any\n * details not specified in `options`.\n *\n * @memberof Map#\n * @param options Options object\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires zoomstart\n * @fires pitchstart\n * @fires rotate\n * @fires move\n * @fires zoom\n * @fires pitch\n * @fires moveend\n * @fires zoomend\n * @fires pitchend\n * @returns {Map} `this`\n * @example\n * // jump to coordinates at current zoom\n * map.jumpTo({center: [0, 0]});\n * // jump with zoom, pitch, and bearing options\n * map.jumpTo({\n * center: [0, 0],\n * zoom: 8,\n * pitch: 45,\n * bearing: 90\n * });\n * @see [Jump to a series of locations](https://docs.mapbox.com/mapbox-gl-js/example/jump-to/)\n * @see [Update a feature in realtime](https://docs.mapbox.com/mapbox-gl-js/example/live-update-feature/)\n */\n jumpTo(options: CameraOptions, eventData?: Object) {\n this.stop();\n\n const tr = this.transform;\n let zoomChanged = false,\n bearingChanged = false,\n pitchChanged = false;\n\n if ('zoom' in options && tr.zoom !== +options.zoom) {\n zoomChanged = true;\n tr.zoom = +options.zoom;\n }\n\n if (options.center !== undefined) {\n tr.center = LngLat.convert(options.center);\n }\n\n if ('bearing' in options && tr.bearing !== +options.bearing) {\n bearingChanged = true;\n tr.bearing = +options.bearing;\n }\n\n if ('pitch' in options && tr.pitch !== +options.pitch) {\n pitchChanged = true;\n tr.pitch = +options.pitch;\n }\n\n if (options.padding != null && !tr.isPaddingEqual(options.padding)) {\n tr.padding = options.padding;\n }\n\n this.fire(new Event('movestart', eventData))\n .fire(new Event('move', eventData));\n\n if (zoomChanged) {\n this.fire(new Event('zoomstart', eventData))\n .fire(new Event('zoom', eventData))\n .fire(new Event('zoomend', eventData));\n }\n\n if (bearingChanged) {\n this.fire(new Event('rotatestart', eventData))\n .fire(new Event('rotate', eventData))\n .fire(new Event('rotateend', eventData));\n }\n\n if (pitchChanged) {\n this.fire(new Event('pitchstart', eventData))\n .fire(new Event('pitch', eventData))\n .fire(new Event('pitchend', eventData));\n }\n\n return this.fire(new Event('moveend', eventData));\n }\n\n /**\n * Changes any combination of `center`, `zoom`, `bearing`, `pitch`, and `padding` with an animated transition\n * between old and new values. The map will retain its current values for any\n * details not specified in `options`.\n *\n * Note: The transition will happen instantly if the user has enabled\n * the `reduced motion` accesibility feature enabled in their operating system,\n * unless `options` includes `essential: true`.\n *\n * @memberof Map#\n * @param options Options describing the destination and animation of the transition.\n * Accepts {@link CameraOptions} and {@link AnimationOptions}.\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires zoomstart\n * @fires pitchstart\n * @fires rotate\n * @fires move\n * @fires zoom\n * @fires pitch\n * @fires moveend\n * @fires zoomend\n * @fires pitchend\n * @returns {Map} `this`\n * @see [Navigate the map with game-like controls](https://www.mapbox.com/mapbox-gl-js/example/game-controls/)\n */\n easeTo(options: CameraOptions & AnimationOptions & {easeId?: string}, eventData?: Object) {\n this._stop(false, options.easeId);\n\n options = extend({\n offset: [0, 0],\n duration: 500,\n easing: defaultEasing\n }, options);\n\n if (options.animate === false || (!options.essential && browser.prefersReducedMotion)) options.duration = 0;\n\n const tr = this.transform,\n startZoom = this.getZoom(),\n startBearing = this.getBearing(),\n startPitch = this.getPitch(),\n startPadding = this.getPadding(),\n\n zoom = 'zoom' in options ? +options.zoom : startZoom,\n bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing,\n pitch = 'pitch' in options ? +options.pitch : startPitch,\n padding = 'padding' in options ? options.padding : tr.padding;\n\n const offsetAsPoint = Point.convert(options.offset);\n let pointAtOffset = tr.centerPoint.add(offsetAsPoint);\n const locationAtOffset = tr.pointLocation(pointAtOffset);\n const center = LngLat.convert(options.center || locationAtOffset);\n this._normalizeCenter(center);\n\n const from = tr.project(locationAtOffset);\n const delta = tr.project(center).sub(from);\n const finalScale = tr.zoomScale(zoom - startZoom);\n\n let around, aroundPoint;\n\n if (options.around) {\n around = LngLat.convert(options.around);\n aroundPoint = tr.locationPoint(around);\n }\n\n const currently = {\n moving: this._moving,\n zooming: this._zooming,\n rotating: this._rotating,\n pitching: this._pitching\n };\n\n this._zooming = this._zooming || (zoom !== startZoom);\n this._rotating = this._rotating || (startBearing !== bearing);\n this._pitching = this._pitching || (pitch !== startPitch);\n this._padding = !tr.isPaddingEqual(padding);\n\n this._easeId = options.easeId;\n this._prepareEase(eventData, options.noMoveStart, currently);\n\n this._ease((k) => {\n if (this._zooming) {\n tr.zoom = interpolate(startZoom, zoom, k);\n }\n if (this._rotating) {\n tr.bearing = interpolate(startBearing, bearing, k);\n }\n if (this._pitching) {\n tr.pitch = interpolate(startPitch, pitch, k);\n }\n if (this._padding) {\n tr.interpolatePadding(startPadding, padding, k);\n // When padding is being applied, Transform#centerPoint is changing continously,\n // thus we need to recalculate offsetPoint every fra,e\n pointAtOffset = tr.centerPoint.add(offsetAsPoint);\n }\n\n if (around) {\n tr.setLocationAtPoint(around, aroundPoint);\n } else {\n const scale = tr.zoomScale(tr.zoom - startZoom);\n const base = zoom > startZoom ?\n Math.min(2, finalScale) :\n Math.max(0.5, finalScale);\n const speedup = Math.pow(base, 1 - k);\n const newCenter = tr.unproject(from.add(delta.mult(k * speedup)).mult(scale));\n tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset);\n }\n\n this._fireMoveEvents(eventData);\n\n }, (interruptingEaseId?: string) => {\n this._afterEase(eventData, interruptingEaseId);\n }, options);\n\n return this;\n }\n\n _prepareEase(eventData?: Object, noMoveStart: boolean, currently: Object = {}) {\n this._moving = true;\n\n if (!noMoveStart && !currently.moving) {\n this.fire(new Event('movestart', eventData));\n }\n if (this._zooming && !currently.zooming) {\n this.fire(new Event('zoomstart', eventData));\n }\n if (this._rotating && !currently.rotating) {\n this.fire(new Event('rotatestart', eventData));\n }\n if (this._pitching && !currently.pitching) {\n this.fire(new Event('pitchstart', eventData));\n }\n }\n\n _fireMoveEvents(eventData?: Object) {\n this.fire(new Event('move', eventData));\n if (this._zooming) {\n this.fire(new Event('zoom', eventData));\n }\n if (this._rotating) {\n this.fire(new Event('rotate', eventData));\n }\n if (this._pitching) {\n this.fire(new Event('pitch', eventData));\n }\n }\n\n _afterEase(eventData?: Object, easeId?: string) {\n // if this easing is being stopped to start another easing with\n // the same id then don't fire any events to avoid extra start/stop events\n if (this._easeId && easeId && this._easeId === easeId) {\n return;\n }\n delete this._easeId;\n\n const wasZooming = this._zooming;\n const wasRotating = this._rotating;\n const wasPitching = this._pitching;\n this._moving = false;\n this._zooming = false;\n this._rotating = false;\n this._pitching = false;\n this._padding = false;\n\n if (wasZooming) {\n this.fire(new Event('zoomend', eventData));\n }\n if (wasRotating) {\n this.fire(new Event('rotateend', eventData));\n }\n if (wasPitching) {\n this.fire(new Event('pitchend', eventData));\n }\n this.fire(new Event('moveend', eventData));\n }\n\n /**\n * Changes any combination of center, zoom, bearing, and pitch, animating the transition along a curve that\n * evokes flight. The animation seamlessly incorporates zooming and panning to help\n * the user maintain her bearings even after traversing a great distance.\n *\n * Note: The animation will be skipped, and this will behave equivalently to `jumpTo`\n * if the user has the `reduced motion` accesibility feature enabled in their operating system,\n * unless 'options' includes `essential: true`.\n *\n * @memberof Map#\n * @param {Object} options Options describing the destination and animation of the transition.\n * Accepts {@link CameraOptions}, {@link AnimationOptions},\n * and the following additional options.\n * @param {number} [options.curve=1.42] The zooming \"curve\" that will occur along the\n * flight path. A high value maximizes zooming for an exaggerated animation, while a low\n * value minimizes zooming for an effect closer to {@link Map#easeTo}. 1.42 is the average\n * value selected by participants in the user study discussed in\n * [van Wijk (2003)](https://www.win.tue.nl/~vanwijk/zoompan.pdf). A value of\n * `Math.pow(6, 0.25)` would be equivalent to the root mean squared average velocity. A\n * value of 1 would produce a circular motion.\n * @param {number} [options.minZoom] The zero-based zoom level at the peak of the flight path. If\n * `options.curve` is specified, this option is ignored.\n * @param {number} [options.speed=1.2] The average speed of the animation defined in relation to\n * `options.curve`. A speed of 1.2 means that the map appears to move along the flight path\n * by 1.2 times `options.curve` screenfuls every second. A _screenful_ is the map's visible span.\n * It does not correspond to a fixed physical distance, but varies by zoom level.\n * @param {number} [options.screenSpeed] The average speed of the animation measured in screenfuls\n * per second, assuming a linear timing curve. If `options.speed` is specified, this option is ignored.\n * @param {number} [options.maxDuration] The animation's maximum duration, measured in milliseconds.\n * If duration exceeds maximum duration, it resets to 0.\n * @param eventData Additional properties to be added to event objects of events triggered by this method.\n * @fires movestart\n * @fires zoomstart\n * @fires pitchstart\n * @fires move\n * @fires zoom\n * @fires rotate\n * @fires pitch\n * @fires moveend\n * @fires zoomend\n * @fires pitchend\n * @returns {Map} `this`\n * @example\n * // fly with default options to null island\n * map.flyTo({center: [0, 0], zoom: 9});\n * // using flyTo options\n * map.flyTo({\n * center: [0, 0],\n * zoom: 9,\n * speed: 0.2,\n * curve: 1,\n * easing(t) {\n * return t;\n * }\n * });\n * @see [Fly to a location](https://www.mapbox.com/mapbox-gl-js/example/flyto/)\n * @see [Slowly fly to a location](https://www.mapbox.com/mapbox-gl-js/example/flyto-options/)\n * @see [Fly to a location based on scroll position](https://www.mapbox.com/mapbox-gl-js/example/scroll-fly-to/)\n */\n flyTo(options: Object, eventData?: Object) {\n // Fall through to jumpTo if user has set prefers-reduced-motion\n if (!options.essential && browser.prefersReducedMotion) {\n const coercedOptions = (pick(options, ['center', 'zoom', 'bearing', 'pitch', 'around']): CameraOptions);\n return this.jumpTo(coercedOptions, eventData);\n }\n\n // This method implements an “optimal path” animation, as detailed in:\n //\n // Van Wijk, Jarke J.; Nuij, Wim A. A. “Smooth and efficient zooming and panning.” INFOVIS\n // ’03. pp. 15–22. .\n //\n // Where applicable, local variable documentation begins with the associated variable or\n // function in van Wijk (2003).\n\n this.stop();\n\n options = extend({\n offset: [0, 0],\n speed: 1.2,\n curve: 1.42,\n easing: defaultEasing\n }, options);\n\n const tr = this.transform,\n startZoom = this.getZoom(),\n startBearing = this.getBearing(),\n startPitch = this.getPitch(),\n startPadding = this.getPadding();\n\n const zoom = 'zoom' in options ? clamp(+options.zoom, tr.minZoom, tr.maxZoom) : startZoom;\n const bearing = 'bearing' in options ? this._normalizeBearing(options.bearing, startBearing) : startBearing;\n const pitch = 'pitch' in options ? +options.pitch : startPitch;\n const padding = 'padding' in options ? options.padding : tr.padding;\n\n const scale = tr.zoomScale(zoom - startZoom);\n const offsetAsPoint = Point.convert(options.offset);\n let pointAtOffset = tr.centerPoint.add(offsetAsPoint);\n const locationAtOffset = tr.pointLocation(pointAtOffset);\n const center = LngLat.convert(options.center || locationAtOffset);\n this._normalizeCenter(center);\n\n const from = tr.project(locationAtOffset);\n const delta = tr.project(center).sub(from);\n\n let rho = options.curve;\n\n // w₀: Initial visible span, measured in pixels at the initial scale.\n const w0 = Math.max(tr.width, tr.height),\n // w₁: Final visible span, measured in pixels with respect to the initial scale.\n w1 = w0 / scale,\n // Length of the flight path as projected onto the ground plane, measured in pixels from\n // the world image origin at the initial scale.\n u1 = delta.mag();\n\n if ('minZoom' in options) {\n const minZoom = clamp(Math.min(options.minZoom, startZoom, zoom), tr.minZoom, tr.maxZoom);\n // wm: Maximum visible span, measured in pixels with respect to the initial\n // scale.\n const wMax = w0 / tr.zoomScale(minZoom - startZoom);\n rho = Math.sqrt(wMax / u1 * 2);\n }\n\n // ρ²\n const rho2 = rho * rho;\n\n /**\n * rᵢ: Returns the zoom-out factor at one end of the animation.\n *\n * @param i 0 for the ascent or 1 for the descent.\n * @private\n */\n function r(i) {\n const b = (w1 * w1 - w0 * w0 + (i ? -1 : 1) * rho2 * rho2 * u1 * u1) / (2 * (i ? w1 : w0) * rho2 * u1);\n return Math.log(Math.sqrt(b * b + 1) - b);\n }\n\n function sinh(n) { return (Math.exp(n) - Math.exp(-n)) / 2; }\n function cosh(n) { return (Math.exp(n) + Math.exp(-n)) / 2; }\n function tanh(n) { return sinh(n) / cosh(n); }\n\n // r₀: Zoom-out factor during ascent.\n const r0 = r(0);\n\n // w(s): Returns the visible span on the ground, measured in pixels with respect to the\n // initial scale. Assumes an angular field of view of 2 arctan ½ ≈ 53°.\n let w: (_: number) => number = function (s) {\n return (cosh(r0) / cosh(r0 + rho * s));\n };\n\n // u(s): Returns the distance along the flight path as projected onto the ground plane,\n // measured in pixels from the world image origin at the initial scale.\n let u: (_: number) => number = function (s) {\n return w0 * ((cosh(r0) * tanh(r0 + rho * s) - sinh(r0)) / rho2) / u1;\n };\n\n // S: Total length of the flight path, measured in ρ-screenfuls.\n let S = (r(1) - r0) / rho;\n\n // When u₀ = u₁, the optimal path doesn’t require both ascent and descent.\n if (Math.abs(u1) < 0.000001 || !isFinite(S)) {\n // Perform a more or less instantaneous transition if the path is too short.\n if (Math.abs(w0 - w1) < 0.000001) return this.easeTo(options, eventData);\n\n const k = w1 < w0 ? -1 : 1;\n S = Math.abs(Math.log(w1 / w0)) / rho;\n\n u = function() { return 0; };\n w = function(s) { return Math.exp(k * rho * s); };\n }\n\n if ('duration' in options) {\n options.duration = +options.duration;\n } else {\n const V = 'screenSpeed' in options ? +options.screenSpeed / rho : +options.speed;\n options.duration = 1000 * S / V;\n }\n\n if (options.maxDuration && options.duration > options.maxDuration) {\n options.duration = 0;\n }\n\n this._zooming = true;\n this._rotating = (startBearing !== bearing);\n this._pitching = (pitch !== startPitch);\n this._padding = !tr.isPaddingEqual(padding);\n\n this._prepareEase(eventData, false);\n\n this._ease((k) => {\n // s: The distance traveled along the flight path, measured in ρ-screenfuls.\n const s = k * S;\n const scale = 1 / w(s);\n tr.zoom = k === 1 ? zoom : startZoom + tr.scaleZoom(scale);\n\n if (this._rotating) {\n tr.bearing = interpolate(startBearing, bearing, k);\n }\n if (this._pitching) {\n tr.pitch = interpolate(startPitch, pitch, k);\n }\n if (this._padding) {\n tr.interpolatePadding(startPadding, padding, k);\n // When padding is being applied, Transform#centerPoint is changing continously,\n // thus we need to recalculate offsetPoint every frame\n pointAtOffset = tr.centerPoint.add(offsetAsPoint);\n }\n\n const newCenter = k === 1 ? center : tr.unproject(from.add(delta.mult(u(s))).mult(scale));\n tr.setLocationAtPoint(tr.renderWorldCopies ? newCenter.wrap() : newCenter, pointAtOffset);\n\n this._fireMoveEvents(eventData);\n\n }, () => this._afterEase(eventData), options);\n\n return this;\n }\n\n isEasing() {\n return !!this._easeFrameId;\n }\n\n /**\n * Stops any animated transition underway.\n *\n * @memberof Map#\n * @returns {Map} `this`\n */\n stop(): this {\n return this._stop();\n }\n\n _stop(allowGestures?: boolean, easeId?: string): this {\n if (this._easeFrameId) {\n this._cancelRenderFrame(this._easeFrameId);\n delete this._easeFrameId;\n delete this._onEaseFrame;\n }\n\n if (this._onEaseEnd) {\n // The _onEaseEnd function might emit events which trigger new\n // animation, which sets a new _onEaseEnd. Ensure we don't delete\n // it unintentionally.\n const onEaseEnd = this._onEaseEnd;\n delete this._onEaseEnd;\n onEaseEnd.call(this, easeId);\n }\n if (!allowGestures) {\n const handlers = (this: any).handlers;\n if (handlers) handlers.stop(false);\n }\n return this;\n }\n\n _ease(frame: (_: number) => void,\n finish: () => void,\n options: {animate: boolean, duration: number, easing: (_: number) => number}) {\n if (options.animate === false || options.duration === 0) {\n frame(1);\n finish();\n } else {\n this._easeStart = browser.now();\n this._easeOptions = options;\n this._onEaseFrame = frame;\n this._onEaseEnd = finish;\n this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback);\n }\n }\n\n // Callback for map._requestRenderFrame\n _renderFrameCallback() {\n const t = Math.min((browser.now() - this._easeStart) / this._easeOptions.duration, 1);\n this._onEaseFrame(this._easeOptions.easing(t));\n if (t < 1) {\n this._easeFrameId = this._requestRenderFrame(this._renderFrameCallback);\n } else {\n this.stop();\n }\n }\n\n // convert bearing so that it's numerically close to the current one so that it interpolates properly\n _normalizeBearing(bearing: number, currentBearing: number) {\n bearing = wrap(bearing, -180, 180);\n const diff = Math.abs(bearing - currentBearing);\n if (Math.abs(bearing - 360 - currentBearing) < diff) bearing -= 360;\n if (Math.abs(bearing + 360 - currentBearing) < diff) bearing += 360;\n return bearing;\n }\n\n // If a path crossing the antimeridian would be shorter, extend the final coordinate so that\n // interpolating between the two endpoints will cross it.\n _normalizeCenter(center: LngLat) {\n const tr = this.transform;\n if (!tr.renderWorldCopies || tr.lngRange) return;\n\n const delta = center.lng - tr.center.lng;\n center.lng +=\n delta > 180 ? -360 :\n delta < -180 ? 360 : 0;\n }\n}\n\n// In debug builds, check that camera change events are fired in the correct order.\n// - ___start events needs to be fired before ___ and ___end events\n// - another ___start event can't be fired before a ___end event has been fired for the previous one\nfunction addAssertions(camera: Camera) { //eslint-disable-line\n Debug.run(() => {\n const inProgress = {};\n\n ['drag', 'zoom', 'rotate', 'pitch', 'move'].forEach(name => {\n inProgress[name] = false;\n\n camera.on(`${name}start`, () => {\n assert(!inProgress[name], `\"${name}start\" fired twice without a \"${name}end\"`);\n inProgress[name] = true;\n assert(inProgress.move);\n });\n\n camera.on(name, () => {\n assert(inProgress[name]);\n assert(inProgress.move);\n });\n\n camera.on(`${name}end`, () => {\n assert(inProgress.move);\n assert(inProgress[name]);\n inProgress[name] = false;\n });\n });\n\n // Canary used to test whether this function is stripped in prod build\n canary = 'canary debug run';\n });\n}\n\nlet canary; //eslint-disable-line\n\nexport default Camera;\n","// @flow\n\nimport DOM from '../../util/dom';\nimport {bindAll} from '../../util/util';\nimport config from '../../util/config';\n\nimport type Map from '../map';\n\ntype Options = {\n compact?: boolean,\n customAttribution?: string | Array\n};\n\n/**\n * An `AttributionControl` control presents the map's [attribution information](https://docs.mapbox.com/help/how-mapbox-works/attribution/).\n *\n * @implements {IControl}\n * @param {Object} [options]\n * @param {boolean} [options.compact] If `true`, force a compact attribution that shows the full attribution on mouse hover. If `false`, force the full attribution control. The default is a responsive attribution that collapses when the map is less than 640 pixels wide. **Attribution should not be collapsed if it can comfortably fit on the map. `compact` should only be used to modify default attribution when map size makes it impossible to fit [default attribution](https://docs.mapbox.com/help/how-mapbox-works/attribution/) and when the automatic compact resizing for default settings are not sufficient.**\n * @param {string | Array} [options.customAttribution] String or strings to show in addition to any other attributions.\n * @example\n * var map = new mapboxgl.Map({attributionControl: false})\n * .addControl(new mapboxgl.AttributionControl({\n * compact: true\n * }));\n */\nclass AttributionControl {\n options: Options;\n _map: Map;\n _container: HTMLElement;\n _innerContainer: HTMLElement;\n _compactButton: HTMLButtonElement;\n _editLink: ?HTMLAnchorElement;\n _attribHTML: string;\n styleId: string;\n styleOwner: string;\n\n constructor(options: Options = {}) {\n this.options = options;\n\n bindAll([\n '_toggleAttribution',\n '_updateEditLink',\n '_updateData',\n '_updateCompact'\n ], this);\n }\n\n getDefaultPosition() {\n return 'bottom-right';\n }\n\n onAdd(map: Map) {\n const compact = this.options && this.options.compact;\n\n this._map = map;\n this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-attrib');\n this._compactButton = DOM.create('button', 'mapboxgl-ctrl-attrib-button', this._container);\n this._compactButton.addEventListener('click', this._toggleAttribution);\n this._setElementTitle(this._compactButton, 'ToggleAttribution');\n this._innerContainer = DOM.create('div', 'mapboxgl-ctrl-attrib-inner', this._container);\n this._innerContainer.setAttribute('role', 'list');\n\n if (compact) {\n this._container.classList.add('mapboxgl-compact');\n }\n\n this._updateAttributions();\n this._updateEditLink();\n\n this._map.on('styledata', this._updateData);\n this._map.on('sourcedata', this._updateData);\n this._map.on('moveend', this._updateEditLink);\n\n if (compact === undefined) {\n this._map.on('resize', this._updateCompact);\n this._updateCompact();\n }\n\n return this._container;\n }\n\n onRemove() {\n DOM.remove(this._container);\n\n this._map.off('styledata', this._updateData);\n this._map.off('sourcedata', this._updateData);\n this._map.off('moveend', this._updateEditLink);\n this._map.off('resize', this._updateCompact);\n\n this._map = (undefined: any);\n this._attribHTML = (undefined: any);\n }\n\n _setElementTitle(element: HTMLElement, title: string) {\n const str = this._map._getUIString(`AttributionControl.${title}`);\n element.title = str;\n element.setAttribute('aria-label', str);\n }\n\n _toggleAttribution() {\n if (this._container.classList.contains('mapboxgl-compact-show')) {\n this._container.classList.remove('mapboxgl-compact-show');\n this._compactButton.setAttribute('aria-pressed', 'false');\n } else {\n this._container.classList.add('mapboxgl-compact-show');\n this._compactButton.setAttribute('aria-pressed', 'true');\n }\n }\n\n _updateEditLink() {\n let editLink = this._editLink;\n if (!editLink) {\n editLink = this._editLink = (this._container.querySelector('.mapbox-improve-map'): any);\n }\n\n const params = [\n {key: 'owner', value: this.styleOwner},\n {key: 'id', value: this.styleId},\n {key: 'access_token', value: this._map._requestManager._customAccessToken || config.ACCESS_TOKEN}\n ];\n\n if (editLink) {\n const paramString = params.reduce((acc, next, i) => {\n if (next.value) {\n acc += `${next.key}=${next.value}${i < params.length - 1 ? '&' : ''}`;\n }\n return acc;\n }, `?`);\n editLink.href = `${config.FEEDBACK_URL}/${paramString}${this._map._hash ? this._map._hash.getHashString(true) : ''}`;\n editLink.rel = 'noopener nofollow';\n this._setElementTitle(editLink, 'MapFeedback');\n }\n }\n\n _updateData(e: any) {\n if (e && (e.sourceDataType === 'metadata' || e.sourceDataType === 'visibility' || e.dataType === 'style')) {\n this._updateAttributions();\n this._updateEditLink();\n }\n }\n\n _updateAttributions() {\n if (!this._map.style) return;\n let attributions: Array = [];\n if (this.options.customAttribution) {\n if (Array.isArray(this.options.customAttribution)) {\n attributions = attributions.concat(\n this.options.customAttribution.map(attribution => {\n if (typeof attribution !== 'string') return '';\n return attribution;\n })\n );\n } else if (typeof this.options.customAttribution === 'string') {\n attributions.push(this.options.customAttribution);\n }\n }\n\n if (this._map.style.stylesheet) {\n const stylesheet: any = this._map.style.stylesheet;\n this.styleOwner = stylesheet.owner;\n this.styleId = stylesheet.id;\n }\n\n const sourceCaches = this._map.style.sourceCaches;\n for (const id in sourceCaches) {\n const sourceCache = sourceCaches[id];\n if (sourceCache.used) {\n const source = sourceCache.getSource();\n if (source.attribution && attributions.indexOf(source.attribution) < 0) {\n attributions.push(source.attribution);\n }\n }\n }\n\n // remove any entries that are substrings of another entry.\n // first sort by length so that substrings come first\n attributions.sort((a, b) => a.length - b.length);\n attributions = attributions.filter((attrib, i) => {\n for (let j = i + 1; j < attributions.length; j++) {\n if (attributions[j].indexOf(attrib) >= 0) { return false; }\n }\n return true;\n });\n\n // check if attribution string is different to minimize DOM changes\n const attribHTML = attributions.join(' | ');\n if (attribHTML === this._attribHTML) return;\n\n this._attribHTML = attribHTML;\n\n if (attributions.length) {\n this._innerContainer.innerHTML = attribHTML;\n this._container.classList.remove('mapboxgl-attrib-empty');\n } else {\n this._container.classList.add('mapboxgl-attrib-empty');\n }\n // remove old DOM node from _editLink\n this._editLink = null;\n }\n\n _updateCompact() {\n if (this._map.getCanvasContainer().offsetWidth <= 640) {\n this._container.classList.add('mapboxgl-compact');\n } else {\n this._container.classList.remove('mapboxgl-compact', 'mapboxgl-compact-show');\n }\n }\n\n}\n\nexport default AttributionControl;\n","// @flow\n\nimport DOM from '../../util/dom';\n\nimport {bindAll} from '../../util/util';\n\nimport type Map from '../map';\n\n/**\n * A `LogoControl` is a control that adds the Mapbox watermark\n * to the map as required by the [terms of service](https://www.mapbox.com/tos/) for Mapbox\n * vector tiles and core styles.\n *\n * @implements {IControl}\n * @private\n**/\n\nclass LogoControl {\n _map: Map;\n _container: HTMLElement;\n\n constructor() {\n bindAll(['_updateLogo'], this);\n bindAll(['_updateCompact'], this);\n }\n\n onAdd(map: Map) {\n this._map = map;\n this._container = DOM.create('div', 'mapboxgl-ctrl');\n const anchor = DOM.create('a', 'mapboxgl-ctrl-logo');\n anchor.target = \"_blank\";\n anchor.rel = \"noopener nofollow\";\n anchor.href = \"https://www.mapbox.com/\";\n anchor.setAttribute(\"aria-label\", this._map._getUIString('LogoControl.Title'));\n anchor.setAttribute(\"rel\", \"noopener nofollow\");\n this._container.appendChild(anchor);\n this._container.style.display = 'none';\n\n this._map.on('sourcedata', this._updateLogo);\n this._updateLogo();\n\n this._map.on('resize', this._updateCompact);\n this._updateCompact();\n\n return this._container;\n }\n\n onRemove() {\n DOM.remove(this._container);\n this._map.off('sourcedata', this._updateLogo);\n this._map.off('resize', this._updateCompact);\n }\n\n getDefaultPosition() {\n return 'bottom-left';\n }\n\n _updateLogo(e: any) {\n if (!e || e.sourceDataType === 'metadata') {\n this._container.style.display = this._logoRequired() ? 'block' : 'none';\n }\n }\n\n _logoRequired() {\n if (!this._map.style) return;\n\n const sourceCaches = this._map.style.sourceCaches;\n for (const id in sourceCaches) {\n const source = sourceCaches[id].getSource();\n if (source.mapbox_logo) {\n return true;\n }\n }\n\n return false;\n }\n\n _updateCompact() {\n const containerChildren = this._container.children;\n if (containerChildren.length) {\n const anchor = containerChildren[0];\n if (this._map.getCanvasContainer().offsetWidth < 250) {\n anchor.classList.add('mapboxgl-compact');\n } else {\n anchor.classList.remove('mapboxgl-compact');\n }\n }\n }\n\n}\n\nexport default LogoControl;\n","// @flow strict\nimport assert from 'assert';\n\nexport type TaskID = number; // can't mark opaque due to https://github.com/flowtype/flow-remove-types/pull/61\ntype Task = {\n callback: (timeStamp: number) => void;\n id: TaskID;\n cancelled: boolean;\n};\n\nclass TaskQueue {\n _queue: Array;\n _id: TaskID;\n _cleared: boolean;\n _currentlyRunning: Array | false;\n\n constructor() {\n this._queue = [];\n this._id = 0;\n this._cleared = false;\n this._currentlyRunning = false;\n }\n\n add(callback: (timeStamp: number) => void): TaskID {\n const id = ++this._id;\n const queue = this._queue;\n queue.push({callback, id, cancelled: false});\n return id;\n }\n\n remove(id: TaskID) {\n const running = this._currentlyRunning;\n const queue = running ? this._queue.concat(running) : this._queue;\n for (const task of queue) {\n if (task.id === id) {\n task.cancelled = true;\n return;\n }\n }\n }\n\n run(timeStamp: number = 0) {\n assert(!this._currentlyRunning);\n const queue = this._currentlyRunning = this._queue;\n\n // Tasks queued by callbacks in the current queue should be executed\n // on the next run, not the current run.\n this._queue = [];\n\n for (const task of queue) {\n if (task.cancelled) continue;\n task.callback(timeStamp);\n if (this._cleared) break;\n }\n\n this._cleared = false;\n this._currentlyRunning = false;\n }\n\n clear() {\n if (this._currentlyRunning) {\n this._cleared = true;\n }\n this._queue = [];\n }\n}\n\nexport default TaskQueue;\n","// @flow\n\nconst defaultLocale = {\n 'AttributionControl.ToggleAttribution': 'Toggle attribution',\n 'AttributionControl.MapFeedback': 'Map feedback',\n 'FullscreenControl.Enter': 'Enter fullscreen',\n 'FullscreenControl.Exit': 'Exit fullscreen',\n 'GeolocateControl.FindMyLocation': 'Find my location',\n 'GeolocateControl.LocationNotAvailable': 'Location not available',\n 'LogoControl.Title': 'Mapbox logo',\n 'NavigationControl.ResetBearing': 'Reset bearing to north',\n 'NavigationControl.ZoomIn': 'Zoom in',\n 'NavigationControl.ZoomOut': 'Zoom out',\n 'ScaleControl.Feet': 'ft',\n 'ScaleControl.Meters': 'm',\n 'ScaleControl.Kilometers': 'km',\n 'ScaleControl.Miles': 'mi',\n 'ScaleControl.NauticalMiles': 'nm'\n\n};\n\nexport default defaultLocale;\n","// @flow\n\nimport {version} from '../../package.json';\nimport {extend, bindAll, warnOnce, uniqueId} from '../util/util';\nimport browser from '../util/browser';\nimport window from '../util/window';\nconst {HTMLImageElement, HTMLElement, ImageBitmap} = window;\nimport DOM from '../util/dom';\nimport {getImage, getJSON, ResourceType} from '../util/ajax';\nimport {RequestManager} from '../util/mapbox';\nimport Style from '../style/style';\nimport EvaluationParameters from '../style/evaluation_parameters';\nimport Painter from '../render/painter';\nimport Transform from '../geo/transform';\nimport Hash from './hash';\nimport HandlerManager from './handler_manager';\nimport Camera from './camera';\nimport LngLat from '../geo/lng_lat';\nimport LngLatBounds from '../geo/lng_lat_bounds';\nimport Point from '@mapbox/point-geometry';\nimport AttributionControl from './control/attribution_control';\nimport LogoControl from './control/logo_control';\nimport isSupported from '@mapbox/mapbox-gl-supported';\nimport {RGBAImage} from '../util/image';\nimport {Event, ErrorEvent} from '../util/evented';\nimport {MapMouseEvent} from './events';\nimport TaskQueue from '../util/task_queue';\nimport webpSupported from '../util/webp_supported';\nimport {PerformanceMarkers, PerformanceUtils} from '../util/performance';\n\nimport {setCacheLimits} from '../util/tile_request_cache';\n\nimport type {PointLike} from '@mapbox/point-geometry';\nimport type {RequestTransformFunction} from '../util/mapbox';\nimport type {LngLatLike} from '../geo/lng_lat';\nimport type {LngLatBoundsLike} from '../geo/lng_lat_bounds';\nimport type {StyleOptions, StyleSetterOptions} from '../style/style';\nimport type {MapEvent, MapDataEvent} from './events';\nimport type {CustomLayerInterface} from '../style/style_layer/custom_style_layer';\nimport type {StyleImageInterface, StyleImageMetadata} from '../style/style_image';\n\nimport type ScrollZoomHandler from './handler/scroll_zoom';\nimport type BoxZoomHandler from './handler/box_zoom';\nimport type {TouchPitchHandler} from './handler/touch_zoom_rotate';\nimport type DragRotateHandler from './handler/shim/drag_rotate';\nimport type DragPanHandler, {DragPanOptions} from './handler/shim/drag_pan';\nimport type KeyboardHandler from './handler/keyboard';\nimport type DoubleClickZoomHandler from './handler/shim/dblclick_zoom';\nimport type TouchZoomRotateHandler from './handler/shim/touch_zoom_rotate';\nimport defaultLocale from './default_locale';\nimport type {TaskID} from '../util/task_queue';\nimport type {Cancelable} from '../types/cancelable';\nimport type {\n LayerSpecification,\n FilterSpecification,\n StyleSpecification,\n LightSpecification,\n SourceSpecification\n} from '../style-spec/types';\n\ntype ControlPosition = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n/* eslint-disable no-use-before-define */\ntype IControl = {\n onAdd(map: Map): HTMLElement;\n onRemove(map: Map): void;\n\n +getDefaultPosition?: () => ControlPosition;\n}\n/* eslint-enable no-use-before-define */\n\ntype MapOptions = {\n hash?: boolean | string,\n interactive?: boolean,\n container: HTMLElement | string,\n bearingSnap?: number,\n attributionControl?: boolean,\n customAttribution?: string | Array,\n logoPosition?: ControlPosition,\n failIfMajorPerformanceCaveat?: boolean,\n preserveDrawingBuffer?: boolean,\n antialias?: boolean,\n refreshExpiredTiles?: boolean,\n maxBounds?: LngLatBoundsLike,\n scrollZoom?: boolean,\n minZoom?: ?number,\n maxZoom?: ?number,\n minPitch?: ?number,\n maxPitch?: ?number,\n boxZoom?: boolean,\n dragRotate?: boolean,\n dragPan?: DragPanOptions,\n keyboard?: boolean,\n doubleClickZoom?: boolean,\n touchZoomRotate?: boolean,\n touchPitch?: boolean,\n trackResize?: boolean,\n center?: LngLatLike,\n zoom?: number,\n bearing?: number,\n pitch?: number,\n renderWorldCopies?: boolean,\n maxTileCacheSize?: number,\n transformRequest?: RequestTransformFunction,\n accessToken: string,\n locale?: Object\n};\n\nconst defaultMinZoom = -2;\nconst defaultMaxZoom = 22;\n\n// the default values, but also the valid range\nconst defaultMinPitch = 0;\nconst defaultMaxPitch = 60;\n\nconst defaultOptions = {\n center: [0, 0],\n zoom: 0,\n bearing: 0,\n pitch: 0,\n\n minZoom: defaultMinZoom,\n maxZoom: defaultMaxZoom,\n\n minPitch: defaultMinPitch,\n maxPitch: defaultMaxPitch,\n\n interactive: true,\n scrollZoom: true,\n boxZoom: true,\n dragRotate: true,\n dragPan: true,\n keyboard: true,\n doubleClickZoom: true,\n touchZoomRotate: true,\n touchPitch: true,\n\n bearingSnap: 7,\n clickTolerance: 3,\n pitchWithRotate: true,\n\n hash: false,\n attributionControl: true,\n\n failIfMajorPerformanceCaveat: false,\n preserveDrawingBuffer: false,\n trackResize: true,\n renderWorldCopies: true,\n refreshExpiredTiles: true,\n maxTileCacheSize: null,\n localIdeographFontFamily: 'sans-serif',\n transformRequest: null,\n accessToken: null,\n fadeDuration: 300,\n crossSourceCollisions: true\n};\n\n/**\n * The `Map` object represents the map on your page. It exposes methods\n * and properties that enable you to programmatically change the map,\n * and fires events as users interact with it.\n *\n * You create a `Map` by specifying a `container` and other options.\n * Then Mapbox GL JS initializes the map on the page and returns your `Map`\n * object.\n *\n * @extends Evented\n * @param {Object} options\n * @param {HTMLElement|string} options.container The HTML element in which Mapbox GL JS will render the map, or the element's string `id`. The specified element must have no children.\n * @param {number} [options.minZoom=0] The minimum zoom level of the map (0-24).\n * @param {number} [options.maxZoom=22] The maximum zoom level of the map (0-24).\n * @param {number} [options.minPitch=0] The minimum pitch of the map (0-60).\n * @param {number} [options.maxPitch=60] The maximum pitch of the map (0-60).\n * @param {Object|string} [options.style] The map's Mapbox style. This must be an a JSON object conforming to\n * the schema described in the [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/), or a URL to\n * such JSON.\n *\n * To load a style from the Mapbox API, you can use a URL of the form `mapbox://styles/:owner/:style`,\n * where `:owner` is your Mapbox account name and `:style` is the style ID. Or you can use one of the following\n * [the predefined Mapbox styles](https://www.mapbox.com/maps/):\n *\n * * `mapbox://styles/mapbox/streets-v11`\n * * `mapbox://styles/mapbox/outdoors-v11`\n * * `mapbox://styles/mapbox/light-v10`\n * * `mapbox://styles/mapbox/dark-v10`\n * * `mapbox://styles/mapbox/satellite-v9`\n * * `mapbox://styles/mapbox/satellite-streets-v11`\n * * `mapbox://styles/mapbox/navigation-preview-day-v4`\n * * `mapbox://styles/mapbox/navigation-preview-night-v4`\n * * `mapbox://styles/mapbox/navigation-guidance-day-v4`\n * * `mapbox://styles/mapbox/navigation-guidance-night-v4`\n *\n * Tilesets hosted with Mapbox can be style-optimized if you append `?optimize=true` to the end of your style URL, like `mapbox://styles/mapbox/streets-v11?optimize=true`.\n * Learn more about style-optimized vector tiles in our [API documentation](https://www.mapbox.com/api-documentation/maps/#retrieve-tiles).\n *\n * @param {(boolean|string)} [options.hash=false] If `true`, the map's position (zoom, center latitude, center longitude, bearing, and pitch) will be synced with the hash fragment of the page's URL.\n * For example, `http://path/to/my/page.html#2.59/39.26/53.07/-24.1/60`.\n * An additional string may optionally be provided to indicate a parameter-styled hash,\n * e.g. http://path/to/my/page.html#map=2.59/39.26/53.07/-24.1/60&foo=bar, where foo\n * is a custom parameter and bar is an arbitrary hash distinct from the map hash.\n * @param {boolean} [options.interactive=true] If `false`, no mouse, touch, or keyboard listeners will be attached to the map, so it will not respond to interaction.\n * @param {number} [options.bearingSnap=7] The threshold, measured in degrees, that determines when the map's\n * bearing will snap to north. For example, with a `bearingSnap` of 7, if the user rotates\n * the map within 7 degrees of north, the map will automatically snap to exact north.\n * @param {boolean} [options.pitchWithRotate=true] If `false`, the map's pitch (tilt) control with \"drag to rotate\" interaction will be disabled.\n * @param {number} [options.clickTolerance=3] The max number of pixels a user can shift the mouse pointer during a click for it to be considered a valid click (as opposed to a mouse drag).\n * @param {boolean} [options.attributionControl=true] If `true`, an {@link AttributionControl} will be added to the map.\n * @param {string | Array} [options.customAttribution] String or strings to show in an {@link AttributionControl}. Only applicable if `options.attributionControl` is `true`.\n * @param {string} [options.logoPosition='bottom-left'] A string representing the position of the Mapbox wordmark on the map. Valid options are `top-left`,`top-right`, `bottom-left`, `bottom-right`.\n * @param {boolean} [options.failIfMajorPerformanceCaveat=false] If `true`, map creation will fail if the performance of Mapbox\n * GL JS would be dramatically worse than expected (i.e. a software renderer would be used).\n * @param {boolean} [options.preserveDrawingBuffer=false] If `true`, the map's canvas can be exported to a PNG using `map.getCanvas().toDataURL()`. This is `false` by default as a performance optimization.\n * @param {boolean} [options.antialias] If `true`, the gl context will be created with MSAA antialiasing, which can be useful for antialiasing custom layers. this is `false` by default as a performance optimization.\n * @param {boolean} [options.refreshExpiredTiles=true] If `false`, the map won't attempt to re-request tiles once they expire per their HTTP `cacheControl`/`expires` headers.\n * @param {LngLatBoundsLike} [options.maxBounds] If set, the map will be constrained to the given bounds.\n * @param {boolean|Object} [options.scrollZoom=true] If `true`, the \"scroll to zoom\" interaction is enabled. An `Object` value is passed as options to {@link ScrollZoomHandler#enable}.\n * @param {boolean} [options.boxZoom=true] If `true`, the \"box zoom\" interaction is enabled (see {@link BoxZoomHandler}).\n * @param {boolean} [options.dragRotate=true] If `true`, the \"drag to rotate\" interaction is enabled (see {@link DragRotateHandler}).\n * @param {boolean|Object} [options.dragPan=true] If `true`, the \"drag to pan\" interaction is enabled. An `Object` value is passed as options to {@link DragPanHandler#enable}.\n * @param {boolean} [options.keyboard=true] If `true`, keyboard shortcuts are enabled (see {@link KeyboardHandler}).\n * @param {boolean} [options.doubleClickZoom=true] If `true`, the \"double click to zoom\" interaction is enabled (see {@link DoubleClickZoomHandler}).\n * @param {boolean|Object} [options.touchZoomRotate=true] If `true`, the \"pinch to rotate and zoom\" interaction is enabled. An `Object` value is passed as options to {@link TouchZoomRotateHandler#enable}.\n * @param {boolean|Object} [options.touchPitch=true] If `true`, the \"drag to pitch\" interaction is enabled. An `Object` value is passed as options to {@link TouchPitchHandler#enable}.\n * @param {boolean} [options.trackResize=true] If `true`, the map will automatically resize when the browser window resizes.\n * @param {LngLatLike} [options.center=[0, 0]] The inital geographical centerpoint of the map. If `center` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `[0, 0]` Note: Mapbox GL uses longitude, latitude coordinate order (as opposed to latitude, longitude) to match GeoJSON.\n * @param {number} [options.zoom=0] The initial zoom level of the map. If `zoom` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`.\n * @param {number} [options.bearing=0] The initial bearing (rotation) of the map, measured in degrees counter-clockwise from north. If `bearing` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`.\n * @param {number} [options.pitch=0] The initial pitch (tilt) of the map, measured in degrees away from the plane of the screen (0-60). If `pitch` is not specified in the constructor options, Mapbox GL JS will look for it in the map's style object. If it is not specified in the style, either, it will default to `0`.\n * @param {LngLatBoundsLike} [options.bounds] The initial bounds of the map. If `bounds` is specified, it overrides `center` and `zoom` constructor options.\n * @param {Object} [options.fitBoundsOptions] A {@link Map#fitBounds} options object to use _only_ when fitting the initial `bounds` provided above.\n * @param {boolean} [options.renderWorldCopies=true] If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:\n * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire\n * container, there will be blank space beyond 180 and -180 degrees longitude.\n * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the\n * map and the other on the left edge of the map) at every zoom level.\n * @param {number} [options.maxTileCacheSize=null] The maximum number of tiles stored in the tile cache for a given source. If omitted, the cache will be dynamically sized based on the current viewport.\n * @param {string} [options.localIdeographFontFamily='sans-serif'] Defines a CSS\n * font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' and 'Hangul Syllables' ranges.\n * In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold).\n * Set to `false`, to enable font settings from the map's style for these glyph ranges. Note that [Mapbox Studio](https://studio.mapbox.com/) sets this value to `false` by default.\n * The purpose of this option is to avoid bandwidth-intensive glyph server requests. (See [Use locally generated ideographs](https://www.mapbox.com/mapbox-gl-js/example/local-ideographs).)\n * @param {RequestTransformFunction} [options.transformRequest=null] A callback run before the Map makes a request for an external URL. The callback can be used to modify the url, set headers, or set the credentials property for cross-origin requests.\n * Expected to return an object with a `url` property and optionally `headers` and `credentials` properties.\n * @param {boolean} [options.collectResourceTiming=false] If `true`, Resource Timing API information will be collected for requests made by GeoJSON and Vector Tile web workers (this information is normally inaccessible from the main Javascript thread). Information will be returned in a `resourceTiming` property of relevant `data` events.\n * @param {number} [options.fadeDuration=300] Controls the duration of the fade-in/fade-out animation for label collisions, in milliseconds. This setting affects all symbol layers. This setting does not affect the duration of runtime styling transitions or raster tile cross-fading.\n * @param {boolean} [options.crossSourceCollisions=true] If `true`, symbols from multiple sources can collide with each other during collision detection. If `false`, collision detection is run separately for the symbols in each source.\n * @param {string} [options.accessToken=null] If specified, map will use this token instead of the one defined in mapboxgl.accessToken.\n * @param {Object} [options.locale=null] A patch to apply to the default localization table for UI strings, e.g. control tooltips. The `locale` object maps namespaced UI string IDs to translated strings in the target language; see `src/ui/default_locale.js` for an example with all supported string IDs. The object may specify all UI strings (thereby adding support for a new translation) or only a subset of strings (thereby patching the default translation table).\n * @example\n * var map = new mapboxgl.Map({\n * container: 'map',\n * center: [-122.420679, 37.772537],\n * zoom: 13,\n * style: style_object,\n * hash: true,\n * transformRequest: (url, resourceType)=> {\n * if(resourceType === 'Source' && url.startsWith('http://myHost')) {\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 * @see [Display a map](https://www.mapbox.com/mapbox-gl-js/examples/)\n */\nclass Map extends Camera {\n style: Style;\n painter: Painter;\n handlers: HandlerManager;\n\n _container: HTMLElement;\n _missingCSSCanary: HTMLElement;\n _canvasContainer: HTMLElement;\n _controlContainer: HTMLElement;\n _controlPositions: {[_: string]: HTMLElement};\n _interactive: ?boolean;\n _showTileBoundaries: ?boolean;\n _showCollisionBoxes: ?boolean;\n _showPadding: ?boolean;\n _showOverdrawInspector: boolean;\n _repaint: ?boolean;\n _vertices: ?boolean;\n _canvas: HTMLCanvasElement;\n _maxTileCacheSize: number;\n _frame: ?Cancelable;\n _styleDirty: ?boolean;\n _sourcesDirty: ?boolean;\n _placementDirty: ?boolean;\n _loaded: boolean;\n // accounts for placement finishing as well\n _fullyLoaded: boolean;\n _trackResize: boolean;\n _preserveDrawingBuffer: boolean;\n _failIfMajorPerformanceCaveat: boolean;\n _antialias: boolean;\n _refreshExpiredTiles: boolean;\n _hash: Hash;\n _delegatedListeners: any;\n _fadeDuration: number;\n _crossSourceCollisions: boolean;\n _crossFadingFactor: number;\n _collectResourceTiming: boolean;\n _renderTaskQueue: TaskQueue;\n _controls: Array;\n _mapId: number;\n _localIdeographFontFamily: string;\n _requestManager: RequestManager;\n _locale: Object;\n _removed: boolean;\n _clickTolerance: number;\n\n /**\n * The map's {@link ScrollZoomHandler}, which implements zooming in and out with a scroll wheel or trackpad.\n * Find more details and examples using `scrollZoom` in the {@link ScrollZoomHandler} section.\n */\n scrollZoom: ScrollZoomHandler;\n\n /**\n * The map's {@link BoxZoomHandler}, which implements zooming using a drag gesture with the Shift key pressed.\n * Find more details and examples using `boxZoom` in the {@link BoxZoomHandler} section.\n */\n boxZoom: BoxZoomHandler;\n\n /**\n * The map's {@link DragRotateHandler}, which implements rotating the map while dragging with the right\n * mouse button or with the Control key pressed. Find more details and examples using `dragRotate`\n * in the {@link DragRotateHandler} section.\n */\n dragRotate: DragRotateHandler;\n\n /**\n * The map's {@link DragPanHandler}, which implements dragging the map with a mouse or touch gesture.\n * Find more details and examples using `dragPan` in the {@link DragPanHandler} section.\n */\n dragPan: DragPanHandler;\n\n /**\n * The map's {@link KeyboardHandler}, which allows the user to zoom, rotate, and pan the map using keyboard\n * shortcuts. Find more details and examples using `keyboard` in the {@link KeyboardHandler} section.\n */\n keyboard: KeyboardHandler;\n\n /**\n * The map's {@link DoubleClickZoomHandler}, which allows the user to zoom by double clicking.\n * Find more details and examples using `doubleClickZoom` in the {@link DoubleClickZoomHandler} section.\n */\n doubleClickZoom: DoubleClickZoomHandler;\n\n /**\n * The map's {@link TouchZoomRotateHandler}, which allows the user to zoom or rotate the map with touch gestures.\n * Find more details and examples using `touchZoomRotate` in the {@link TouchZoomRotateHandler} section.\n */\n touchZoomRotate: TouchZoomRotateHandler;\n\n /**\n * The map's {@link TouchPitchHandler}, which allows the user to pitch the map with touch gestures.\n * Find more details and examples using `touchPitch` in the {@link TouchPitchHandler} section.\n */\n touchPitch: TouchPitchHandler;\n\n constructor(options: MapOptions) {\n PerformanceUtils.mark(PerformanceMarkers.create);\n\n options = extend({}, defaultOptions, options);\n\n if (options.minZoom != null && options.maxZoom != null && options.minZoom > options.maxZoom) {\n throw new Error(`maxZoom must be greater than or equal to minZoom`);\n }\n\n if (options.minPitch != null && options.maxPitch != null && options.minPitch > options.maxPitch) {\n throw new Error(`maxPitch must be greater than or equal to minPitch`);\n }\n\n if (options.minPitch != null && options.minPitch < defaultMinPitch) {\n throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`);\n }\n\n if (options.maxPitch != null && options.maxPitch > defaultMaxPitch) {\n throw new Error(`maxPitch must be less than or equal to ${defaultMaxPitch}`);\n }\n\n const transform = new Transform(options.minZoom, options.maxZoom, options.minPitch, options.maxPitch, options.renderWorldCopies);\n super(transform, options);\n\n this._interactive = options.interactive;\n this._maxTileCacheSize = options.maxTileCacheSize;\n this._failIfMajorPerformanceCaveat = options.failIfMajorPerformanceCaveat;\n this._preserveDrawingBuffer = options.preserveDrawingBuffer;\n this._antialias = options.antialias;\n this._trackResize = options.trackResize;\n this._bearingSnap = options.bearingSnap;\n this._refreshExpiredTiles = options.refreshExpiredTiles;\n this._fadeDuration = options.fadeDuration;\n this._crossSourceCollisions = options.crossSourceCollisions;\n this._crossFadingFactor = 1;\n this._collectResourceTiming = options.collectResourceTiming;\n this._renderTaskQueue = new TaskQueue();\n this._controls = [];\n this._mapId = uniqueId();\n this._locale = extend({}, defaultLocale, options.locale);\n this._clickTolerance = options.clickTolerance;\n\n this._requestManager = new RequestManager(options.transformRequest, options.accessToken);\n\n if (typeof options.container === 'string') {\n this._container = window.document.getElementById(options.container);\n if (!this._container) {\n throw new Error(`Container '${options.container}' not found.`);\n }\n } else if (options.container instanceof HTMLElement) {\n this._container = options.container;\n } else {\n throw new Error(`Invalid type: 'container' must be a String or HTMLElement.`);\n }\n\n if (options.maxBounds) {\n this.setMaxBounds(options.maxBounds);\n }\n\n bindAll([\n '_onWindowOnline',\n '_onWindowResize',\n '_onMapScroll',\n '_contextLost',\n '_contextRestored'\n ], this);\n\n this._setupContainer();\n this._setupPainter();\n if (this.painter === undefined) {\n throw new Error(`Failed to initialize WebGL.`);\n }\n\n this.on('move', () => this._update(false));\n this.on('moveend', () => this._update(false));\n this.on('zoom', () => this._update(true));\n\n if (typeof window !== 'undefined') {\n window.addEventListener('online', this._onWindowOnline, false);\n window.addEventListener('resize', this._onWindowResize, false);\n window.addEventListener('orientationchange', this._onWindowResize, false);\n }\n\n this.handlers = new HandlerManager(this, options);\n\n const hashName = (typeof options.hash === 'string' && options.hash) || undefined;\n this._hash = options.hash && (new Hash(hashName)).addTo(this);\n // don't set position from options if set through hash\n if (!this._hash || !this._hash._onHashChange()) {\n this.jumpTo({\n center: options.center,\n zoom: options.zoom,\n bearing: options.bearing,\n pitch: options.pitch\n });\n\n if (options.bounds) {\n this.resize();\n this.fitBounds(options.bounds, extend({}, options.fitBoundsOptions, {duration: 0}));\n }\n }\n\n this.resize();\n\n this._localIdeographFontFamily = options.localIdeographFontFamily;\n if (options.style) this.setStyle(options.style, {localIdeographFontFamily: options.localIdeographFontFamily});\n\n if (options.attributionControl)\n this.addControl(new AttributionControl({customAttribution: options.customAttribution}));\n\n this.addControl(new LogoControl(), options.logoPosition);\n\n this.on('style.load', () => {\n if (this.transform.unmodified) {\n this.jumpTo((this.style.stylesheet: any));\n }\n });\n this.on('data', (event: MapDataEvent) => {\n this._update(event.dataType === 'style');\n this.fire(new Event(`${event.dataType}data`, event));\n });\n this.on('dataloading', (event: MapDataEvent) => {\n this.fire(new Event(`${event.dataType}dataloading`, event));\n });\n }\n\n /*\n * Returns a unique number for this map instance which is used for the MapLoadEvent\n * to make sure we only fire one event per instantiated map object.\n * @private\n * @returns {number}\n */\n _getMapId() {\n return this._mapId;\n }\n\n /**\n * Adds an {@link IControl} to the map, calling `control.onAdd(this)`.\n *\n * @param {IControl} control The {@link IControl} to add.\n * @param {string} [position] position on the map to which the control will be added.\n * Valid values are `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`. Defaults to `'top-right'`.\n * @returns {Map} `this`\n * @example\n * // Add zoom and rotation controls to the map.\n * map.addControl(new mapboxgl.NavigationControl());\n * @see [Display map navigation controls](https://www.mapbox.com/mapbox-gl-js/example/navigation/)\n */\n addControl(control: IControl, position?: ControlPosition) {\n if (position === undefined) {\n if (control.getDefaultPosition) {\n position = control.getDefaultPosition();\n } else {\n position = 'top-right';\n }\n }\n if (!control || !control.onAdd) {\n return this.fire(new ErrorEvent(new Error(\n 'Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.')));\n }\n const controlElement = control.onAdd(this);\n this._controls.push(control);\n\n const positionContainer = this._controlPositions[position];\n if (position.indexOf('bottom') !== -1) {\n positionContainer.insertBefore(controlElement, positionContainer.firstChild);\n } else {\n positionContainer.appendChild(controlElement);\n }\n return this;\n }\n\n /**\n * Removes the control from the map.\n *\n * @param {IControl} control The {@link IControl} to remove.\n * @returns {Map} `this`\n * @example\n * // Define a new navigation control.\n * var navigation = new mapboxgl.NavigationControl();\n * // Add zoom and rotation controls to the map.\n * map.addControl(navigation);\n * // Remove zoom and rotation controls from the map.\n * map.removeControl(navigation);\n */\n removeControl(control: IControl) {\n if (!control || !control.onRemove) {\n return this.fire(new ErrorEvent(new Error(\n 'Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.')));\n }\n const ci = this._controls.indexOf(control);\n if (ci > -1) this._controls.splice(ci, 1);\n control.onRemove(this);\n return this;\n }\n\n /**\n * Checks if a control exists on the map.\n *\n * @param {IControl} control The {@link IControl} to check.\n * @returns {boolean} True if map contains control.\n * @example\n * // Define a new navigation control.\n * var navigation = new mapboxgl.NavigationControl();\n * // Add zoom and rotation controls to the map.\n * map.addControl(navigation);\n * // Check that the navigation control exists on the map.\n * map.hasControl(navigation);\n */\n hasControl(control: IControl) {\n return this._controls.indexOf(control) > -1;\n }\n\n /**\n * Resizes the map according to the dimensions of its\n * `container` element.\n *\n * Checks if the map container size changed and updates the map if it has changed.\n * This method must be called after the map's `container` is resized programmatically\n * or when the map is shown after being initially hidden with CSS.\n *\n * @param eventData Additional properties to be passed to `movestart`, `move`, `resize`, and `moveend`\n * events that get triggered as a result of resize. This can be useful for differentiating the\n * source of an event (for example, user-initiated or programmatically-triggered events).\n * @returns {Map} `this`\n * @example\n * // Resize the map when the map container is shown\n * // after being initially hidden with CSS.\n * var mapDiv = document.getElementById('map');\n * if (mapDiv.style.visibility === true) map.resize();\n */\n resize(eventData?: Object) {\n const [width, height] = this._containerDimensions();\n\n // do nothing if container remained the same size\n if (width === this.transform.width && height === this.transform.height) return this;\n\n this._resizeCanvas(width, height);\n this.transform.resize(width, height);\n this.painter.resize(width, height);\n\n const fireMoving = !this._moving;\n if (fireMoving) {\n this.fire(new Event('movestart', eventData))\n .fire(new Event('move', eventData));\n }\n\n this.fire(new Event('resize', eventData));\n\n if (fireMoving) this.fire(new Event('moveend', eventData));\n\n return this;\n }\n\n /**\n * Returns the map's geographical bounds. When the bearing or pitch is non-zero, the visible region is not\n * an axis-aligned rectangle, and the result is the smallest bounds that encompasses the visible region.\n * @returns {LngLatBounds} The geographical bounds of the map as {@link LngLatBounds}.\n * @example\n * var bounds = map.getBounds();\n */\n getBounds(): LngLatBounds {\n return this.transform.getBounds();\n }\n\n /**\n * Returns the maximum geographical bounds the map is constrained to, or `null` if none set.\n * @returns The map object.\n * @example\n * var maxBounds = map.getMaxBounds();\n */\n getMaxBounds(): LngLatBounds | null {\n return this.transform.getMaxBounds();\n }\n\n /**\n * Sets or clears the map's geographical bounds.\n *\n * Pan and zoom operations are constrained within these bounds.\n * If a pan or zoom is performed that would\n * display regions outside these bounds, the map will\n * instead display a position and zoom level\n * as close as possible to the operation's request while still\n * remaining within the bounds.\n *\n * @param {LngLatBoundsLike | null | undefined} bounds The maximum bounds to set. If `null` or `undefined` is provided, the function removes the map's maximum bounds.\n * @returns {Map} `this`\n * @example\n * // Define bounds that conform to the `LngLatBoundsLike` object.\n * var bounds = [\n * [-74.04728, 40.68392], // [west, south]\n * [-73.91058, 40.87764] // [east, north]\n * ];\n * // Set the map's max bounds.\n * map.setMaxBounds(bounds);\n */\n setMaxBounds(bounds: LngLatBoundsLike) {\n this.transform.setMaxBounds(LngLatBounds.convert(bounds));\n return this._update();\n }\n\n /**\n * Sets or clears the map's minimum zoom level.\n * If the map's current zoom level is lower than the new minimum,\n * the map will zoom to the new minimum.\n *\n * It is not always possible to zoom out and reach the set `minZoom`.\n * Other factors such as map height may restrict zooming. For example,\n * if the map is 512px tall it will not be possible to zoom below zoom 0\n * no matter what the `minZoom` is set to.\n *\n * @param {number | null | undefined} minZoom The minimum zoom level to set (-2 - 24).\n * If `null` or `undefined` is provided, the function removes the current minimum zoom (i.e. sets it to -2).\n * @returns {Map} `this`\n * @example\n * map.setMinZoom(12.25);\n */\n setMinZoom(minZoom?: ?number) {\n\n minZoom = minZoom === null || minZoom === undefined ? defaultMinZoom : minZoom;\n\n if (minZoom >= defaultMinZoom && minZoom <= this.transform.maxZoom) {\n this.transform.minZoom = minZoom;\n this._update();\n\n if (this.getZoom() < minZoom) this.setZoom(minZoom);\n\n return this;\n\n } else throw new Error(`minZoom must be between ${defaultMinZoom} and the current maxZoom, inclusive`);\n }\n\n /**\n * Returns the map's minimum allowable zoom level.\n *\n * @returns {number} minZoom\n * @example\n * var minZoom = map.getMinZoom();\n */\n getMinZoom() { return this.transform.minZoom; }\n\n /**\n * Sets or clears the map's maximum zoom level.\n * If the map's current zoom level is higher than the new maximum,\n * the map will zoom to the new maximum.\n *\n * @param {number | null | undefined} maxZoom The maximum zoom level to set.\n * If `null` or `undefined` is provided, the function removes the current maximum zoom (sets it to 22).\n * @returns {Map} `this`\n * @example\n * map.setMaxZoom(18.75);\n */\n setMaxZoom(maxZoom?: ?number) {\n\n maxZoom = maxZoom === null || maxZoom === undefined ? defaultMaxZoom : maxZoom;\n\n if (maxZoom >= this.transform.minZoom) {\n this.transform.maxZoom = maxZoom;\n this._update();\n\n if (this.getZoom() > maxZoom) this.setZoom(maxZoom);\n\n return this;\n\n } else throw new Error(`maxZoom must be greater than the current minZoom`);\n }\n\n /**\n * Returns the map's maximum allowable zoom level.\n *\n * @returns {number} maxZoom\n * @example\n * var maxZoom = map.getMaxZoom();\n */\n getMaxZoom() { return this.transform.maxZoom; }\n\n /**\n * Sets or clears the map's minimum pitch.\n * If the map's current pitch is lower than the new minimum,\n * the map will pitch to the new minimum.\n *\n * @param {number | null | undefined} minPitch The minimum pitch to set (0-60).\n * If `null` or `undefined` is provided, the function removes the current minimum pitch (i.e. sets it to 0).\n * @returns {Map} `this`\n */\n setMinPitch(minPitch?: ?number) {\n\n minPitch = minPitch === null || minPitch === undefined ? defaultMinPitch : minPitch;\n\n if (minPitch < defaultMinPitch) {\n throw new Error(`minPitch must be greater than or equal to ${defaultMinPitch}`);\n }\n\n if (minPitch >= defaultMinPitch && minPitch <= this.transform.maxPitch) {\n this.transform.minPitch = minPitch;\n this._update();\n\n if (this.getPitch() < minPitch) this.setPitch(minPitch);\n\n return this;\n\n } else throw new Error(`minPitch must be between ${defaultMinPitch} and the current maxPitch, inclusive`);\n }\n\n /**\n * Returns the map's minimum allowable pitch.\n *\n * @returns {number} minPitch\n */\n getMinPitch() { return this.transform.minPitch; }\n\n /**\n * Sets or clears the map's maximum pitch.\n * If the map's current pitch is higher than the new maximum,\n * the map will pitch to the new maximum.\n *\n * @param {number | null | undefined} maxPitch The maximum pitch to set.\n * If `null` or `undefined` is provided, the function removes the current maximum pitch (sets it to 60).\n * @returns {Map} `this`\n */\n setMaxPitch(maxPitch?: ?number) {\n\n maxPitch = maxPitch === null || maxPitch === undefined ? defaultMaxPitch : maxPitch;\n\n if (maxPitch > defaultMaxPitch) {\n throw new Error(`maxPitch must be less than or equal to ${defaultMaxPitch}`);\n }\n\n if (maxPitch >= this.transform.minPitch) {\n this.transform.maxPitch = maxPitch;\n this._update();\n\n if (this.getPitch() > maxPitch) this.setPitch(maxPitch);\n\n return this;\n\n } else throw new Error(`maxPitch must be greater than the current minPitch`);\n }\n\n /**\n * Returns the map's maximum allowable pitch.\n *\n * @returns {number} maxPitch\n */\n getMaxPitch() { return this.transform.maxPitch; }\n\n /**\n * Returns the state of `renderWorldCopies`. If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:\n * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire\n * container, there will be blank space beyond 180 and -180 degrees longitude.\n * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the\n * map and the other on the left edge of the map) at every zoom level.\n * @returns {boolean} renderWorldCopies\n * @example\n * var worldCopiesRendered = map.getRenderWorldCopies();\n * @see [Render world copies](https://docs.mapbox.com/mapbox-gl-js/example/render-world-copies/)\n */\n getRenderWorldCopies() { return this.transform.renderWorldCopies; }\n\n /**\n * Sets the state of `renderWorldCopies`.\n *\n * @param {boolean} renderWorldCopies If `true`, multiple copies of the world will be rendered side by side beyond -180 and 180 degrees longitude. If set to `false`:\n * - When the map is zoomed out far enough that a single representation of the world does not fill the map's entire\n * container, there will be blank space beyond 180 and -180 degrees longitude.\n * - Features that cross 180 and -180 degrees longitude will be cut in two (with one portion on the right edge of the\n * map and the other on the left edge of the map) at every zoom level.\n *\n * `undefined` is treated as `true`, `null` is treated as `false`.\n * @returns {Map} `this`\n * @example\n * map.setRenderWorldCopies(true);\n * @see [Render world copies](https://docs.mapbox.com/mapbox-gl-js/example/render-world-copies/)\n */\n setRenderWorldCopies(renderWorldCopies?: ?boolean) {\n this.transform.renderWorldCopies = renderWorldCopies;\n return this._update();\n }\n\n /**\n * Returns a {@link Point} representing pixel coordinates, relative to the map's `container`,\n * that correspond to the specified geographical location.\n *\n * @param {LngLatLike} lnglat The geographical location to project.\n * @returns {Point} The {@link Point} corresponding to `lnglat`, relative to the map's `container`.\n * @example\n * var coordinate = [-122.420679, 37.772537];\n * var point = map.project(coordinate);\n */\n project(lnglat: LngLatLike) {\n return this.transform.locationPoint(LngLat.convert(lnglat));\n }\n\n /**\n * Returns a {@link LngLat} representing geographical coordinates that correspond\n * to the specified pixel coordinates.\n *\n * @param {PointLike} point The pixel coordinates to unproject.\n * @returns {LngLat} The {@link LngLat} corresponding to `point`.\n * @example\n * map.on('click', function(e) {\n * // When the map is clicked, get the geographic coordinate.\n * var coordinate = map.unproject(e.point);\n * });\n */\n unproject(point: PointLike) {\n return this.transform.pointLocation(Point.convert(point));\n }\n\n /**\n * Returns true if the map is panning, zooming, rotating, or pitching due to a camera animation or user gesture.\n * @returns {boolean} True if the map is moving.\n * @example\n * var isMoving = map.isMoving();\n */\n isMoving(): boolean {\n return this._moving || this.handlers.isMoving();\n }\n\n /**\n * Returns true if the map is zooming due to a camera animation or user gesture.\n * @returns {boolean} True if the map is zooming.\n * @example\n * var isZooming = map.isZooming();\n */\n isZooming(): boolean {\n return this._zooming || this.handlers.isZooming();\n }\n\n /**\n * Returns true if the map is rotating due to a camera animation or user gesture.\n * @returns {boolean} True if the map is rotating.\n * @example\n * map.isRotating();\n */\n isRotating(): boolean {\n return this._rotating || this.handlers.isRotating();\n }\n\n _createDelegatedListener(type: MapEvent, layerId: any, listener: any) {\n if (type === 'mouseenter' || type === 'mouseover') {\n let mousein = false;\n const mousemove = (e) => {\n const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : [];\n if (!features.length) {\n mousein = false;\n } else if (!mousein) {\n mousein = true;\n listener.call(this, new MapMouseEvent(type, this, e.originalEvent, {features}));\n }\n };\n const mouseout = () => {\n mousein = false;\n };\n return {layer: layerId, listener, delegates: {mousemove, mouseout}};\n } else if (type === 'mouseleave' || type === 'mouseout') {\n let mousein = false;\n const mousemove = (e) => {\n const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : [];\n if (features.length) {\n mousein = true;\n } else if (mousein) {\n mousein = false;\n listener.call(this, new MapMouseEvent(type, this, e.originalEvent));\n }\n };\n const mouseout = (e) => {\n if (mousein) {\n mousein = false;\n listener.call(this, new MapMouseEvent(type, this, e.originalEvent));\n }\n };\n return {layer: layerId, listener, delegates: {mousemove, mouseout}};\n } else {\n const delegate = (e) => {\n const features = this.getLayer(layerId) ? this.queryRenderedFeatures(e.point, {layers: [layerId]}) : [];\n if (features.length) {\n // Here we need to mutate the original event, so that preventDefault works as expected.\n e.features = features;\n listener.call(this, e);\n delete e.features;\n }\n };\n return {layer: layerId, listener, delegates: {[type]: delegate}};\n }\n }\n\n /**\n * Adds a listener for events of a specified type, optionally limited to features in a specified style layer.\n *\n * @param {string} type The event type to listen for. Events compatible with the optional `layerId` parameter are triggered\n * when the cursor enters a visible portion of the specified layer from outside that layer or outside the map canvas.\n *\n * | Event | Compatible with `layerId` |\n * |-----------------------------------------------------------|---------------------------|\n * | [`mousedown`](#map.event:mousedown) | yes |\n * | [`mouseup`](#map.event:mouseup) | yes |\n * | [`mouseover`](#map.event:mouseover) | yes |\n * | [`mouseout`](#map.event:mouseout) | yes |\n * | [`mousemove`](#map.event:mousemove) | yes |\n * | [`mouseenter`](#map.event:mouseenter) | yes (required) |\n * | [`mouseleave`](#map.event:mouseleave) | yes (required) |\n * | [`click`](#map.event:click) | yes |\n * | [`dblclick`](#map.event:dblclick) | yes |\n * | [`contextmenu`](#map.event:contextmenu) | yes |\n * | [`touchstart`](#map.event:touchstart) | yes |\n * | [`touchend`](#map.event:touchend) | yes |\n * | [`touchcancel`](#map.event:touchcancel) | yes |\n * | [`wheel`](#map.event:wheel) | |\n * | [`resize`](#map.event:resize) | |\n * | [`remove`](#map.event:remove) | |\n * | [`touchmove`](#map.event:touchmove) | |\n * | [`movestart`](#map.event:movestart) | |\n * | [`move`](#map.event:move) | |\n * | [`moveend`](#map.event:moveend) | |\n * | [`dragstart`](#map.event:dragstart) | |\n * | [`drag`](#map.event:drag) | |\n * | [`dragend`](#map.event:dragend) | |\n * | [`zoomstart`](#map.event:zoomstart) | |\n * | [`zoom`](#map.event:zoom) | |\n * | [`zoomend`](#map.event:zoomend) | |\n * | [`rotatestart`](#map.event:rotatestart) | |\n * | [`rotate`](#map.event:rotate) | |\n * | [`rotateend`](#map.event:rotateend) | |\n * | [`pitchstart`](#map.event:pitchstart) | |\n * | [`pitch`](#map.event:pitch) | |\n * | [`pitchend`](#map.event:pitchend) | |\n * | [`boxzoomstart`](#map.event:boxzoomstart) | |\n * | [`boxzoomend`](#map.event:boxzoomend) | |\n * | [`boxzoomcancel`](#map.event:boxzoomcancel) | |\n * | [`webglcontextlost`](#map.event:webglcontextlost) | |\n * | [`webglcontextrestored`](#map.event:webglcontextrestored) | |\n * | [`load`](#map.event:load) | |\n * | [`render`](#map.event:render) | |\n * | [`idle`](#map.event:idle) | |\n * | [`error`](#map.event:error) | |\n * | [`data`](#map.event:data) | |\n * | [`styledata`](#map.event:styledata) | |\n * | [`sourcedata`](#map.event:sourcedata) | |\n * | [`dataloading`](#map.event:dataloading) | |\n * | [`styledataloading`](#map.event:styledataloading) | |\n * | [`sourcedataloading`](#map.event:sourcedataloading) | |\n * | [`styleimagemissing`](#map.event:styleimagemissing) | |\n *\n * @param {string} layerId (optional) The ID of a style layer. Event will only be triggered if its location\n * is within a visible feature in this layer. The event will have a `features` property containing\n * an array of the matching features. If `layerId` is not supplied, the event will not have a `features` property.\n * Please note that many event types are not compatible with the optional `layerId` parameter.\n * @param {Function} listener The function to be called when the event is fired.\n * @returns {Map} `this`\n * @example\n * // Set an event listener that will fire\n * // when the map has finished loading\n * map.on('load', function() {\n * // Once the map has finished loading,\n * // add a new layer\n * map.addLayer({\n * id: 'points-of-interest',\n * source: {\n * type: 'vector',\n * url: 'mapbox://mapbox.mapbox-streets-v8'\n * },\n * 'source-layer': 'poi_label',\n * type: 'circle',\n * paint: {\n * // Mapbox Style Specification paint properties\n * },\n * layout: {\n * // Mapbox Style Specification layout properties\n * }\n * });\n * });\n * @example\n * // Set an event listener that will fire\n * // when a feature on the countries layer of the map is clicked\n * map.on('click', 'countries', function(e) {\n * new mapboxgl.Popup()\n * .setLngLat(e.lngLat)\n * .setHTML(`Country name: ${e.features[0].properties.name}`)\n * .addTo(map);\n * });\n * @see [Display popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/)\n * @see [Center the map on a clicked symbol](https://docs.mapbox.com/mapbox-gl-js/example/center-on-symbol/)\n * @see [Create a hover effect](https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/)\n * @see [Create a draggable marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)\n */\n on(type: MapEvent, layerId: any, listener: any) {\n if (listener === undefined) {\n return super.on(type, layerId);\n }\n\n const delegatedListener = this._createDelegatedListener(type, layerId, listener);\n\n this._delegatedListeners = this._delegatedListeners || {};\n this._delegatedListeners[type] = this._delegatedListeners[type] || [];\n this._delegatedListeners[type].push(delegatedListener);\n\n for (const event in delegatedListener.delegates) {\n this.on((event: any), delegatedListener.delegates[event]);\n }\n\n return this;\n }\n\n /**\n * Adds a listener that will be called only once to a specified event type.\n *\n * @method\n * @name once\n * @memberof Map\n * @instance\n * @param {string} type The event type to add a listener 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 {Map} `this`\n */\n\n /**\n * Adds a listener that will be called only once to a specified event type occurring on features in a specified style layer.\n *\n * @param {string} type The event type to listen for; one of `'mousedown'`, `'mouseup'`, `'click'`, `'dblclick'`,\n * `'mousemove'`, `'mouseenter'`, `'mouseleave'`, `'mouseover'`, `'mouseout'`, `'contextmenu'`, `'touchstart'`,\n * `'touchend'`, or `'touchcancel'`. `mouseenter` and `mouseover` events are triggered when the cursor enters\n * a visible portion of the specified layer from outside that layer or outside the map canvas. `mouseleave`\n * and `mouseout` events are triggered when the cursor leaves a visible portion of the specified layer, or leaves\n * the map canvas.\n * @param {string} layerId The ID of a style layer. Only events whose location is within a visible\n * feature in this layer will trigger the listener. The event will have a `features` property containing\n * an array of the matching features.\n * @param {Function} listener The function to be called when the event is fired.\n * @returns {Map} `this`\n */\n\n once(type: MapEvent, layerId: any, listener: any) {\n\n if (listener === undefined) {\n return super.once(type, layerId);\n }\n\n const delegatedListener = this._createDelegatedListener(type, layerId, listener);\n\n for (const event in delegatedListener.delegates) {\n this.once((event: any), delegatedListener.delegates[event]);\n }\n\n return this;\n }\n\n /**\n * Removes an event listener previously added with `Map#on`.\n *\n * @method\n * @name off\n * @memberof Map\n * @instance\n * @param {string} type The event type previously used to install the listener.\n * @param {Function} listener The function previously installed as a listener.\n * @returns {Map} `this`\n */\n\n /**\n * Removes an event listener for layer-specific events previously added with `Map#on`.\n *\n * @param {string} type The event type previously used to install the listener.\n * @param {string} layerId The layer ID previously used to install the listener.\n * @param {Function} listener The function previously installed as a listener.\n * @returns {Map} `this`\n */\n off(type: MapEvent, layerId: any, listener: any) {\n if (listener === undefined) {\n return super.off(type, layerId);\n }\n\n const removeDelegatedListener = (delegatedListeners) => {\n const listeners = delegatedListeners[type];\n for (let i = 0; i < listeners.length; i++) {\n const delegatedListener = listeners[i];\n if (delegatedListener.layer === layerId && delegatedListener.listener === listener) {\n for (const event in delegatedListener.delegates) {\n this.off((event: any), delegatedListener.delegates[event]);\n }\n listeners.splice(i, 1);\n return this;\n }\n }\n };\n\n if (this._delegatedListeners && this._delegatedListeners[type]) {\n removeDelegatedListener(this._delegatedListeners);\n }\n\n return this;\n }\n\n /**\n * Returns an array of [GeoJSON](http://geojson.org/)\n * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2)\n * representing visible features that satisfy the query parameters.\n *\n * @param {PointLike|Array} [geometry] - The geometry of the query region:\n * either a single point or southwest and northeast points describing a bounding box.\n * Omitting this parameter (i.e. calling {@link Map#queryRenderedFeatures} with zero arguments,\n * or with only a `options` argument) is equivalent to passing a bounding box encompassing the entire\n * map viewport.\n * @param {Object} [options] Options object.\n * @param {Array} [options.layers] An array of [style layer IDs](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-id) for the query to inspect.\n * Only features within these layers will be returned. If this parameter is undefined, all layers will be checked.\n * @param {Array} [options.filter] A [filter](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter)\n * to limit query results.\n * @param {boolean} [options.validate=true] Whether to check if the [options.filter] conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.\n *\n * @returns {Array} An array of [GeoJSON](http://geojson.org/)\n * [feature objects](https://tools.ietf.org/html/rfc7946#section-3.2).\n *\n * The `properties` value of each returned feature object contains the properties of its source feature. For GeoJSON sources, only\n * string and numeric property values are supported (i.e. `null`, `Array`, and `Object` values are not supported).\n *\n * Each feature includes top-level `layer`, `source`, and `sourceLayer` properties. The `layer` property is an object\n * representing the style layer to which the feature belongs. Layout and paint properties in this object contain values\n * which are fully evaluated for the given zoom level and feature.\n *\n * Only features that are currently rendered are included. Some features will **not** be included, like:\n *\n * - Features from layers whose `visibility` property is `\"none\"`.\n * - Features from layers whose zoom range excludes the current zoom level.\n * - Symbol features that have been hidden due to text or icon collision.\n *\n * Features from all other layers are included, including features that may have no visible\n * contribution to the rendered result; for example, because the layer's opacity or color alpha component is set to\n * 0.\n *\n * The topmost rendered feature appears first in the returned array, and subsequent features are sorted by\n * descending z-order. Features that are rendered multiple times (due to wrapping across the antimeridian at low\n * zoom levels) are returned only once (though subject to the following caveat).\n *\n * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature\n * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple\n * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query.\n * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding\n * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile\n * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple\n * tiles due to tile buffering.\n *\n * @example\n * // Find all features at a point\n * var features = map.queryRenderedFeatures(\n * [20, 35],\n * { layers: ['my-layer-name'] }\n * );\n *\n * @example\n * // Find all features within a static bounding box\n * var features = map.queryRenderedFeatures(\n * [[10, 20], [30, 50]],\n * { layers: ['my-layer-name'] }\n * );\n *\n * @example\n * // Find all features within a bounding box around a point\n * var width = 10;\n * var height = 20;\n * var features = map.queryRenderedFeatures([\n * [point.x - width / 2, point.y - height / 2],\n * [point.x + width / 2, point.y + height / 2]\n * ], { layers: ['my-layer-name'] });\n *\n * @example\n * // Query all rendered features from a single layer\n * var features = map.queryRenderedFeatures({ layers: ['my-layer-name'] });\n * @see [Get features under the mouse pointer](https://www.mapbox.com/mapbox-gl-js/example/queryrenderedfeatures/)\n * @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)\n * @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)\n */\n queryRenderedFeatures(geometry?: PointLike | [PointLike, PointLike], options?: Object) {\n // The first parameter can be omitted entirely, making this effectively an overloaded method\n // with two signatures:\n //\n // queryRenderedFeatures(geometry: PointLike | [PointLike, PointLike], options?: Object)\n // queryRenderedFeatures(options?: Object)\n //\n // There no way to express that in a way that's compatible with both flow and documentation.js.\n // Related: https://github.com/facebook/flow/issues/1556\n\n if (!this.style) {\n return [];\n }\n\n if (options === undefined && geometry !== undefined && !(geometry instanceof Point) && !Array.isArray(geometry)) {\n options = (geometry: Object);\n geometry = undefined;\n }\n\n options = options || {};\n geometry = geometry || [[0, 0], [this.transform.width, this.transform.height]];\n\n let queryGeometry;\n if (geometry instanceof Point || typeof geometry[0] === 'number') {\n queryGeometry = [Point.convert(geometry)];\n } else {\n const tl = Point.convert(geometry[0]);\n const br = Point.convert(geometry[1]);\n queryGeometry = [tl, new Point(br.x, tl.y), br, new Point(tl.x, br.y), tl];\n }\n\n return this.style.queryRenderedFeatures(queryGeometry, options, this.transform);\n }\n\n /**\n * Returns an array of [GeoJSON](http://geojson.org/)\n * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2)\n * representing features within the specified vector tile or GeoJSON source that satisfy the query parameters.\n *\n * @param {string} sourceId The ID of the vector tile or GeoJSON source to query.\n * @param {Object} [parameters] Options object.\n * @param {string} [parameters.sourceLayer] The name of the [source layer](https://docs.mapbox.com/help/glossary/source-layer/)\n * to query. *For vector tile sources, this parameter is required.* For GeoJSON sources, it is ignored.\n * @param {Array} [parameters.filter] A [filter](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter)\n * to limit query results.\n * @param {boolean} [parameters.validate=true] Whether to check if the [parameters.filter] conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.\n *\n * @returns {Array} An array of [GeoJSON](http://geojson.org/)\n * [Feature objects](https://tools.ietf.org/html/rfc7946#section-3.2).\n *\n * In contrast to {@link Map#queryRenderedFeatures}, this function returns all features matching the query parameters,\n * whether or not they are rendered by the current style (i.e. visible). The domain of the query includes all currently-loaded\n * vector tiles and GeoJSON source tiles: this function does not check tiles outside the currently\n * visible viewport.\n *\n * Because features come from tiled vector data or GeoJSON data that is converted to tiles internally, feature\n * geometries may be split or duplicated across tile boundaries and, as a result, features may appear multiple\n * times in query results. For example, suppose there is a highway running through the bounding rectangle of a query.\n * The results of the query will be those parts of the highway that lie within the map tiles covering the bounding\n * rectangle, even if the highway extends into other tiles, and the portion of the highway within each map tile\n * will be returned as a separate feature. Similarly, a point feature near a tile boundary may appear in multiple\n * tiles due to tile buffering.\n *\n * @example\n * // Find all features in one source layer in a vector source\n * var features = map.querySourceFeatures('your-source-id', {\n * sourceLayer: 'your-source-layer'\n * });\n *\n * @see [Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/)\n */\n querySourceFeatures(sourceId: string, parameters: ?{sourceLayer: ?string, filter: ?Array, validate?: boolean}) {\n return this.style.querySourceFeatures(sourceId, parameters);\n }\n\n /**\n * Updates the map's Mapbox style object with a new value.\n *\n * If a style is already set when this is used and options.diff is set to true, the map renderer will attempt to compare the given style\n * against the map's current state and perform only the changes necessary to make the map style match the desired state. Changes in sprites\n * (images used for icons and patterns) and glyphs (fonts for label text) **cannot** be diffed. If the sprites or fonts used in the current\n * style and the given style are different in any way, the map renderer will force a full update, removing the current style and building\n * the given one from scratch.\n *\n *\n * @param style A JSON object conforming to the schema described in the\n * [Mapbox Style Specification](https://mapbox.com/mapbox-gl-style-spec/), or a URL to such JSON.\n * @param {Object} [options] Options object.\n * @param {boolean} [options.diff=true] If false, force a 'full' update, removing the current style\n * and building the given one instead of attempting a diff-based update.\n * @param {string} [options.localIdeographFontFamily='sans-serif'] Defines a CSS\n * font-family for locally overriding generation of glyphs in the 'CJK Unified Ideographs', 'Hiragana', 'Katakana' and 'Hangul Syllables' ranges.\n * In these ranges, font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold).\n * Set to `false`, to enable font settings from the map's style for these glyph ranges.\n * Forces a full update.\n * @returns {Map} `this`\n *\n * @example\n * map.setStyle(\"mapbox://styles/mapbox/streets-v11\");\n *\n * @see [Change a map's style](https://www.mapbox.com/mapbox-gl-js/example/setstyle/)\n */\n setStyle(style: StyleSpecification | string | null, options?: {diff?: boolean} & StyleOptions) {\n options = extend({}, {localIdeographFontFamily: this._localIdeographFontFamily}, options);\n\n if ((options.diff !== false && options.localIdeographFontFamily === this._localIdeographFontFamily) && this.style && style) {\n this._diffStyle(style, options);\n return this;\n } else {\n this._localIdeographFontFamily = options.localIdeographFontFamily;\n return this._updateStyle(style, options);\n }\n }\n\n _getUIString(key: string) {\n const str = this._locale[key];\n if (str == null) {\n throw new Error(`Missing UI string '${key}'`);\n }\n\n return str;\n }\n\n _updateStyle(style: StyleSpecification | string | null, options?: {diff?: boolean} & StyleOptions) {\n if (this.style) {\n this.style.setEventedParent(null);\n this.style._remove();\n }\n\n if (!style) {\n delete this.style;\n return this;\n } else {\n this.style = new Style(this, options || {});\n }\n\n this.style.setEventedParent(this, {style: this.style});\n\n if (typeof style === 'string') {\n this.style.loadURL(style);\n } else {\n this.style.loadJSON(style);\n }\n\n return this;\n }\n\n _lazyInitEmptyStyle() {\n if (!this.style) {\n this.style = new Style(this, {});\n this.style.setEventedParent(this, {style: this.style});\n this.style.loadEmpty();\n }\n }\n\n _diffStyle(style: StyleSpecification | string, options?: {diff?: boolean} & StyleOptions) {\n if (typeof style === 'string') {\n const url = this._requestManager.normalizeStyleURL(style);\n const request = this._requestManager.transformRequest(url, ResourceType.Style);\n getJSON(request, (error: ?Error, json: ?Object) => {\n if (error) {\n this.fire(new ErrorEvent(error));\n } else if (json) {\n this._updateDiff(json, options);\n }\n });\n } else if (typeof style === 'object') {\n this._updateDiff(style, options);\n }\n }\n\n _updateDiff(style: StyleSpecification, options?: {diff?: boolean} & StyleOptions) {\n try {\n if (this.style.setState(style)) {\n this._update(true);\n }\n } catch (e) {\n warnOnce(\n `Unable to perform style diff: ${e.message || e.error || e}. Rebuilding the style from scratch.`\n );\n this._updateStyle(style, options);\n }\n }\n\n /**\n * Returns the map's Mapbox [style](https://docs.mapbox.com/help/glossary/style/) object, a JSON object which can be used to recreate the map's style.\n *\n * @returns {Object} The map's style JSON object.\n *\n * @example\n * var styleJson = map.getStyle();\n *\n */\n getStyle() {\n if (this.style) {\n return this.style.serialize();\n }\n }\n\n /**\n * Returns a Boolean indicating whether the map's style is fully loaded.\n *\n * @returns {boolean} A Boolean indicating whether the style is fully loaded.\n *\n * @example\n * var styleLoadStatus = map.isStyleLoaded();\n */\n isStyleLoaded() {\n if (!this.style) return warnOnce('There is no style added to the map.');\n return this.style.loaded();\n }\n\n /**\n * Adds a source to the map's style.\n *\n * @param {string} id The ID of the source to add. Must not conflict with existing sources.\n * @param {Object} source The source object, conforming to the\n * Mapbox Style Specification's [source definition](https://www.mapbox.com/mapbox-gl-style-spec/#sources) or\n * {@link CanvasSourceOptions}.\n * @fires source.add\n * @returns {Map} `this`\n * @example\n * map.addSource('my-data', {\n * type: 'vector',\n * url: 'mapbox://myusername.tilesetid'\n * });\n * @example\n * map.addSource('my-data', {\n * \"type\": \"geojson\",\n * \"data\": {\n * \"type\": \"Feature\",\n * \"geometry\": {\n * \"type\": \"Point\",\n * \"coordinates\": [-77.0323, 38.9131]\n * },\n * \"properties\": {\n * \"title\": \"Mapbox DC\",\n * \"marker-symbol\": \"monument\"\n * }\n * }\n * });\n * @see Vector source: [Show and hide layers](https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/)\n * @see GeoJSON source: [Add live realtime data](https://docs.mapbox.com/mapbox-gl-js/example/live-geojson/)\n * @see Raster DEM source: [Add hillshading](https://docs.mapbox.com/mapbox-gl-js/example/hillshade/)\n */\n addSource(id: string, source: SourceSpecification) {\n this._lazyInitEmptyStyle();\n this.style.addSource(id, source);\n return this._update(true);\n }\n\n /**\n * Returns a Boolean indicating whether the source is loaded. Returns `true` if the source with\n * the given ID in the map's style has no outstanding network requests, otherwise `false`.\n *\n * @param {string} id The ID of the source to be checked.\n * @returns {boolean} A Boolean indicating whether the source is loaded.\n * @example\n * var sourceLoaded = map.isSourceLoaded('bathymetry-data');\n */\n isSourceLoaded(id: string) {\n const source = this.style && this.style.sourceCaches[id];\n if (source === undefined) {\n this.fire(new ErrorEvent(new Error(`There is no source with ID '${id}'`)));\n return;\n }\n return source.loaded();\n }\n\n /**\n * Returns a Boolean indicating whether all tiles in the viewport from all sources on\n * the style are loaded.\n *\n * @returns {boolean} A Boolean indicating whether all tiles are loaded.\n * @example\n * var tilesLoaded = map.areTilesLoaded();\n */\n\n areTilesLoaded() {\n const sources = this.style && this.style.sourceCaches;\n for (const id in sources) {\n const source = sources[id];\n const tiles = source._tiles;\n for (const t in tiles) {\n const tile = tiles[t];\n if (!(tile.state === 'loaded' || tile.state === 'errored')) return false;\n }\n }\n return true;\n }\n\n /**\n * Adds a [custom source type](#Custom Sources), making it available for use with\n * {@link Map#addSource}.\n * @private\n * @param {string} name The name of the source type; source definition objects use this name in the `{type: ...}` field.\n * @param {Function} SourceType A {@link Source} constructor.\n * @param {Function} callback Called when the source type is ready or with an error argument if there is an error.\n */\n addSourceType(name: string, SourceType: any, callback: Function) {\n this._lazyInitEmptyStyle();\n return this.style.addSourceType(name, SourceType, callback);\n }\n\n /**\n * Removes a source from the map's style.\n *\n * @param {string} id The ID of the source to remove.\n * @returns {Map} `this`\n * @example\n * map.removeSource('bathymetry-data');\n */\n removeSource(id: string) {\n this.style.removeSource(id);\n return this._update(true);\n }\n\n /**\n * Returns the source with the specified ID in the map's style.\n *\n * This method is often used to update a source using the instance members for the relevant\n * source type as defined in [Sources](#sources).\n * For example, setting the `data` for a GeoJSON source or updating the `url` and `coordinates`\n * of an image source.\n *\n * @param {string} id The ID of the source to get.\n * @returns {?Object} The style source with the specified ID or `undefined` if the ID\n * corresponds to no existing sources.\n * The shape of the object varies by source type.\n * A list of options for each source type is available on the Mapbox Style Specification's\n * [Sources](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/) page.\n * @example\n * var sourceObject = map.getSource('points');\n * @see [Create a draggable point](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-point/)\n * @see [Animate a point](https://docs.mapbox.com/mapbox-gl-js/example/animate-point-along-line/)\n * @see [Add live realtime data](https://docs.mapbox.com/mapbox-gl-js/example/live-geojson/)\n */\n getSource(id: string) {\n return this.style.getSource(id);\n }\n\n // eslint-disable-next-line jsdoc/require-returns\n /**\n * Add an image to the style. This image can be displayed on the map like any other icon in the style's\n * [sprite](https://docs.mapbox.com/help/glossary/sprite/) using the image's ID with\n * [`icon-image`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-icon-image),\n * [`background-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-background-background-pattern),\n * [`fill-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-fill-fill-pattern),\n * or [`line-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-line-line-pattern).\n * A {@link Map.event:error} event will be fired if there is not enough space in the sprite to add this image.\n *\n * @param id The ID of the image.\n * @param image The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data`\n * properties with the same format as `ImageData`.\n * @param options Options object.\n * @param options.pixelRatio The ratio of pixels in the image to physical pixels on the screen\n * @param options.sdf Whether the image should be interpreted as an SDF image\n * @param options.content `[x1, y1, x2, y2]` If `icon-text-fit` is used in a layer with this image, this option defines the part of the image that can be covered by the content in `text-field`.\n * @param options.stretchX `[[x1, x2], ...]` If `icon-text-fit` is used in a layer with this image, this option defines the part(s) of the image that can be stretched horizontally.\n * @param options.stretchY `[[y1, y2], ...]` If `icon-text-fit` is used in a layer with this image, this option defines the part(s) of the image that can be stretched vertically.\n *\n * @example\n * // If the style's sprite does not already contain an image with ID 'cat',\n * // add the image 'cat-icon.png' to the style's sprite with the ID 'cat'.\n * map.loadImage('https://upload.wikimedia.org/wikipedia/commons/thumb/6/60/Cat_silhouette.svg/400px-Cat_silhouette.svg.png', function(error, image) {\n * if (error) throw error;\n * if (!map.hasImage('cat')) map.addImage('cat', image);\n * });\n *\n *\n * // Add a stretchable image that can be used with `icon-text-fit`\n * // In this example, the image is 600px wide by 400px high.\n * map.loadImage('https://upload.wikimedia.org/wikipedia/commons/8/89/Black_and_White_Boxed_%28bordered%29.png', function(error, image) {\n * if (error) throw error;\n * if (!map.hasImage('border-image')) {\n * map.addImage('border-image', image, {\n * content: [16, 16, 300, 384], // place text over left half of image, avoiding the 16px border\n * stretchX: [[16, 584]], // stretch everything horizontally except the 16px border\n * stretchY: [[16, 384]], // stretch everything vertically except the 16px border\n * });\n * }\n * });\n *\n *\n * @see Use `HTMLImageElement`: [Add an icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image/)\n * @see Use `ImageData`: [Add a generated icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image-generated/)\n */\n addImage(id: string,\n image: HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: Uint8Array | Uint8ClampedArray} | StyleImageInterface,\n {pixelRatio = 1, sdf = false, stretchX, stretchY, content}: $Shape = {}) {\n this._lazyInitEmptyStyle();\n const version = 0;\n\n if (image instanceof HTMLImageElement || (ImageBitmap && image instanceof ImageBitmap)) {\n const {width, height, data} = browser.getImageData(image);\n this.style.addImage(id, {data: new RGBAImage({width, height}, data), pixelRatio, stretchX, stretchY, content, sdf, version});\n } else if (image.width === undefined || image.height === undefined) {\n return this.fire(new ErrorEvent(new Error(\n 'Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' +\n 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`')));\n } else {\n const {width, height, data} = image;\n const userImage = ((image: any): StyleImageInterface);\n\n this.style.addImage(id, {\n data: new RGBAImage({width, height}, new Uint8Array(data)),\n pixelRatio,\n stretchX,\n stretchY,\n content,\n sdf,\n version,\n userImage\n });\n\n if (userImage.onAdd) {\n userImage.onAdd(this, id);\n }\n }\n }\n\n // eslint-disable-next-line jsdoc/require-returns\n /**\n * Update an existing image in a style. This image can be displayed on the map like any other icon in the style's\n * [sprite](https://docs.mapbox.com/help/glossary/sprite/) using the image's ID with\n * [`icon-image`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layout-symbol-icon-image),\n * [`background-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-background-background-pattern),\n * [`fill-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-fill-fill-pattern),\n * or [`line-pattern`](https://docs.mapbox.com/mapbox-gl-js/style-spec/#paint-line-line-pattern).\n *\n * @param id The ID of the image.\n * @param image The image as an `HTMLImageElement`, `ImageData`, `ImageBitmap` or object with `width`, `height`, and `data`\n * properties with the same format as `ImageData`.\n *\n * @example\n * // If an image with the ID 'cat' already exists in the style's sprite,\n * // replace that image with a new image, 'other-cat-icon.png'.\n * if (map.hasImage('cat')) map.updateImage('cat', './other-cat-icon.png');\n */\n updateImage(id: string,\n image: HTMLImageElement | ImageBitmap | ImageData | {width: number, height: number, data: Uint8Array | Uint8ClampedArray} | StyleImageInterface) {\n\n const existingImage = this.style.getImage(id);\n if (!existingImage) {\n return this.fire(new ErrorEvent(new Error(\n 'The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.')));\n }\n const imageData = (image instanceof HTMLImageElement || (ImageBitmap && image instanceof ImageBitmap)) ? browser.getImageData(image) : image;\n const {width, height, data} = imageData;\n\n if (width === undefined || height === undefined) {\n return this.fire(new ErrorEvent(new Error(\n 'Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, ' +\n 'or object with `width`, `height`, and `data` properties with the same format as `ImageData`')));\n }\n\n if (width !== existingImage.data.width || height !== existingImage.data.height) {\n return this.fire(new ErrorEvent(new Error(\n 'The width and height of the updated image must be that same as the previous version of the image')));\n }\n\n const copy = !(image instanceof HTMLImageElement || (ImageBitmap && image instanceof ImageBitmap));\n existingImage.data.replace(data, copy);\n\n this.style.updateImage(id, existingImage);\n }\n\n /**\n * Check whether or not an image with a specific ID exists in the style. This checks both images\n * in the style's original [sprite](https://docs.mapbox.com/help/glossary/sprite/) and any images\n * that have been added at runtime using {@link Map#addImage}.\n *\n * @param id The ID of the image.\n *\n * @returns {boolean} A Boolean indicating whether the image exists.\n * @example\n * // Check if an image with the ID 'cat' exists in\n * // the style's sprite.\n * var catIconExists = map.hasImage('cat');\n */\n hasImage(id: string): boolean {\n if (!id) {\n this.fire(new ErrorEvent(new Error('Missing required image id')));\n return false;\n }\n\n return !!this.style.getImage(id);\n }\n\n /**\n * Remove an image from a style. This can be an image from the style's original\n * [sprite](https://docs.mapbox.com/help/glossary/sprite/) or any images\n * that have been added at runtime using {@link Map#addImage}.\n *\n * @param id The ID of the image.\n *\n * @example\n * // If an image with the ID 'cat' exists in\n * // the style's sprite, remove it.\n * if (map.hasImage('cat')) map.removeImage('cat');\n */\n removeImage(id: string) {\n this.style.removeImage(id);\n }\n\n /**\n * Load an image from an external URL to be used with {@link Map#addImage}. External\n * domains must support [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS).\n *\n * @param {string} url The URL of the image file. Image file must be in png, webp, or jpg format.\n * @param {Function} callback Expecting `callback(error, data)`. Called when the image has loaded or with an error argument if there is an error.\n *\n * @example\n * // Load an image from an external URL.\n * map.loadImage('http://placekitten.com/50/50', function(error, image) {\n * if (error) throw error;\n * // Add the loaded image to the style's sprite with the ID 'kitten'.\n * map.addImage('kitten', image);\n * });\n *\n * @see [Add an icon to the map](https://www.mapbox.com/mapbox-gl-js/example/add-image/)\n */\n loadImage(url: string, callback: Function) {\n getImage(this._requestManager.transformRequest(url, ResourceType.Image), callback);\n }\n\n /**\n * Returns an Array of strings containing the IDs of all images currently available in the map.\n * This includes both images from the style's original [sprite](https://docs.mapbox.com/help/glossary/sprite/)\n * and any images that have been added at runtime using {@link Map#addImage}.\n *\n * @returns {Array} An Array of strings containing the names of all sprites/images currently available in the map.\n *\n * @example\n * var allImages = map.listImages();\n *\n */\n listImages() {\n return this.style.listImages();\n }\n\n /**\n * Adds a [Mapbox style layer](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers)\n * to the map's style.\n *\n * A layer defines how data from a specified source will be styled. Read more about layer types\n * and available paint and layout properties in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers).\n *\n * @param {Object | CustomLayerInterface} layer The layer to add, conforming to either the Mapbox Style Specification's [layer definition](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layers) or, less commonly, the {@link CustomLayerInterface} specification.\n * The Mapbox Style Specification's layer definition is appropriate for most layers.\n *\n * @param {string} layer.id A unique idenfier that you define.\n * @param {string} layer.type The type of layer (for example `fill` or `symbol`).\n * A list of layer types is available in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#type).\n *\n * (This can also be `custom`. For more information, see {@link CustomLayerInterface}.)\n * @param {string | Object} [layer.source] The data source for the layer.\n * Reference a source that has _already been defined_ using the source's unique id.\n * Reference a _new source_ using a source object (as defined in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/)) directly.\n * This is **required** for all `layer.type` options _except_ for `custom`.\n * @param {string} [layer.sourceLayer] (optional) The name of the [source layer](https://docs.mapbox.com/help/glossary/source-layer/) within the specified `layer.source` to use for this style layer.\n * This is only applicable for vector tile sources and is **required** when `layer.source` is of the type `vector`.\n * @param {array} [layer.filter] (optional) An expression specifying conditions on source features.\n * Only features that match the filter are displayed.\n * The Mapbox Style Specification includes more information on the limitations of the [`filter`](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter) parameter\n * and a complete list of available [expressions](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/).\n * If no filter is provided, all features in the source (or source layer for vector tilesets) will be displayed.\n * @param {Object} [layer.paint] (optional) Paint properties for the layer.\n * Available paint properties vary by `layer.type`.\n * A full list of paint properties for each layer type is available in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/).\n * If no paint properties are specified, default values will be used.\n * @param {Object} [layer.layout] (optional) Layout properties for the layer.\n * Available layout properties vary by `layer.type`.\n * A full list of layout properties for each layer type is available in the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/).\n * If no layout properties are specified, default values will be used.\n * @param {number} [layer.maxzoom] (optional) The maximum zoom level for the layer.\n * At zoom levels equal to or greater than the maxzoom, the layer will be hidden.\n * The value can be any number between `0` and `24` (inclusive).\n * If no maxzoom is provided, the layer will be visible at all zoom levels for which there are tiles available.\n * @param {number} [layer.minzoom] (optional) The minimum zoom level for the layer.\n * At zoom levels less than the minzoom, the layer will be hidden.\n * The value can be any number between `0` and `24` (inclusive).\n * If no minzoom is provided, the layer will be visible at all zoom levels for which there are tiles available.\n * @param {Object} [layer.metadata] (optional) Arbitrary properties useful to track with the layer, but do not influence rendering.\n * @param {string} [layer.renderingMode] This is only applicable for layers with the type `custom`.\n * See {@link CustomLayerInterface} for more information.\n * @param {string} [beforeId] The ID of an existing layer to insert the new layer before,\n * resulting in the new layer appearing visually beneath the existing layer.\n * If this argument is not specified, the layer will be appended to the end of the layers array\n * and appear visually above all other layers.\n *\n * @returns {Map} `this`\n *\n * @example\n * // Add a circle layer with a vector source\n * map.addLayer({\n * id: 'points-of-interest',\n * source: {\n * type: 'vector',\n * url: 'mapbox://mapbox.mapbox-streets-v8'\n * },\n * 'source-layer': 'poi_label',\n * type: 'circle',\n * paint: {\n * // Mapbox Style Specification paint properties\n * },\n * layout: {\n * // Mapbox Style Specification layout properties\n * }\n * });\n *\n * @example\n * // Define a source before using it to create a new layer\n * map.addSource('state-data', {\n * type: 'geojson',\n * data: 'path/to/data.geojson'\n * });\n *\n * map.addLayer({\n * id: 'states',\n * // References the GeoJSON source defined above\n * // and does not require a `source-layer`\n * source: 'state-data',\n * type: 'symbol',\n * layout: {\n * // Set the label content to the\n * // feature's `name` property\n * text-field: ['get', 'name']\n * }\n * });\n *\n * @example\n * // Add a new symbol layer before an existing layer\n * map.addLayer({\n * id: 'states',\n * // References a source that's already been defined\n * source: 'state-data',\n * type: 'symbol',\n * layout: {\n * // Set the label content to the\n * // feature's `name` property\n * text-field: ['get', 'name']\n * }\n * // Add the layer before the existing `cities` layer\n * }, 'cities');\n *\n * @see [Create and style clusters](https://docs.mapbox.com/mapbox-gl-js/example/cluster/)\n * @see [Add a vector tile source](https://docs.mapbox.com/mapbox-gl-js/example/vector-source/)\n * @see [Add a WMS source](https://docs.mapbox.com/mapbox-gl-js/example/wms/)\n */\n addLayer(layer: LayerSpecification | CustomLayerInterface, beforeId?: string) {\n this._lazyInitEmptyStyle();\n this.style.addLayer(layer, beforeId);\n return this._update(true);\n }\n\n /**\n * Moves a layer to a different z-position.\n *\n * @param {string} id The ID of the layer to move.\n * @param {string} [beforeId] The ID of an existing layer to insert the new layer before. When viewing the map, the `id` layer will appear beneath the `beforeId` layer. If `beforeId` is omitted, the layer will be appended to the end of the layers array and appear above all other layers on the map.\n * @returns {Map} `this`\n *\n * @example\n * // Move a layer with ID 'polygon' before the layer with ID 'country-label'. The `polygon` layer will appear beneath the `country-label` layer on the map.\n * map.moveLayer('polygon', 'country-label');\n */\n moveLayer(id: string, beforeId?: string) {\n this.style.moveLayer(id, beforeId);\n return this._update(true);\n }\n\n // eslint-disable-next-line jsdoc/require-returns\n /**\n * Removes the layer with the given ID from the map's style.\n *\n * If no such layer exists, an `error` event is fired.\n *\n * @param {string} id id of the layer to remove\n * @fires error\n *\n * @example\n * // If a layer with ID 'state-data' exists, remove it.\n * if (map.getLayer('state-data')) map.removeLayer('state-data');\n */\n removeLayer(id: string) {\n this.style.removeLayer(id);\n return this._update(true);\n }\n\n /**\n * Returns the layer with the specified ID in the map's style.\n *\n * @param {string} id The ID of the layer to get.\n * @returns {?Object} The layer with the specified ID, or `undefined`\n * if the ID corresponds to no existing layers.\n *\n * @example\n * var stateDataLayer = map.getLayer('state-data');\n *\n * @see [Filter symbols by toggling a list](https://www.mapbox.com/mapbox-gl-js/example/filter-markers/)\n * @see [Filter symbols by text input](https://www.mapbox.com/mapbox-gl-js/example/filter-markers-by-input/)\n */\n getLayer(id: string) {\n return this.style.getLayer(id);\n }\n\n /**\n * Sets the zoom extent for the specified style layer. The zoom extent includes the\n * [minimum zoom level](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-minzoom)\n * and [maximum zoom level](https://docs.mapbox.com/mapbox-gl-js/style-spec/#layer-maxzoom))\n * at which the layer will be rendered.\n *\n * Note: For style layers using vector sources, style layers cannot be rendered at zoom levels lower than the\n * minimum zoom level of the _source layer_ because the data does not exist at those zoom levels. If the minimum\n * zoom level of the source layer is higher than the minimum zoom level defined in the style layer, the style\n * layer will not be rendered at all zoom levels in the zoom range.\n *\n * @param {string} layerId The ID of the layer to which the zoom extent will be applied.\n * @param {number} minzoom The minimum zoom to set (0-24).\n * @param {number} maxzoom The maximum zoom to set (0-24).\n * @returns {Map} `this`\n *\n * @example\n * map.setLayerZoomRange('my-layer', 2, 5);\n *\n */\n setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number) {\n this.style.setLayerZoomRange(layerId, minzoom, maxzoom);\n return this._update(true);\n }\n\n /**\n * Sets the filter for the specified style layer.\n *\n * Filters control which features a style layer renders from its source.\n * Any feature for which the filter expression evaluates to `true` will be\n * rendered on the map. Those that are false will be hidden.\n *\n * Use `setFilter` to show a subset of your source data.\n *\n * To clear the filter, pass `null` or `undefined` as the second parameter.\n *\n * @param {string} layerId The ID of the layer to which the filter will be applied.\n * @param {Array | null | undefined} filter The filter, conforming to the Mapbox Style Specification's\n * [filter definition](https://docs.mapbox.com/mapbox-gl-js/style-spec/layers/#filter). If `null` or `undefined` is provided, the function removes any existing filter from the layer.\n * @param {Object} [options] Options object.\n * @param {boolean} [options.validate=true] Whether to check if the filter conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.\n * @returns {Map} `this`\n *\n * @example\n * // display only features with the 'name' property 'USA'\n * map.setFilter('my-layer', ['==', ['get', 'name'], 'USA']);\n * @example\n * // display only features with five or more 'available-spots'\n * map.setFilter('bike-docks', ['>=', ['get', 'available-spots'], 5]);\n * @example\n * // remove the filter for the 'bike-docks' style layer\n * map.setFilter('bike-docks', null);\n *\n * @see [Filter features within map view](https://www.mapbox.com/mapbox-gl-js/example/filter-features-within-map-view/)\n * @see [Highlight features containing similar data](https://www.mapbox.com/mapbox-gl-js/example/query-similar-features/)\n * @see [Create a timeline animation](https://www.mapbox.com/mapbox-gl-js/example/timeline-animation/)\n * @see Tutorial: [Show changes over time](https://docs.mapbox.com/help/tutorials/show-changes-over-time/)\n */\n setFilter(layerId: string, filter: ?FilterSpecification, options: StyleSetterOptions = {}) {\n this.style.setFilter(layerId, filter, options);\n return this._update(true);\n }\n\n /**\n * Returns the filter applied to the specified style layer.\n *\n * @param {string} layerId The ID of the style layer whose filter to get.\n * @returns {Array} The layer's filter.\n */\n getFilter(layerId: string) {\n return this.style.getFilter(layerId);\n }\n\n /**\n * Sets the value of a paint property in the specified style layer.\n *\n * @param {string} layerId The ID of the layer to set the paint property in.\n * @param {string} name The name of the paint property to set.\n * @param {*} value The value of the paint property to set.\n * Must be of a type appropriate for the property, as defined in the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/).\n * @param {Object} [options] Options object.\n * @param {boolean} [options.validate=true] Whether to check if `value` conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.\n * @returns {Map} `this`\n * @example\n * map.setPaintProperty('my-layer', 'fill-color', '#faafee');\n * @see [Change a layer's color with buttons](https://www.mapbox.com/mapbox-gl-js/example/color-switcher/)\n * @see [Adjust a layer's opacity](https://www.mapbox.com/mapbox-gl-js/example/adjust-layer-opacity/)\n * @see [Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/)\n */\n setPaintProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) {\n this.style.setPaintProperty(layerId, name, value, options);\n return this._update(true);\n }\n\n /**\n * Returns the value of a paint property in the specified style layer.\n *\n * @param {string} layerId The ID of the layer to get the paint property from.\n * @param {string} name The name of a paint property to get.\n * @returns {*} The value of the specified paint property.\n */\n getPaintProperty(layerId: string, name: string) {\n return this.style.getPaintProperty(layerId, name);\n }\n\n /**\n * Sets the value of a layout property in the specified style layer.\n *\n * @param {string} layerId The ID of the layer to set the layout property in.\n * @param {string} name The name of the layout property to set.\n * @param {*} value The value of the layout property. Must be of a type appropriate for the property, as defined in the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/).\n * @param {Object} [options] Options object.\n * @param {boolean} [options.validate=true] Whether to check if `value` conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.\n * @returns {Map} `this`\n * @example\n * map.setLayoutProperty('my-layer', 'visibility', 'none');\n * @see [Show and hide layers](https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/)\n */\n setLayoutProperty(layerId: string, name: string, value: any, options: StyleSetterOptions = {}) {\n this.style.setLayoutProperty(layerId, name, value, options);\n return this._update(true);\n }\n\n /**\n * Returns the value of a layout property in the specified style layer.\n *\n * @param {string} layerId The ID of the layer to get the layout property from.\n * @param {string} name The name of the layout property to get.\n * @returns {*} The value of the specified layout property.\n */\n getLayoutProperty(layerId: string, name: string) {\n return this.style.getLayoutProperty(layerId, name);\n }\n\n /**\n * Sets the any combination of light values.\n *\n * @param light Light properties to set. Must conform to the [Mapbox Style Specification](https://www.mapbox.com/mapbox-gl-style-spec/#light).\n * @param {Object} [options] Options object.\n * @param {boolean} [options.validate=true] Whether to check if the filter conforms to the Mapbox GL Style Specification. Disabling validation is a performance optimization that should only be used if you have previously validated the values you will be passing to this function.\n * @returns {Map} `this`\n * @example\n * var layerVisibility = map.getLayoutProperty('my-layer', 'visibility');\n * @see [Show and hide layers](https://docs.mapbox.com/mapbox-gl-js/example/toggle-layers/)\n */\n setLight(light: LightSpecification, options: StyleSetterOptions = {}) {\n this._lazyInitEmptyStyle();\n this.style.setLight(light, options);\n return this._update(true);\n }\n\n /**\n * Returns the value of the light object.\n *\n * @returns {Object} light Light properties of the style.\n */\n getLight() {\n return this.style.getLight();\n }\n\n // eslint-disable-next-line jsdoc/require-returns\n /**\n * Sets the `state` of a feature.\n * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime.\n * When using this method, the `state` object is merged with any existing key-value pairs in the feature's state.\n * Features are identified by their `feature.id` attribute, which can be any number or string.\n *\n * This method can only be used with sources that have a `feature.id` attribute. The `feature.id` attribute can be defined in three ways:\n * - For vector or GeoJSON sources, including an `id` attribute in the original data file.\n * - For vector or GeoJSON sources, using the [`promoteId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#vector-promoteId) option at the time the source is defined.\n * - For GeoJSON sources, using the [`generateId`](https://docs.mapbox.com/mapbox-gl-js/style-spec/sources/#geojson-generateId) option to auto-assign an `id` based on the feature's index in the source data. If you change feature data using `map.getSource('some id').setData(..)`, you may need to re-apply state taking into account updated `id` values.\n *\n * _Note: You can use the [`feature-state` expression](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#feature-state) to access the values in a feature's state object for the purposes of styling._\n *\n * @param {Object} feature Feature identifier. Feature objects returned from\n * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers.\n * @param {string | number} feature.id Unique id of the feature.\n * @param {string} feature.source The id of the vector or GeoJSON source for the feature.\n * @param {string} [feature.sourceLayer] (optional) *For vector tile sources, `sourceLayer` is required.*\n * @param {Object} state A set of key-value pairs. The values should be valid JSON types.\n *\n * @example\n * // When the mouse moves over the `my-layer` layer, update\n * // the feature state for the feature under the mouse\n * map.on('mousemove', 'my-layer', function(e) {\n * if (e.features.length > 0) {\n * map.setFeatureState({\n * source: 'my-source',\n * sourceLayer: 'my-source-layer',\n * id: e.features[0].id,\n * }, {\n * hover: true\n * });\n * }\n * });\n *\n * @see [Create a hover effect](https://docs.mapbox.com/mapbox-gl-js/example/hover-styles/)\n * @see Tutorial: [Create interactive hover effects with Mapbox GL JS](https://docs.mapbox.com/help/tutorials/create-interactive-hover-effects-with-mapbox-gl-js/)\n */\n setFeatureState(feature: { source: string; sourceLayer?: string; id: string | number; }, state: Object) {\n this.style.setFeatureState(feature, state);\n return this._update();\n }\n\n // eslint-disable-next-line jsdoc/require-returns\n /**\n * Removes the `state` of a feature, setting it back to the default behavior.\n * If only a `target.source` is specified, it will remove the state for all features from that source.\n * If `target.id` is also specified, it will remove all keys for that feature's state.\n * If `key` is also specified, it removes only that key from that feature's state.\n * Features are identified by their `feature.id` attribute, which can be any number or string.\n *\n * @param {Object} target Identifier of where to remove state. It can be a source, a feature, or a specific key of feature.\n * Feature objects returned from {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers.\n * @param {string | number} target.id (optional) Unique id of the feature. Optional if key is not specified.\n * @param {string} target.source The id of the vector or GeoJSON source for the feature.\n * @param {string} [target.sourceLayer] (optional) *For vector tile sources, `sourceLayer` is required.*\n * @param {string} key (optional) The key in the feature state to reset.\n *\n * @example\n * // Reset the entire state object for all features\n * // in the `my-source` source\n * map.removeFeatureState({\n * source: 'my-source'\n * });\n *\n * @example\n * // When the mouse leaves the `my-layer` layer,\n * // reset the entire state object for the\n * // feature under the mouse\n * map.on('mouseleave', 'my-layer', function(e) {\n * map.removeFeatureState({\n * source: 'my-source',\n * sourceLayer: 'my-source-layer',\n * id: e.features[0].id\n * });\n * });\n *\n * @example\n * // When the mouse leaves the `my-layer` layer,\n * // reset only the `hover` key-value pair in the\n * // state for the feature under the mouse\n * map.on('mouseleave', 'my-layer', function(e) {\n * map.removeFeatureState({\n * source: 'my-source',\n * sourceLayer: 'my-source-layer',\n * id: e.features[0].id\n * }, 'hover');\n * });\n *\n */\n removeFeatureState(target: { source: string; sourceLayer?: string; id?: string | number; }, key?: string) {\n this.style.removeFeatureState(target, key);\n return this._update();\n }\n\n /**\n * Gets the `state` of a feature.\n * A feature's `state` is a set of user-defined key-value pairs that are assigned to a feature at runtime.\n * Features are identified by their `feature.id` attribute, which can be any number or string.\n *\n * _Note: To access the values in a feature's state object for the purposes of styling the feature, use the [`feature-state` expression](https://docs.mapbox.com/mapbox-gl-js/style-spec/expressions/#feature-state)._\n *\n * @param {Object} feature Feature identifier. Feature objects returned from\n * {@link Map#queryRenderedFeatures} or event handlers can be used as feature identifiers.\n * @param {string | number} feature.id Unique id of the feature.\n * @param {string} feature.source The id of the vector or GeoJSON source for the feature.\n * @param {string} [feature.sourceLayer] (optional) *For vector tile sources, `sourceLayer` is required.*\n *\n * @returns {Object} The state of the feature: a set of key-value pairs that was assigned to the feature at runtime.\n *\n * @example\n * // When the mouse moves over the `my-layer` layer,\n * // get the feature state for the feature under the mouse\n * map.on('mousemove', 'my-layer', function(e) {\n * if (e.features.length > 0) {\n * map.getFeatureState({\n * source: 'my-source',\n * sourceLayer: 'my-source-layer',\n * id: e.features[0].id\n * });\n * }\n * });\n *\n */\n getFeatureState(feature: { source: string; sourceLayer?: string; id: string | number; }): any {\n return this.style.getFeatureState(feature);\n }\n\n /**\n * Returns the map's containing HTML element.\n *\n * @returns {HTMLElement} The map's container.\n */\n getContainer() {\n return this._container;\n }\n\n /**\n * Returns the HTML element containing the map's `` element.\n *\n * If you want to add non-GL overlays to the map, you should append them to this element.\n *\n * This is the element to which event bindings for map interactivity (such as panning and zooming) are\n * attached. It will receive bubbled events from child elements such as the ``, but not from\n * map controls.\n *\n * @returns {HTMLElement} The container of the map's ``.\n * @see [Create a draggable point](https://www.mapbox.com/mapbox-gl-js/example/drag-a-point/)\n * @see [Highlight features within a bounding box](https://www.mapbox.com/mapbox-gl-js/example/using-box-queryrenderedfeatures/)\n */\n getCanvasContainer() {\n return this._canvasContainer;\n }\n\n /**\n * Returns the map's `` element.\n *\n * @returns {HTMLCanvasElement} The map's `` element.\n * @see [Measure distances](https://www.mapbox.com/mapbox-gl-js/example/measure/)\n * @see [Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)\n * @see [Center the map on a clicked symbol](https://www.mapbox.com/mapbox-gl-js/example/center-on-symbol/)\n */\n getCanvas() {\n return this._canvas;\n }\n\n _containerDimensions() {\n let width = 0;\n let height = 0;\n\n if (this._container) {\n width = this._container.clientWidth || 400;\n height = this._container.clientHeight || 300;\n }\n\n return [width, height];\n }\n\n _detectMissingCSS(): void {\n const computedColor = window.getComputedStyle(this._missingCSSCanary).getPropertyValue('background-color');\n if (computedColor !== 'rgb(250, 128, 114)') {\n warnOnce('This page appears to be missing CSS declarations for ' +\n 'Mapbox GL JS, which may cause the map to display incorrectly. ' +\n 'Please ensure your page includes mapbox-gl.css, as described ' +\n 'in https://www.mapbox.com/mapbox-gl-js/api/.');\n }\n }\n\n _setupContainer() {\n const container = this._container;\n container.classList.add('mapboxgl-map');\n\n const missingCSSCanary = this._missingCSSCanary = DOM.create('div', 'mapboxgl-canary', container);\n missingCSSCanary.style.visibility = 'hidden';\n this._detectMissingCSS();\n\n const canvasContainer = this._canvasContainer = DOM.create('div', 'mapboxgl-canvas-container', container);\n if (this._interactive) {\n canvasContainer.classList.add('mapboxgl-interactive');\n }\n\n this._canvas = DOM.create('canvas', 'mapboxgl-canvas', canvasContainer);\n this._canvas.addEventListener('webglcontextlost', this._contextLost, false);\n this._canvas.addEventListener('webglcontextrestored', this._contextRestored, false);\n this._canvas.setAttribute('tabindex', '0');\n this._canvas.setAttribute('aria-label', 'Map');\n this._canvas.setAttribute('role', 'region');\n\n const dimensions = this._containerDimensions();\n this._resizeCanvas(dimensions[0], dimensions[1]);\n\n const controlContainer = this._controlContainer = DOM.create('div', 'mapboxgl-control-container', container);\n const positions = this._controlPositions = {};\n ['top-left', 'top-right', 'bottom-left', 'bottom-right'].forEach((positionName) => {\n positions[positionName] = DOM.create('div', `mapboxgl-ctrl-${positionName}`, controlContainer);\n });\n\n this._container.addEventListener('scroll', this._onMapScroll, false);\n }\n\n _resizeCanvas(width: number, height: number) {\n const pixelRatio = browser.devicePixelRatio || 1;\n\n // Request the required canvas size taking the pixelratio into account.\n this._canvas.width = pixelRatio * width;\n this._canvas.height = pixelRatio * height;\n\n // Maintain the same canvas size, potentially downscaling it for HiDPI displays\n this._canvas.style.width = `${width}px`;\n this._canvas.style.height = `${height}px`;\n }\n\n _setupPainter() {\n const attributes = extend({}, isSupported.webGLContextAttributes, {\n failIfMajorPerformanceCaveat: this._failIfMajorPerformanceCaveat,\n preserveDrawingBuffer: this._preserveDrawingBuffer,\n antialias: this._antialias || false\n });\n\n const gl = this._canvas.getContext('webgl', attributes) ||\n this._canvas.getContext('experimental-webgl', attributes);\n\n if (!gl) {\n this.fire(new ErrorEvent(new Error('Failed to initialize WebGL')));\n return;\n }\n\n this.painter = new Painter(gl, this.transform);\n\n webpSupported.testSupport(gl);\n }\n\n _contextLost(event: *) {\n event.preventDefault();\n if (this._frame) {\n this._frame.cancel();\n this._frame = null;\n }\n this.fire(new Event('webglcontextlost', {originalEvent: event}));\n }\n\n _contextRestored(event: *) {\n this._setupPainter();\n this.resize();\n this._update();\n this.fire(new Event('webglcontextrestored', {originalEvent: event}));\n }\n\n _onMapScroll(event: *) {\n if (event.target !== this._container) return;\n\n // Revert any scroll which would move the canvas outside of the view\n this._container.scrollTop = 0;\n this._container.scrollLeft = 0;\n return false;\n }\n\n /**\n * Returns a Boolean indicating whether the map is fully loaded.\n *\n * Returns `false` if the style is not yet fully loaded,\n * or if there has been a change to the sources or style that\n * has not yet fully loaded.\n *\n * @returns {boolean} A Boolean indicating whether the map is fully loaded.\n */\n loaded() {\n return !this._styleDirty && !this._sourcesDirty && !!this.style && this.style.loaded();\n }\n\n /**\n * Update this map's style and sources, and re-render the map.\n *\n * @param {boolean} updateStyle mark the map's style for reprocessing as\n * well as its sources\n * @returns {Map} this\n * @private\n */\n _update(updateStyle?: boolean) {\n if (!this.style) return this;\n\n this._styleDirty = this._styleDirty || updateStyle;\n this._sourcesDirty = true;\n this.triggerRepaint();\n\n return this;\n }\n\n /**\n * Request that the given callback be executed during the next render\n * frame. Schedule a render frame if one is not already scheduled.\n * @returns An id that can be used to cancel the callback\n * @private\n */\n _requestRenderFrame(callback: () => void): TaskID {\n this._update();\n return this._renderTaskQueue.add(callback);\n }\n\n _cancelRenderFrame(id: TaskID) {\n this._renderTaskQueue.remove(id);\n }\n\n /**\n * Call when a (re-)render of the map is required:\n * - The style has changed (`setPaintProperty()`, etc.)\n * - Source data has changed (e.g. tiles have finished loading)\n * - The map has is moving (or just finished moving)\n * - A transition is in progress\n *\n * @param {number} paintStartTimeStamp The time when the animation frame began executing.\n *\n * @returns {Map} this\n * @private\n */\n _render(paintStartTimeStamp: number) {\n let gpuTimer, frameStartTime = 0;\n const extTimerQuery = this.painter.context.extTimerQuery;\n if (this.listens('gpu-timing-frame')) {\n gpuTimer = extTimerQuery.createQueryEXT();\n extTimerQuery.beginQueryEXT(extTimerQuery.TIME_ELAPSED_EXT, gpuTimer);\n frameStartTime = browser.now();\n }\n\n // A custom layer may have used the context asynchronously. Mark the state as dirty.\n this.painter.context.setDirty();\n this.painter.setBaseState();\n\n this._renderTaskQueue.run(paintStartTimeStamp);\n // A task queue callback may have fired a user event which may have removed the map\n if (this._removed) return;\n\n let crossFading = false;\n\n // If the style has changed, the map is being zoomed, or a transition or fade is in progress:\n // - Apply style changes (in a batch)\n // - Recalculate paint properties.\n if (this.style && this._styleDirty) {\n this._styleDirty = false;\n\n const zoom = this.transform.zoom;\n const now = browser.now();\n this.style.zoomHistory.update(zoom, now);\n\n const parameters = new EvaluationParameters(zoom, {\n now,\n fadeDuration: this._fadeDuration,\n zoomHistory: this.style.zoomHistory,\n transition: this.style.getTransition()\n });\n\n const factor = parameters.crossFadingFactor();\n if (factor !== 1 || factor !== this._crossFadingFactor) {\n crossFading = true;\n this._crossFadingFactor = factor;\n }\n\n this.style.update(parameters);\n }\n\n // If we are in _render for any reason other than an in-progress paint\n // transition, update source caches to check for and load any tiles we\n // need for the current transform\n if (this.style && this._sourcesDirty) {\n this._sourcesDirty = false;\n this.style._updateSources(this.transform);\n }\n\n this._placementDirty = this.style && this.style._updatePlacement(this.painter.transform, this.showCollisionBoxes, this._fadeDuration, this._crossSourceCollisions);\n\n // Actually draw\n this.painter.render(this.style, {\n showTileBoundaries: this.showTileBoundaries,\n showOverdrawInspector: this._showOverdrawInspector,\n rotating: this.isRotating(),\n zooming: this.isZooming(),\n moving: this.isMoving(),\n fadeDuration: this._fadeDuration,\n showPadding: this.showPadding,\n gpuTiming: !!this.listens('gpu-timing-layer'),\n });\n\n this.fire(new Event('render'));\n\n if (this.loaded() && !this._loaded) {\n this._loaded = true;\n PerformanceUtils.mark(PerformanceMarkers.load);\n this.fire(new Event('load'));\n }\n\n if (this.style && (this.style.hasTransitions() || crossFading)) {\n this._styleDirty = true;\n }\n\n if (this.style && !this._placementDirty) {\n // Since no fade operations are in progress, we can release\n // all tiles held for fading. If we didn't do this, the tiles\n // would just sit in the SourceCaches until the next render\n this.style._releaseSymbolFadeTiles();\n }\n\n if (this.listens('gpu-timing-frame')) {\n const renderCPUTime = browser.now() - frameStartTime;\n extTimerQuery.endQueryEXT(extTimerQuery.TIME_ELAPSED_EXT, gpuTimer);\n setTimeout(() => {\n const renderGPUTime = extTimerQuery.getQueryObjectEXT(gpuTimer, extTimerQuery.QUERY_RESULT_EXT) / (1000 * 1000);\n extTimerQuery.deleteQueryEXT(gpuTimer);\n this.fire(new Event('gpu-timing-frame', {\n cpuTime: renderCPUTime,\n gpuTime: renderGPUTime\n }));\n }, 50); // Wait 50ms to give time for all GPU calls to finish before querying\n }\n\n if (this.listens('gpu-timing-layer')) {\n // Resetting the Painter's per-layer timing queries here allows us to isolate\n // the queries to individual frames.\n const frameLayerQueries = this.painter.collectGpuTimers();\n\n setTimeout(() => {\n const renderedLayerTimes = this.painter.queryGpuTimers(frameLayerQueries);\n\n this.fire(new Event('gpu-timing-layer', {\n layerTimes: renderedLayerTimes\n }));\n }, 50); // Wait 50ms to give time for all GPU calls to finish before querying\n }\n\n // Schedule another render frame if it's needed.\n //\n // Even though `_styleDirty` and `_sourcesDirty` are reset in this\n // method, synchronous events fired during Style#update or\n // Style#_updateSources could have caused them to be set again.\n const somethingDirty = this._sourcesDirty || this._styleDirty || this._placementDirty;\n if (somethingDirty || this._repaint) {\n this.triggerRepaint();\n } else if (!this.isMoving() && this.loaded()) {\n this.fire(new Event('idle'));\n }\n\n if (this._loaded && !this._fullyLoaded && !somethingDirty) {\n this._fullyLoaded = true;\n PerformanceUtils.mark(PerformanceMarkers.fullLoad);\n }\n\n return this;\n }\n\n /**\n * Clean up and release all internal resources associated with this map.\n *\n * This includes DOM elements, event bindings, web workers, and WebGL resources.\n *\n * Use this method when you are done using the map and wish to ensure that it no\n * longer consumes browser resources. Afterwards, you must not call any other\n * methods on the map.\n */\n remove() {\n if (this._hash) this._hash.remove();\n\n for (const control of this._controls) control.onRemove(this);\n this._controls = [];\n\n if (this._frame) {\n this._frame.cancel();\n this._frame = null;\n }\n this._renderTaskQueue.clear();\n this.painter.destroy();\n this.handlers.destroy();\n delete this.handlers;\n this.setStyle(null);\n if (typeof window !== 'undefined') {\n window.removeEventListener('resize', this._onWindowResize, false);\n window.removeEventListener('orientationchange', this._onWindowResize, false);\n window.removeEventListener('online', this._onWindowOnline, false);\n }\n\n const extension = this.painter.context.gl.getExtension('WEBGL_lose_context');\n if (extension) extension.loseContext();\n removeNode(this._canvasContainer);\n removeNode(this._controlContainer);\n removeNode(this._missingCSSCanary);\n this._container.classList.remove('mapboxgl-map');\n\n PerformanceUtils.clearMetrics();\n\n this._removed = true;\n this.fire(new Event('remove'));\n }\n\n /**\n * Trigger the rendering of a single frame. Use this method with custom layers to\n * repaint the map when the layer changes. Calling this multiple times before the\n * next frame is rendered will still result in only a single frame being rendered.\n * @example\n * map.triggerRepaint();\n * @see [Add a 3D model](https://docs.mapbox.com/mapbox-gl-js/example/add-3d-model/)\n * @see [Add an animated icon to the map](https://docs.mapbox.com/mapbox-gl-js/example/add-image-animated/)\n */\n triggerRepaint() {\n if (this.style && !this._frame) {\n this._frame = browser.frame((paintStartTimeStamp: number) => {\n PerformanceUtils.frame(paintStartTimeStamp);\n this._frame = null;\n this._render(paintStartTimeStamp);\n });\n }\n }\n\n _onWindowOnline() {\n this._update();\n }\n\n _onWindowResize(event: Event) {\n if (this._trackResize) {\n this.resize({originalEvent: event})._update();\n }\n }\n\n /**\n * Gets and sets a Boolean indicating whether the map will render an outline\n * around each tile and the tile ID. These tile boundaries are useful for\n * debugging.\n *\n * The uncompressed file size of the first vector source is drawn in the top left\n * corner of each tile, next to the tile ID.\n *\n * @name showTileBoundaries\n * @type {boolean}\n * @instance\n * @memberof Map\n * @example\n * map.showTileBoundaries = true;\n */\n get showTileBoundaries(): boolean { return !!this._showTileBoundaries; }\n set showTileBoundaries(value: boolean) {\n if (this._showTileBoundaries === value) return;\n this._showTileBoundaries = value;\n this._update();\n }\n\n /**\n * Gets and sets a Boolean indicating whether the map will visualize\n * the padding offsets.\n *\n * @name showPadding\n * @type {boolean}\n * @instance\n * @memberof Map\n */\n get showPadding(): boolean { return !!this._showPadding; }\n set showPadding(value: boolean) {\n if (this._showPadding === value) return;\n this._showPadding = value;\n this._update();\n }\n\n /**\n * Gets and sets a Boolean indicating whether the map will render boxes\n * around all symbols in the data source, revealing which symbols\n * were rendered or which were hidden due to collisions.\n * This information is useful for debugging.\n *\n * @name showCollisionBoxes\n * @type {boolean}\n * @instance\n * @memberof Map\n */\n get showCollisionBoxes(): boolean { return !!this._showCollisionBoxes; }\n set showCollisionBoxes(value: boolean) {\n if (this._showCollisionBoxes === value) return;\n this._showCollisionBoxes = value;\n if (value) {\n // When we turn collision boxes on we have to generate them for existing tiles\n // When we turn them off, there's no cost to leaving existing boxes in place\n this.style._generateCollisionBoxes();\n } else {\n // Otherwise, call an update to remove collision boxes\n this._update();\n }\n }\n\n /*\n * Gets and sets a Boolean indicating whether the map should color-code\n * each fragment to show how many times it has been shaded.\n * White fragments have been shaded 8 or more times.\n * Black fragments have been shaded 0 times.\n * This information is useful for debugging.\n *\n * @name showOverdraw\n * @type {boolean}\n * @instance\n * @memberof Map\n */\n get showOverdrawInspector(): boolean { return !!this._showOverdrawInspector; }\n set showOverdrawInspector(value: boolean) {\n if (this._showOverdrawInspector === value) return;\n this._showOverdrawInspector = value;\n this._update();\n }\n\n /**\n * Gets and sets a Boolean indicating whether the map will\n * continuously repaint. This information is useful for analyzing performance.\n *\n * @name repaint\n * @type {boolean}\n * @instance\n * @memberof Map\n */\n get repaint(): boolean { return !!this._repaint; }\n set repaint(value: boolean) {\n if (this._repaint !== value) {\n this._repaint = value;\n this.triggerRepaint();\n }\n }\n // show vertices\n get vertices(): boolean { return !!this._vertices; }\n set vertices(value: boolean) { this._vertices = value; this._update(); }\n\n // for cache browser tests\n _setCacheLimits(limit: number, checkThreshold: number) {\n setCacheLimits(limit, checkThreshold);\n }\n\n /**\n * The version of Mapbox GL JS in use as specified in package.json, CHANGELOG.md, and the GitHub release.\n *\n * @name version\n * @instance\n * @memberof Map\n * @var {string} version\n */\n\n get version(): string { return version; }\n}\n\nexport default Map;\n\nfunction removeNode(node) {\n if (node.parentNode) {\n node.parentNode.removeChild(node);\n }\n}\n\n/**\n * Interface for interactive controls added to the map. This is a\n * specification for implementers to model: it is not\n * an exported method or class.\n *\n * Controls must implement `onAdd` and `onRemove`, and must own an\n * element, which is often a `div` element. To use Mapbox GL JS's\n * default control styling, add the `mapboxgl-ctrl` class to your control's\n * node.\n *\n * @interface IControl\n * @example\n * // Control implemented as ES6 class\n * class HelloWorldControl {\n * onAdd(map) {\n * this._map = map;\n * this._container = document.createElement('div');\n * this._container.className = 'mapboxgl-ctrl';\n * this._container.textContent = 'Hello, world';\n * return this._container;\n * }\n *\n * onRemove() {\n * this._container.parentNode.removeChild(this._container);\n * this._map = undefined;\n * }\n * }\n *\n * // Control implemented as ES5 prototypical class\n * function HelloWorldControl() { }\n *\n * HelloWorldControl.prototype.onAdd = function(map) {\n * this._map = map;\n * this._container = document.createElement('div');\n * this._container.className = 'mapboxgl-ctrl';\n * this._container.textContent = 'Hello, world';\n * return this._container;\n * };\n *\n * HelloWorldControl.prototype.onRemove = function () {\n * this._container.parentNode.removeChild(this._container);\n * this._map = undefined;\n * };\n */\n\n/**\n * Register a control on the map and give it a chance to register event listeners\n * and resources. This method is called by {@link Map#addControl}\n * internally.\n *\n * @function\n * @memberof IControl\n * @instance\n * @name onAdd\n * @param {Map} map the Map this control will be added to\n * @returns {HTMLElement} The control's container element. This should\n * be created by the control and returned by onAdd without being attached\n * to the DOM: the map will insert the control's element into the DOM\n * as necessary.\n */\n\n/**\n * Unregister a control on the map and give it a chance to detach event listeners\n * and resources. This method is called by {@link Map#removeControl}\n * internally.\n *\n * @function\n * @memberof IControl\n * @instance\n * @name onRemove\n * @param {Map} map the Map this control will be removed from\n * @returns {undefined} there is no required return value for this method\n */\n\n/**\n * Optionally provide a default position for this control. If this method\n * is implemented and {@link Map#addControl} is called without the `position`\n * parameter, the value returned by getDefaultPosition will be used as the\n * control's position.\n *\n * @function\n * @memberof IControl\n * @instance\n * @name getDefaultPosition\n * @returns {string} a control position, one of the values valid in addControl.\n */\n\n/**\n * A [`Point` geometry](https://github.com/mapbox/point-geometry) object, which has\n * `x` and `y` properties representing screen coordinates in pixels.\n *\n * @typedef {Object} Point\n * @example\n * var point = new mapboxgl.Point(-77, 38);\n */\n\n/**\n * A {@link Point} or an array of two numbers representing `x` and `y` screen coordinates in pixels.\n *\n * @typedef {(Point | Array)} PointLike\n * @example\n * var p1 = new mapboxgl.Point(-77, 38); // a PointLike which is a Point\n * var p2 = [-77, 38]; // a PointLike which is an array of two numbers\n */\n","// @flow\n\nimport DOM from '../../util/dom';\nimport {extend, bindAll} from '../../util/util';\nimport {MouseRotateHandler, MousePitchHandler} from '../handler/mouse';\nimport window from '../../util/window';\n\nimport type Map from '../map';\n\ntype Options = {\n showCompass?: boolean,\n showZoom?: boolean,\n visualizePitch?: boolean\n};\n\nconst defaultOptions: Options = {\n showCompass: true,\n showZoom: true,\n visualizePitch: false\n};\n\n/**\n * A `NavigationControl` control contains zoom buttons and a compass.\n *\n * @implements {IControl}\n * @param {Object} [options]\n * @param {Boolean} [options.showCompass=true] If `true` the compass button is included.\n * @param {Boolean} [options.showZoom=true] If `true` the zoom-in and zoom-out buttons are included.\n * @param {Boolean} [options.visualizePitch=false] If `true` the pitch is visualized by rotating X-axis of compass.\n * @example\n * var nav = new mapboxgl.NavigationControl();\n * map.addControl(nav, 'top-left');\n * @see [Display map navigation controls](https://www.mapbox.com/mapbox-gl-js/example/navigation/)\n * @see [Add a third party vector tile source](https://www.mapbox.com/mapbox-gl-js/example/third-party/)\n */\nclass NavigationControl {\n _map: Map;\n options: Options;\n _container: HTMLElement;\n _zoomInButton: HTMLButtonElement;\n _zoomOutButton: HTMLButtonElement;\n _compass: HTMLButtonElement;\n _compassIcon: HTMLElement;\n _handler: MouseRotateWrapper;\n\n constructor(options: Options) {\n this.options = extend({}, defaultOptions, options);\n\n this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-group');\n this._container.addEventListener('contextmenu', (e) => e.preventDefault());\n\n if (this.options.showZoom) {\n bindAll([\n '_setButtonTitle',\n '_updateZoomButtons'\n ], this);\n this._zoomInButton = this._createButton('mapboxgl-ctrl-zoom-in', (e) => this._map.zoomIn({}, {originalEvent: e}));\n DOM.create('span', `mapboxgl-ctrl-icon`, this._zoomInButton).setAttribute('aria-hidden', true);\n this._zoomOutButton = this._createButton('mapboxgl-ctrl-zoom-out', (e) => this._map.zoomOut({}, {originalEvent: e}));\n DOM.create('span', `mapboxgl-ctrl-icon`, this._zoomOutButton).setAttribute('aria-hidden', true);\n }\n if (this.options.showCompass) {\n bindAll([\n '_rotateCompassArrow'\n ], this);\n this._compass = this._createButton('mapboxgl-ctrl-compass', (e) => {\n if (this.options.visualizePitch) {\n this._map.resetNorthPitch({}, {originalEvent: e});\n } else {\n this._map.resetNorth({}, {originalEvent: e});\n }\n });\n this._compassIcon = DOM.create('span', 'mapboxgl-ctrl-icon', this._compass);\n this._compassIcon.setAttribute('aria-hidden', true);\n }\n }\n\n _updateZoomButtons() {\n const zoom = this._map.getZoom();\n const isMax = zoom === this._map.getMaxZoom();\n const isMin = zoom === this._map.getMinZoom();\n this._zoomInButton.disabled = isMax;\n this._zoomOutButton.disabled = isMin;\n this._zoomInButton.setAttribute('aria-disabled', isMax.toString());\n this._zoomOutButton.setAttribute('aria-disabled', isMin.toString());\n }\n\n _rotateCompassArrow() {\n const rotate = this.options.visualizePitch ?\n `scale(${1 / Math.pow(Math.cos(this._map.transform.pitch * (Math.PI / 180)), 0.5)}) rotateX(${this._map.transform.pitch}deg) rotateZ(${this._map.transform.angle * (180 / Math.PI)}deg)` :\n `rotate(${this._map.transform.angle * (180 / Math.PI)}deg)`;\n\n this._compassIcon.style.transform = rotate;\n }\n\n onAdd(map: Map) {\n this._map = map;\n if (this.options.showZoom) {\n this._setButtonTitle(this._zoomInButton, 'ZoomIn');\n this._setButtonTitle(this._zoomOutButton, 'ZoomOut');\n this._map.on('zoom', this._updateZoomButtons);\n this._updateZoomButtons();\n }\n if (this.options.showCompass) {\n this._setButtonTitle(this._compass, 'ResetBearing');\n if (this.options.visualizePitch) {\n this._map.on('pitch', this._rotateCompassArrow);\n }\n this._map.on('rotate', this._rotateCompassArrow);\n this._rotateCompassArrow();\n this._handler = new MouseRotateWrapper(this._map, this._compass, this.options.visualizePitch);\n }\n return this._container;\n }\n\n onRemove() {\n DOM.remove(this._container);\n if (this.options.showZoom) {\n this._map.off('zoom', this._updateZoomButtons);\n }\n if (this.options.showCompass) {\n if (this.options.visualizePitch) {\n this._map.off('pitch', this._rotateCompassArrow);\n }\n this._map.off('rotate', this._rotateCompassArrow);\n this._handler.off();\n delete this._handler;\n }\n\n delete this._map;\n }\n\n _createButton(className: string, fn: () => mixed) {\n const a = DOM.create('button', className, this._container);\n a.type = 'button';\n a.addEventListener('click', fn);\n return a;\n }\n\n _setButtonTitle(button: HTMLButtonElement, title: string) {\n const str = this._map._getUIString(`NavigationControl.${title}`);\n button.title = str;\n button.setAttribute('aria-label', str);\n }\n}\n\nclass MouseRotateWrapper {\n\n map: Map;\n _clickTolerance: number;\n element: HTMLElement;\n mouseRotate: MouseRotateHandler;\n mousePitch: MousePitchHandler;\n _startPos: Point;\n _lastPos: Point;\n\n constructor(map: Map, element: HTMLElement, pitch?: boolean = false) {\n this._clickTolerance = 10;\n this.element = element;\n this.mouseRotate = new MouseRotateHandler({clickTolerance: map.dragRotate._mouseRotate._clickTolerance});\n this.map = map;\n if (pitch) this.mousePitch = new MousePitchHandler({clickTolerance: map.dragRotate._mousePitch._clickTolerance});\n\n bindAll(['mousedown', 'mousemove', 'mouseup', 'touchstart', 'touchmove', 'touchend', 'reset'], this);\n DOM.addEventListener(element, 'mousedown', this.mousedown);\n DOM.addEventListener(element, 'touchstart', this.touchstart, {passive: false});\n DOM.addEventListener(element, 'touchmove', this.touchmove);\n DOM.addEventListener(element, 'touchend', this.touchend);\n DOM.addEventListener(element, 'touchcancel', this.reset);\n }\n\n down(e: MouseEvent, point: Point) {\n this.mouseRotate.mousedown(e, point);\n if (this.mousePitch) this.mousePitch.mousedown(e, point);\n DOM.disableDrag();\n }\n\n move(e: MouseEvent, point: Point) {\n const map = this.map;\n const r = this.mouseRotate.mousemoveWindow(e, point);\n if (r && r.bearingDelta) map.setBearing(map.getBearing() + r.bearingDelta);\n if (this.mousePitch) {\n const p = this.mousePitch.mousemoveWindow(e, point);\n if (p && p.pitchDelta) map.setPitch(map.getPitch() + p.pitchDelta);\n }\n }\n\n off() {\n const element = this.element;\n DOM.removeEventListener(element, 'mousedown', this.mousedown);\n DOM.removeEventListener(element, 'touchstart', this.touchstart, {passive: false});\n DOM.removeEventListener(element, 'touchmove', this.touchmove);\n DOM.removeEventListener(element, 'touchend', this.touchend);\n DOM.removeEventListener(element, 'touchcancel', this.reset);\n this.offTemp();\n }\n\n offTemp() {\n DOM.enableDrag();\n DOM.removeEventListener(window, 'mousemove', this.mousemove);\n DOM.removeEventListener(window, 'mouseup', this.mouseup);\n }\n\n mousedown(e: MouseEvent) {\n this.down(extend({}, e, {ctrlKey: true, preventDefault: () => e.preventDefault()}), DOM.mousePos(this.element, e));\n DOM.addEventListener(window, 'mousemove', this.mousemove);\n DOM.addEventListener(window, 'mouseup', this.mouseup);\n }\n\n mousemove(e: MouseEvent) {\n this.move(e, DOM.mousePos(this.element, e));\n }\n\n mouseup(e: MouseEvent) {\n this.mouseRotate.mouseupWindow(e);\n if (this.mousePitch) this.mousePitch.mouseupWindow(e);\n this.offTemp();\n }\n\n touchstart(e: TouchEvent) {\n if (e.targetTouches.length !== 1) {\n this.reset();\n } else {\n this._startPos = this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0];\n this.down((({type: 'mousedown', button: 0, ctrlKey: true, preventDefault: () => e.preventDefault()}: any): MouseEvent), this._startPos);\n }\n }\n\n touchmove(e: TouchEvent) {\n if (e.targetTouches.length !== 1) {\n this.reset();\n } else {\n this._lastPos = DOM.touchPos(this.element, e.targetTouches)[0];\n this.move((({preventDefault: () => e.preventDefault()}: any): MouseEvent), this._lastPos);\n }\n }\n\n touchend(e: TouchEvent) {\n if (e.targetTouches.length === 0 &&\n this._startPos &&\n this._lastPos &&\n this._startPos.dist(this._lastPos) < this._clickTolerance) {\n this.element.click();\n }\n this.reset();\n }\n\n reset() {\n this.mouseRotate.reset();\n if (this.mousePitch) this.mousePitch.reset();\n delete this._startPos;\n delete this._lastPos;\n this.offTemp();\n }\n}\n\nexport default NavigationControl;\n","// @flow\n\nimport LngLat from '../geo/lng_lat';\n\nimport type Point from '@mapbox/point-geometry';\nimport type Transform from '../geo/transform';\n\n/**\n * Given a LngLat, prior projected position, and a transform, return a new LngLat shifted\n * n × 360° east or west for some n ≥ 0 such that:\n *\n * * the projected location of the result is on screen, if possible, and secondarily:\n * * the difference between the projected location of the result and the prior position\n * is minimized.\n *\n * The object is to preserve perceived object constancy for Popups and Markers as much as\n * possible; they should avoid shifting large distances across the screen, even when the\n * map center changes by ±360° due to automatic wrapping, and when about to go off screen,\n * should wrap just enough to avoid doing so.\n *\n * @private\n */\nexport default function(lngLat: LngLat, priorPos: ?Point, transform: Transform): LngLat {\n lngLat = new LngLat(lngLat.lng, lngLat.lat);\n\n // First, try shifting one world in either direction, and see if either is closer to the\n // prior position. This preserves object constancy when the map center is auto-wrapped\n // during animations.\n if (priorPos) {\n const left = new LngLat(lngLat.lng - 360, lngLat.lat);\n const right = new LngLat(lngLat.lng + 360, lngLat.lat);\n const delta = transform.locationPoint(lngLat).distSqr(priorPos);\n if (transform.locationPoint(left).distSqr(priorPos) < delta) {\n lngLat = left;\n } else if (transform.locationPoint(right).distSqr(priorPos) < delta) {\n lngLat = right;\n }\n }\n\n // Second, wrap toward the center until the new position is on screen, or we can't get\n // any closer.\n while (Math.abs(lngLat.lng - transform.center.lng) > 180) {\n const pos = transform.locationPoint(lngLat);\n if (pos.x >= 0 && pos.y >= 0 && pos.x <= transform.width && pos.y <= transform.height) {\n break;\n }\n if (lngLat.lng > transform.center.lng) {\n lngLat.lng -= 360;\n } else {\n lngLat.lng += 360;\n }\n }\n\n return lngLat;\n}\n","// @flow\n\nexport type Anchor =\n | 'center'\n | 'top'\n | 'bottom'\n | 'left'\n | 'right'\n | 'top-left'\n | 'top-right'\n | 'bottom-left'\n | 'bottom-right';\n\nexport const anchorTranslate: {[_: Anchor]: string} = {\n 'center': 'translate(-50%,-50%)',\n 'top': 'translate(-50%,0)',\n 'top-left': 'translate(0,0)',\n 'top-right': 'translate(-100%,0)',\n 'bottom': 'translate(-50%,-100%)',\n 'bottom-left': 'translate(0,-100%)',\n 'bottom-right': 'translate(-100%,-100%)',\n 'left': 'translate(0,-50%)',\n 'right': 'translate(-100%,-50%)'\n};\n\nexport function applyAnchorClass(element: HTMLElement, anchor: Anchor, prefix: string) {\n const classList = element.classList;\n for (const key in anchorTranslate) {\n classList.remove(`mapboxgl-${prefix}-anchor-${key}`);\n }\n classList.add(`mapboxgl-${prefix}-anchor-${anchor}`);\n}\n","// @flow\n\nimport DOM from '../util/dom';\nimport window from '../util/window';\nimport LngLat from '../geo/lng_lat';\nimport Point from '@mapbox/point-geometry';\nimport smartWrap from '../util/smart_wrap';\nimport {bindAll, extend} from '../util/util';\nimport {type Anchor, anchorTranslate, applyAnchorClass} from './anchor';\nimport {Event, Evented} from '../util/evented';\nimport type Map from './map';\nimport type Popup from './popup';\nimport type {LngLatLike} from \"../geo/lng_lat\";\nimport type {MapMouseEvent, MapTouchEvent} from './events';\nimport type {PointLike} from '@mapbox/point-geometry';\n\ntype Options = {\n element?: HTMLElement,\n offset?: PointLike,\n anchor?: Anchor,\n color?: string,\n scale?: number,\n draggable?: boolean,\n clickTolerance?: number,\n rotation?: number,\n rotationAlignment?: string,\n pitchAlignment?: string\n};\n\n/**\n * Creates a marker component\n * @param {Object} [options]\n * @param {HTMLElement} [options.element] DOM element to use as a marker. The default is a light blue, droplet-shaped SVG marker.\n * @param {string} [options.anchor='center'] A string indicating the part of the Marker that should be positioned closest to the coordinate set via {@link Marker#setLngLat}.\n * Options are `'center'`, `'top'`, `'bottom'`, `'left'`, `'right'`, `'top-left'`, `'top-right'`, `'bottom-left'`, and `'bottom-right'`.\n * @param {PointLike} [options.offset] The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up.\n * @param {string} [options.color='#3FB1CE'] The color to use for the default marker if options.element is not provided. The default is light blue.\n * @param {number} [options.scale=1] The scale to use for the default marker if options.element is not provided. The default scale corresponds to a height of `41px` and a width of `27px`.\n * @param {boolean} [options.draggable=false] A boolean indicating whether or not a marker is able to be dragged to a new position on the map.\n * @param {number} [options.clickTolerance=0] The max number of pixels a user can shift the mouse pointer during a click on the marker for it to be considered a valid click (as opposed to a marker drag). The default is to inherit map's clickTolerance.\n * @param {number} [options.rotation=0] The rotation angle of the marker in degrees, relative to its respective `rotationAlignment` setting. A positive value will rotate the marker clockwise.\n * @param {string} [options.pitchAlignment='auto'] `map` aligns the `Marker` to the plane of the map. `viewport` aligns the `Marker` to the plane of the viewport. `auto` automatically matches the value of `rotationAlignment`.\n * @param {string} [options.rotationAlignment='auto'] `map` aligns the `Marker`'s rotation relative to the map, maintaining a bearing as the map rotates. `viewport` aligns the `Marker`'s rotation relative to the viewport, agnostic to map rotations. `auto` is equivalent to `viewport`.\n * @example\n * var marker = new mapboxgl.Marker()\n * .setLngLat([30.5, 50.5])\n * .addTo(map);\n * @example\n * // Set options\n * var marker = new mapboxgl.Marker({\n * color: \"#FFFFFF\",\n * draggable: true\n * }).setLngLat([30.5, 50.5])\n * .addTo(map);\n * @see [Add custom icons with Markers](https://www.mapbox.com/mapbox-gl-js/example/custom-marker-icons/)\n * @see [Create a draggable Marker](https://www.mapbox.com/mapbox-gl-js/example/drag-a-marker/)\n */\nexport default class Marker extends Evented {\n _map: Map;\n _anchor: Anchor;\n _offset: Point;\n _element: HTMLElement;\n _popup: ?Popup;\n _lngLat: LngLat;\n _pos: ?Point;\n _color: ?string;\n _scale: number;\n _defaultMarker: boolean;\n _draggable: boolean;\n _clickTolerance: number;\n _isDragging: boolean;\n _state: 'inactive' | 'pending' | 'active'; // used for handling drag events\n _positionDelta: ?Point;\n _pointerdownPos: ?Point;\n _rotation: number;\n _pitchAlignment: string;\n _rotationAlignment: string;\n _originalTabIndex: ?string; // original tabindex of _element\n\n constructor(options?: Options, legacyOptions?: Options) {\n super();\n // For backward compatibility -- the constructor used to accept the element as a\n // required first argument, before it was made optional.\n if (options instanceof window.HTMLElement || legacyOptions) {\n options = extend({element: options}, legacyOptions);\n }\n\n bindAll([\n '_update',\n '_onMove',\n '_onUp',\n '_addDragHandler',\n '_onMapClick',\n '_onKeyPress'\n ], this);\n\n this._anchor = options && options.anchor || 'center';\n this._color = options && options.color || '#3FB1CE';\n this._scale = options && options.scale || 1;\n this._draggable = options && options.draggable || false;\n this._clickTolerance = options && options.clickTolerance || 0;\n this._isDragging = false;\n this._state = 'inactive';\n this._rotation = options && options.rotation || 0;\n this._rotationAlignment = options && options.rotationAlignment || 'auto';\n this._pitchAlignment = options && options.pitchAlignment && options.pitchAlignment !== 'auto' ? options.pitchAlignment : this._rotationAlignment;\n\n if (!options || !options.element) {\n this._defaultMarker = true;\n this._element = DOM.create('div');\n this._element.setAttribute('aria-label', 'Map marker');\n\n // create default map marker SVG\n const svg = DOM.createNS('http://www.w3.org/2000/svg', 'svg');\n const defaultHeight = 41;\n const defaultWidth = 27;\n svg.setAttributeNS(null, 'display', 'block');\n svg.setAttributeNS(null, 'height', `${defaultHeight}px`);\n svg.setAttributeNS(null, 'width', `${defaultWidth}px`);\n svg.setAttributeNS(null, 'viewBox', `0 0 ${defaultWidth} ${defaultHeight}`);\n\n const markerLarge = DOM.createNS('http://www.w3.org/2000/svg', 'g');\n markerLarge.setAttributeNS(null, 'stroke', 'none');\n markerLarge.setAttributeNS(null, 'stroke-width', '1');\n markerLarge.setAttributeNS(null, 'fill', 'none');\n markerLarge.setAttributeNS(null, 'fill-rule', 'evenodd');\n\n const page1 = DOM.createNS('http://www.w3.org/2000/svg', 'g');\n page1.setAttributeNS(null, 'fill-rule', 'nonzero');\n\n const shadow = DOM.createNS('http://www.w3.org/2000/svg', 'g');\n shadow.setAttributeNS(null, 'transform', 'translate(3.0, 29.0)');\n shadow.setAttributeNS(null, 'fill', '#000000');\n\n const ellipses = [\n {'rx': '10.5', 'ry': '5.25002273'},\n {'rx': '10.5', 'ry': '5.25002273'},\n {'rx': '9.5', 'ry': '4.77275007'},\n {'rx': '8.5', 'ry': '4.29549936'},\n {'rx': '7.5', 'ry': '3.81822308'},\n {'rx': '6.5', 'ry': '3.34094679'},\n {'rx': '5.5', 'ry': '2.86367051'},\n {'rx': '4.5', 'ry': '2.38636864'}\n ];\n\n for (const data of ellipses) {\n const ellipse = DOM.createNS('http://www.w3.org/2000/svg', 'ellipse');\n ellipse.setAttributeNS(null, 'opacity', '0.04');\n ellipse.setAttributeNS(null, 'cx', '10.5');\n ellipse.setAttributeNS(null, 'cy', '5.80029008');\n ellipse.setAttributeNS(null, 'rx', data['rx']);\n ellipse.setAttributeNS(null, 'ry', data['ry']);\n shadow.appendChild(ellipse);\n }\n\n const background = DOM.createNS('http://www.w3.org/2000/svg', 'g');\n background.setAttributeNS(null, 'fill', this._color);\n\n const bgPath = DOM.createNS('http://www.w3.org/2000/svg', 'path');\n bgPath.setAttributeNS(null, 'd', 'M27,13.5 C27,19.074644 20.250001,27.000002 14.75,34.500002 C14.016665,35.500004 12.983335,35.500004 12.25,34.500002 C6.7499993,27.000002 0,19.222562 0,13.5 C0,6.0441559 6.0441559,0 13.5,0 C20.955844,0 27,6.0441559 27,13.5 Z');\n\n background.appendChild(bgPath);\n\n const border = DOM.createNS('http://www.w3.org/2000/svg', 'g');\n border.setAttributeNS(null, 'opacity', '0.25');\n border.setAttributeNS(null, 'fill', '#000000');\n\n const borderPath = DOM.createNS('http://www.w3.org/2000/svg', 'path');\n borderPath.setAttributeNS(null, 'd', 'M13.5,0 C6.0441559,0 0,6.0441559 0,13.5 C0,19.222562 6.7499993,27 12.25,34.5 C13,35.522727 14.016664,35.500004 14.75,34.5 C20.250001,27 27,19.074644 27,13.5 C27,6.0441559 20.955844,0 13.5,0 Z M13.5,1 C20.415404,1 26,6.584596 26,13.5 C26,15.898657 24.495584,19.181431 22.220703,22.738281 C19.945823,26.295132 16.705119,30.142167 13.943359,33.908203 C13.743445,34.180814 13.612715,34.322738 13.5,34.441406 C13.387285,34.322738 13.256555,34.180814 13.056641,33.908203 C10.284481,30.127985 7.4148684,26.314159 5.015625,22.773438 C2.6163816,19.232715 1,15.953538 1,13.5 C1,6.584596 6.584596,1 13.5,1 Z');\n\n border.appendChild(borderPath);\n\n const maki = DOM.createNS('http://www.w3.org/2000/svg', 'g');\n maki.setAttributeNS(null, 'transform', 'translate(6.0, 7.0)');\n maki.setAttributeNS(null, 'fill', '#FFFFFF');\n\n const circleContainer = DOM.createNS('http://www.w3.org/2000/svg', 'g');\n circleContainer.setAttributeNS(null, 'transform', 'translate(8.0, 8.0)');\n\n const circle1 = DOM.createNS('http://www.w3.org/2000/svg', 'circle');\n circle1.setAttributeNS(null, 'fill', '#000000');\n circle1.setAttributeNS(null, 'opacity', '0.25');\n circle1.setAttributeNS(null, 'cx', '5.5');\n circle1.setAttributeNS(null, 'cy', '5.5');\n circle1.setAttributeNS(null, 'r', '5.4999962');\n\n const circle2 = DOM.createNS('http://www.w3.org/2000/svg', 'circle');\n circle2.setAttributeNS(null, 'fill', '#FFFFFF');\n circle2.setAttributeNS(null, 'cx', '5.5');\n circle2.setAttributeNS(null, 'cy', '5.5');\n circle2.setAttributeNS(null, 'r', '5.4999962');\n\n circleContainer.appendChild(circle1);\n circleContainer.appendChild(circle2);\n\n page1.appendChild(shadow);\n page1.appendChild(background);\n page1.appendChild(border);\n page1.appendChild(maki);\n page1.appendChild(circleContainer);\n\n svg.appendChild(page1);\n\n svg.setAttributeNS(null, 'height', `${defaultHeight * this._scale}px`);\n svg.setAttributeNS(null, 'width', `${defaultWidth * this._scale}px`);\n\n this._element.appendChild(svg);\n\n // if no element and no offset option given apply an offset for the default marker\n // the -14 as the y value of the default marker offset was determined as follows\n //\n // the marker tip is at the center of the shadow ellipse from the default svg\n // the y value of the center of the shadow ellipse relative to the svg top left is \"shadow transform translate-y (29.0) + ellipse cy (5.80029008)\"\n // offset to the svg center \"height (41 / 2)\" gives (29.0 + 5.80029008) - (41 / 2) and rounded for an integer pixel offset gives 14\n // negative is used to move the marker up from the center so the tip is at the Marker lngLat\n this._offset = Point.convert(options && options.offset || [0, -14]);\n } else {\n this._element = options.element;\n this._offset = Point.convert(options && options.offset || [0, 0]);\n }\n\n this._element.classList.add('mapboxgl-marker');\n this._element.addEventListener('dragstart', (e: DragEvent) => {\n e.preventDefault();\n });\n this._element.addEventListener('mousedown', (e: MouseEvent) => {\n // prevent focusing on click\n e.preventDefault();\n });\n applyAnchorClass(this._element, this._anchor, 'marker');\n\n this._popup = null;\n }\n\n /**\n * Attaches the `Marker` to a `Map` object.\n * @param {Map} map The Mapbox GL JS map to add the marker to.\n * @returns {Marker} `this`\n * @example\n * var marker = new mapboxgl.Marker()\n * .setLngLat([30.5, 50.5])\n * .addTo(map); // add the marker to the map\n */\n addTo(map: Map) {\n this.remove();\n this._map = map;\n map.getCanvasContainer().appendChild(this._element);\n map.on('move', this._update);\n map.on('moveend', this._update);\n this.setDraggable(this._draggable);\n this._update();\n\n // If we attached the `click` listener to the marker element, the popup\n // would close once the event propogated to `map` due to the\n // `Popup#_onClickClose` listener.\n this._map.on('click', this._onMapClick);\n\n return this;\n }\n\n /**\n * Removes the marker from a map\n * @example\n * var marker = new mapboxgl.Marker().addTo(map);\n * marker.remove();\n * @returns {Marker} `this`\n */\n remove() {\n if (this._map) {\n this._map.off('click', this._onMapClick);\n this._map.off('move', this._update);\n this._map.off('moveend', this._update);\n this._map.off('mousedown', this._addDragHandler);\n this._map.off('touchstart', this._addDragHandler);\n this._map.off('mouseup', this._onUp);\n this._map.off('touchend', this._onUp);\n this._map.off('mousemove', this._onMove);\n this._map.off('touchmove', this._onMove);\n delete this._map;\n }\n DOM.remove(this._element);\n if (this._popup) this._popup.remove();\n return this;\n }\n\n /**\n * Get the marker's geographical location.\n *\n * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously\n * set by `setLngLat` because `Marker` wraps the anchor longitude across copies of the world to keep\n * the marker on screen.\n *\n * @returns {LngLat} A {@link LngLat} describing the marker's location.\n * @example\n * // Store the marker's longitude and latitude coordinates in a variable\n * var lngLat = marker.getLngLat();\n * // Print the marker's longitude and latitude values in the console\n * console.log('Longitude: ' + lngLat.lng + ', Latitude: ' + lngLat.lat )\n * @see [Create a draggable Marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-marker/)\n */\n getLngLat() {\n return this._lngLat;\n }\n\n /**\n * Set the marker's geographical position and move it.\n * @param {LngLat} lnglat A {@link LngLat} describing where the marker should be located.\n * @returns {Marker} `this`\n * @example\n * // Create a new marker, set the longitude and latitude, and add it to the map\n * new mapboxgl.Marker()\n * .setLngLat([-65.017, -16.457])\n * .addTo(map);\n * @see [Add custom icons with Markers](https://docs.mapbox.com/mapbox-gl-js/example/custom-marker-icons/)\n * @see [Create a draggable Marker](https://docs.mapbox.com/mapbox-gl-js/example/drag-a-marker/)\n * @see [Add a marker using a place name](https://docs.mapbox.com/mapbox-gl-js/example/marker-from-geocode/)\n */\n setLngLat(lnglat: LngLatLike) {\n this._lngLat = LngLat.convert(lnglat);\n this._pos = null;\n if (this._popup) this._popup.setLngLat(this._lngLat);\n this._update();\n return this;\n }\n\n /**\n * Returns the `Marker`'s HTML element.\n * @returns {HTMLElement} element\n */\n getElement() {\n return this._element;\n }\n\n /**\n * Binds a {@link Popup} to the {@link Marker}.\n * @param popup An instance of the {@link Popup} class. If undefined or null, any popup\n * set on this {@link Marker} instance is unset.\n * @returns {Marker} `this`\n * @example\n * var marker = new mapboxgl.Marker()\n * .setLngLat([0, 0])\n * .setPopup(new mapboxgl.Popup().setHTML(\"

Hello World!

\")) // add popup\n * .addTo(map);\n * @see [Attach a popup to a marker instance](https://docs.mapbox.com/mapbox-gl-js/example/set-popup/)\n */\n setPopup(popup: ?Popup) {\n if (this._popup) {\n this._popup.remove();\n this._popup = null;\n this._element.removeEventListener('keypress', this._onKeyPress);\n\n if (!this._originalTabIndex) {\n this._element.removeAttribute('tabindex');\n }\n }\n\n if (popup) {\n if (!('offset' in popup.options)) {\n const markerHeight = 41 - (5.8 / 2);\n const markerRadius = 13.5;\n const linearOffset = Math.sqrt(Math.pow(markerRadius, 2) / 2);\n popup.options.offset = this._defaultMarker ? {\n 'top': [0, 0],\n 'top-left': [0, 0],\n 'top-right': [0, 0],\n 'bottom': [0, -markerHeight],\n 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1],\n 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1],\n 'left': [markerRadius, (markerHeight - markerRadius) * -1],\n 'right': [-markerRadius, (markerHeight - markerRadius) * -1]\n } : this._offset;\n }\n this._popup = popup;\n if (this._lngLat) this._popup.setLngLat(this._lngLat);\n\n this._originalTabIndex = this._element.getAttribute('tabindex');\n if (!this._originalTabIndex) {\n this._element.setAttribute('tabindex', '0');\n }\n this._element.addEventListener('keypress', this._onKeyPress);\n }\n\n return this;\n }\n\n _onKeyPress(e: KeyboardEvent) {\n const code = e.code;\n const legacyCode = e.charCode || e.keyCode;\n\n if (\n (code === 'Space') || (code === 'Enter') ||\n (legacyCode === 32) || (legacyCode === 13) // space or enter\n ) {\n this.togglePopup();\n }\n }\n\n _onMapClick(e: MapMouseEvent) {\n const targetElement = e.originalEvent.target;\n const element = this._element;\n\n if (this._popup && (targetElement === element || element.contains((targetElement: any)))) {\n this.togglePopup();\n }\n }\n\n /**\n * Returns the {@link Popup} instance that is bound to the {@link Marker}.\n * @returns {Popup} popup\n * @example\n * var marker = new mapboxgl.Marker()\n * .setLngLat([0, 0])\n * .setPopup(new mapboxgl.Popup().setHTML(\"

Hello World!

\"))\n * .addTo(map);\n *\n * console.log(marker.getPopup()); // return the popup instance\n */\n getPopup() {\n return this._popup;\n }\n\n /**\n * Opens or closes the {@link Popup} instance that is bound to the {@link Marker}, depending on the current state of the {@link Popup}.\n * @returns {Marker} `this`\n * @example\n * var marker = new mapboxgl.Marker()\n * .setLngLat([0, 0])\n * .setPopup(new mapboxgl.Popup().setHTML(\"

Hello World!

\"))\n * .addTo(map);\n *\n * marker.togglePopup(); // toggle popup open or closed\n */\n togglePopup() {\n const popup = this._popup;\n\n if (!popup) return this;\n else if (popup.isOpen()) popup.remove();\n else popup.addTo(this._map);\n return this;\n }\n\n _update(e?: {type: 'move' | 'moveend'}) {\n if (!this._map) return;\n\n if (this._map.transform.renderWorldCopies) {\n this._lngLat = smartWrap(this._lngLat, this._pos, this._map.transform);\n }\n\n this._pos = this._map.project(this._lngLat)._add(this._offset);\n\n let rotation = \"\";\n if (this._rotationAlignment === \"viewport\" || this._rotationAlignment === \"auto\") {\n rotation = `rotateZ(${this._rotation}deg)`;\n } else if (this._rotationAlignment === \"map\") {\n rotation = `rotateZ(${this._rotation - this._map.getBearing()}deg)`;\n }\n\n let pitch = \"\";\n if (this._pitchAlignment === \"viewport\" || this._pitchAlignment === \"auto\") {\n pitch = \"rotateX(0deg)\";\n } else if (this._pitchAlignment === \"map\") {\n pitch = `rotateX(${this._map.getPitch()}deg)`;\n }\n\n // because rounding the coordinates at every `move` event causes stuttered zooming\n // we only round them when _update is called with `moveend` or when its called with\n // no arguments (when the Marker is initialized or Marker#setLngLat is invoked).\n if (!e || e.type === \"moveend\") {\n this._pos = this._pos.round();\n }\n\n DOM.setTransform(this._element, `${anchorTranslate[this._anchor]} translate(${this._pos.x}px, ${this._pos.y}px) ${pitch} ${rotation}`);\n }\n\n /**\n * Get the marker's offset.\n * @returns {Point} The marker's screen coordinates in pixels.\n */\n getOffset() {\n return this._offset;\n }\n\n /**\n * Sets the offset of the marker\n * @param {PointLike} offset The offset in pixels as a {@link PointLike} object to apply relative to the element's center. Negatives indicate left and up.\n * @returns {Marker} `this`\n */\n setOffset(offset: PointLike) {\n this._offset = Point.convert(offset);\n this._update();\n return this;\n }\n\n _onMove(e: MapMouseEvent | MapTouchEvent) {\n if (!this._isDragging) {\n const clickTolerance = this._clickTolerance || this._map._clickTolerance;\n this._isDragging = e.point.dist(this._pointerdownPos) >= clickTolerance;\n }\n if (!this._isDragging) return;\n\n this._pos = e.point.sub(this._positionDelta);\n this._lngLat = this._map.unproject(this._pos);\n this.setLngLat(this._lngLat);\n // suppress click event so that popups don't toggle on drag\n this._element.style.pointerEvents = 'none';\n\n // make sure dragstart only fires on the first move event after mousedown.\n // this can't be on mousedown because that event doesn't necessarily\n // imply that a drag is about to happen.\n if (this._state === 'pending') {\n this._state = 'active';\n\n /**\n * Fired when dragging starts\n *\n * @event dragstart\n * @memberof Marker\n * @instance\n * @type {Object}\n * @property {Marker} marker object that is being dragged\n */\n this.fire(new Event('dragstart'));\n }\n\n /**\n * Fired while dragging\n *\n * @event drag\n * @memberof Marker\n * @instance\n * @type {Object}\n * @property {Marker} marker object that is being dragged\n */\n this.fire(new Event('drag'));\n }\n\n _onUp() {\n // revert to normal pointer event handling\n this._element.style.pointerEvents = 'auto';\n this._positionDelta = null;\n this._pointerdownPos = null;\n this._isDragging = false;\n this._map.off('mousemove', this._onMove);\n this._map.off('touchmove', this._onMove);\n\n // only fire dragend if it was preceded by at least one drag event\n if (this._state === 'active') {\n /**\n * Fired when the marker is finished being dragged\n *\n * @event dragend\n * @memberof Marker\n * @instance\n * @type {Object}\n * @property {Marker} marker object that was dragged\n */\n this.fire(new Event('dragend'));\n }\n\n this._state = 'inactive';\n }\n\n _addDragHandler(e: MapMouseEvent | MapTouchEvent) {\n if (this._element.contains((e.originalEvent.target: any))) {\n e.preventDefault();\n\n // We need to calculate the pixel distance between the click point\n // and the marker position, with the offset accounted for. Then we\n // can subtract this distance from the mousemove event's position\n // to calculate the new marker position.\n // If we don't do this, the marker 'jumps' to the click position\n // creating a jarring UX effect.\n this._positionDelta = e.point.sub(this._pos).add(this._offset);\n\n this._pointerdownPos = e.point;\n\n this._state = 'pending';\n this._map.on('mousemove', this._onMove);\n this._map.on('touchmove', this._onMove);\n this._map.once('mouseup', this._onUp);\n this._map.once('touchend', this._onUp);\n }\n }\n\n /**\n * Sets the `draggable` property and functionality of the marker\n * @param {boolean} [shouldBeDraggable=false] Turns drag functionality on/off\n * @returns {Marker} `this`\n */\n setDraggable(shouldBeDraggable: boolean) {\n this._draggable = !!shouldBeDraggable; // convert possible undefined value to false\n\n // handle case where map may not exist yet\n // e.g. when setDraggable is called before addTo\n if (this._map) {\n if (shouldBeDraggable) {\n this._map.on('mousedown', this._addDragHandler);\n this._map.on('touchstart', this._addDragHandler);\n } else {\n this._map.off('mousedown', this._addDragHandler);\n this._map.off('touchstart', this._addDragHandler);\n }\n }\n\n return this;\n }\n\n /**\n * Returns true if the marker can be dragged\n * @returns {boolean} True if the marker is draggable.\n */\n isDraggable() {\n return this._draggable;\n }\n\n /**\n * Sets the `rotation` property of the marker.\n * @param {number} [rotation=0] The rotation angle of the marker (clockwise, in degrees), relative to its respective {@link Marker#setRotationAlignment} setting.\n * @returns {Marker} `this`\n */\n setRotation(rotation: number) {\n this._rotation = rotation || 0;\n this._update();\n return this;\n }\n\n /**\n * Returns the current rotation angle of the marker (in degrees).\n * @returns {number} The current rotation angle of the marker.\n */\n getRotation() {\n return this._rotation;\n }\n\n /**\n * Sets the `rotationAlignment` property of the marker.\n * @param {string} [alignment='auto'] Sets the `rotationAlignment` property of the marker.\n * @returns {Marker} `this`\n */\n setRotationAlignment(alignment: string) {\n this._rotationAlignment = alignment || 'auto';\n this._update();\n return this;\n }\n\n /**\n * Returns the current `rotationAlignment` property of the marker.\n * @returns {string} The current rotational alignment of the marker.\n */\n getRotationAlignment() {\n return this._rotationAlignment;\n }\n\n /**\n * Sets the `pitchAlignment` property of the marker.\n * @param {string} [alignment] Sets the `pitchAlignment` property of the marker. If alignment is 'auto', it will automatically match `rotationAlignment`.\n * @returns {Marker} `this`\n */\n setPitchAlignment(alignment: string) {\n this._pitchAlignment = alignment && alignment !== 'auto' ? alignment : this._rotationAlignment;\n this._update();\n return this;\n }\n\n /**\n * Returns the current `pitchAlignment` property of the marker.\n * @returns {string} The current pitch alignment of the marker in degrees.\n */\n getPitchAlignment() {\n return this._pitchAlignment;\n }\n}\n","// @flow\n\nimport {Event, Evented} from '../../util/evented';\nimport DOM from '../../util/dom';\nimport window from '../../util/window';\nimport {extend, bindAll, warnOnce} from '../../util/util';\nimport assert from 'assert';\nimport LngLat from '../../geo/lng_lat';\nimport Marker from '../marker';\n\nimport type Map from '../map';\nimport type {AnimationOptions, CameraOptions} from '../camera';\n\ntype Options = {\n positionOptions?: PositionOptions,\n fitBoundsOptions?: AnimationOptions & CameraOptions,\n trackUserLocation?: boolean,\n showAccuracyCircle?: boolean,\n showUserLocation?: boolean\n};\n\nconst defaultOptions: Options = {\n positionOptions: {\n enableHighAccuracy: false,\n maximumAge: 0,\n timeout: 6000 /* 6 sec */\n },\n fitBoundsOptions: {\n maxZoom: 15\n },\n trackUserLocation: false,\n showAccuracyCircle: true,\n showUserLocation: true\n};\n\nlet supportsGeolocation;\n\nfunction checkGeolocationSupport(callback) {\n if (supportsGeolocation !== undefined) {\n callback(supportsGeolocation);\n\n } else if (window.navigator.permissions !== undefined) {\n // navigator.permissions has incomplete browser support\n // http://caniuse.com/#feat=permissions-api\n // Test for the case where a browser disables Geolocation because of an\n // insecure origin\n window.navigator.permissions.query({name: 'geolocation'}).then((p) => {\n supportsGeolocation = p.state !== 'denied';\n callback(supportsGeolocation);\n });\n\n } else {\n supportsGeolocation = !!window.navigator.geolocation;\n callback(supportsGeolocation);\n }\n}\n\nlet numberOfWatches = 0;\nlet noTimeout = false;\n\n/**\n * A `GeolocateControl` control provides a button that uses the browser's geolocation\n * API to locate the user on the map.\n *\n * Not all browsers support geolocation,\n * and some users may disable the feature. Geolocation support for modern\n * browsers including Chrome requires sites to be served over HTTPS. If\n * geolocation support is not available, the GeolocateControl will show\n * as disabled.\n *\n * The zoom level applied will depend on the accuracy of the geolocation provided by the device.\n *\n * The GeolocateControl has two modes. If `trackUserLocation` is `false` (default) the control acts as a button, which when pressed will set the map's camera to target the user location. If the user moves, the map won't update. This is most suited for the desktop. If `trackUserLocation` is `true` the control acts as a toggle button that when active the user's location is actively monitored for changes. In this mode the GeolocateControl has three interaction states:\n * * active - the map's camera automatically updates as the user's location changes, keeping the location dot in the center. Initial state and upon clicking the `GeolocateControl` button.\n * * passive - the user's location dot automatically updates, but the map's camera does not. Occurs upon the user initiating a map movement.\n * * disabled - occurs if Geolocation is not available, disabled or denied.\n *\n * These interaction states can't be controlled programmatically, rather they are set based on user interactions.\n *\n * @implements {IControl}\n * @param {Object} [options]\n * @param {Object} [options.positionOptions={enableHighAccuracy: false, timeout: 6000}] A Geolocation API [PositionOptions](https://developer.mozilla.org/en-US/docs/Web/API/PositionOptions) object.\n * @param {Object} [options.fitBoundsOptions={maxZoom: 15}] A {@link Map#fitBounds} options object to use when the map is panned and zoomed to the user's location. The default is to use a `maxZoom` of 15 to limit how far the map will zoom in for very accurate locations.\n * @param {Object} [options.trackUserLocation=false] If `true` the Geolocate Control becomes a toggle button and when active the map will receive updates to the user's location as it changes.\n * @param {Object} [options.showAccuracyCircle=true] By default, if showUserLocation is `true`, a transparent circle will be drawn around the user location indicating the accuracy (95% confidence level) of the user's location. Set to `false` to disable. Always disabled when showUserLocation is `false`.\n * @param {Object} [options.showUserLocation=true] By default a dot will be shown on the map at the user's location. Set to `false` to disable.\n *\n * @example\n * map.addControl(new mapboxgl.GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * }));\n * @see [Locate the user](https://www.mapbox.com/mapbox-gl-js/example/locate-user/)\n */\nclass GeolocateControl extends Evented {\n _map: Map;\n options: Options;\n _container: HTMLElement;\n _dotElement: HTMLElement;\n _circleElement: HTMLElement;\n _geolocateButton: HTMLButtonElement;\n _geolocationWatchID: number;\n _timeoutId: ?TimeoutID;\n _watchState: 'OFF' | 'ACTIVE_LOCK' | 'WAITING_ACTIVE' | 'ACTIVE_ERROR' | 'BACKGROUND' | 'BACKGROUND_ERROR';\n _lastKnownPosition: any;\n _userLocationDotMarker: Marker;\n _accuracyCircleMarker: Marker;\n _accuracy: number;\n _setup: boolean; // set to true once the control has been setup\n\n constructor(options: Options) {\n super();\n this.options = extend({}, defaultOptions, options);\n\n bindAll([\n '_onSuccess',\n '_onError',\n '_onZoom',\n '_finish',\n '_setupUI',\n '_updateCamera',\n '_updateMarker'\n ], this);\n }\n\n onAdd(map: Map) {\n this._map = map;\n this._container = DOM.create('div', `mapboxgl-ctrl mapboxgl-ctrl-group`);\n checkGeolocationSupport(this._setupUI);\n return this._container;\n }\n\n onRemove() {\n // clear the geolocation watch if exists\n if (this._geolocationWatchID !== undefined) {\n window.navigator.geolocation.clearWatch(this._geolocationWatchID);\n this._geolocationWatchID = (undefined: any);\n }\n\n // clear the markers from the map\n if (this.options.showUserLocation && this._userLocationDotMarker) {\n this._userLocationDotMarker.remove();\n }\n if (this.options.showAccuracyCircle && this._accuracyCircleMarker) {\n this._accuracyCircleMarker.remove();\n }\n\n DOM.remove(this._container);\n this._map.off('zoom', this._onZoom);\n this._map = (undefined: any);\n numberOfWatches = 0;\n noTimeout = false;\n }\n\n /**\n * Check if the Geolocation API Position is outside the map's maxbounds.\n *\n * @param {Position} position the Geolocation API Position\n * @returns {boolean} Returns `true` if position is outside the map's maxbounds, otherwise returns `false`.\n * @private\n */\n _isOutOfMapMaxBounds(position: Position) {\n const bounds = this._map.getMaxBounds();\n const coordinates = position.coords;\n\n return bounds && (\n coordinates.longitude < bounds.getWest() ||\n coordinates.longitude > bounds.getEast() ||\n coordinates.latitude < bounds.getSouth() ||\n coordinates.latitude > bounds.getNorth()\n );\n }\n\n _setErrorState() {\n switch (this._watchState) {\n case 'WAITING_ACTIVE':\n this._watchState = 'ACTIVE_ERROR';\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error');\n break;\n case 'ACTIVE_LOCK':\n this._watchState = 'ACTIVE_ERROR';\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');\n // turn marker grey\n break;\n case 'BACKGROUND':\n this._watchState = 'BACKGROUND_ERROR';\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background-error');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');\n // turn marker grey\n break;\n case 'ACTIVE_ERROR':\n break;\n default:\n assert(false, `Unexpected watchState ${this._watchState}`);\n }\n }\n\n /**\n * When the Geolocation API returns a new location, update the GeolocateControl.\n *\n * @param {Position} position the Geolocation API Position\n * @private\n */\n _onSuccess(position: Position) {\n if (!this._map) {\n // control has since been removed\n return;\n }\n\n if (this._isOutOfMapMaxBounds(position)) {\n this._setErrorState();\n\n this.fire(new Event('outofmaxbounds', position));\n this._updateMarker();\n this._finish();\n\n return;\n }\n\n if (this.options.trackUserLocation) {\n // keep a record of the position so that if the state is BACKGROUND and the user\n // clicks the button, we can move to ACTIVE_LOCK immediately without waiting for\n // watchPosition to trigger _onSuccess\n this._lastKnownPosition = position;\n\n switch (this._watchState) {\n case 'WAITING_ACTIVE':\n case 'ACTIVE_LOCK':\n case 'ACTIVE_ERROR':\n this._watchState = 'ACTIVE_LOCK';\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active');\n break;\n case 'BACKGROUND':\n case 'BACKGROUND_ERROR':\n this._watchState = 'BACKGROUND';\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background');\n break;\n default:\n assert(false, `Unexpected watchState ${this._watchState}`);\n }\n }\n\n // if showUserLocation and the watch state isn't off then update the marker location\n if (this.options.showUserLocation && this._watchState !== 'OFF') {\n this._updateMarker(position);\n }\n\n // if in normal mode (not watch mode), or if in watch mode and the state is active watch\n // then update the camera\n if (!this.options.trackUserLocation || this._watchState === 'ACTIVE_LOCK') {\n this._updateCamera(position);\n }\n\n if (this.options.showUserLocation) {\n this._dotElement.classList.remove('mapboxgl-user-location-dot-stale');\n }\n\n this.fire(new Event('geolocate', position));\n this._finish();\n }\n\n /**\n * Update the camera location to center on the current position\n *\n * @param {Position} position the Geolocation API Position\n * @private\n */\n _updateCamera(position: Position) {\n const center = new LngLat(position.coords.longitude, position.coords.latitude);\n const radius = position.coords.accuracy;\n const bearing = this._map.getBearing();\n const options = extend({bearing}, this.options.fitBoundsOptions);\n\n this._map.fitBounds(center.toBounds(radius), options, {\n geolocateSource: true // tag this camera change so it won't cause the control to change to background state\n });\n }\n\n /**\n * Update the user location dot Marker to the current position\n *\n * @param {Position} [position] the Geolocation API Position\n * @private\n */\n _updateMarker(position: ?Position) {\n if (position) {\n const center = new LngLat(position.coords.longitude, position.coords.latitude);\n this._accuracyCircleMarker.setLngLat(center).addTo(this._map);\n this._userLocationDotMarker.setLngLat(center).addTo(this._map);\n this._accuracy = position.coords.accuracy;\n if (this.options.showUserLocation && this.options.showAccuracyCircle) {\n this._updateCircleRadius();\n }\n } else {\n this._userLocationDotMarker.remove();\n this._accuracyCircleMarker.remove();\n }\n }\n\n _updateCircleRadius() {\n assert(this._circleElement);\n const y = this._map._container.clientHeight / 2;\n const a = this._map.unproject([0, y]);\n const b = this._map.unproject([1, y]);\n const metersPerPixel = a.distanceTo(b);\n const circleDiameter = Math.ceil(2.0 * this._accuracy / metersPerPixel);\n this._circleElement.style.width = `${circleDiameter}px`;\n this._circleElement.style.height = `${circleDiameter}px`;\n }\n\n _onZoom() {\n if (this.options.showUserLocation && this.options.showAccuracyCircle) {\n this._updateCircleRadius();\n }\n }\n\n _onError(error: PositionError) {\n if (!this._map) {\n // control has since been removed\n return;\n }\n\n if (this.options.trackUserLocation) {\n if (error.code === 1) {\n // PERMISSION_DENIED\n this._watchState = 'OFF';\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error');\n this._geolocateButton.disabled = true;\n const title = this._map._getUIString('GeolocateControl.LocationNotAvailable');\n this._geolocateButton.title = title;\n this._geolocateButton.setAttribute('aria-label', title);\n\n if (this._geolocationWatchID !== undefined) {\n this._clearWatch();\n }\n } else if (error.code === 3 && noTimeout) {\n // this represents a forced error state\n // this was triggered to force immediate geolocation when a watch is already present\n // see https://github.com/mapbox/mapbox-gl-js/issues/8214\n // and https://w3c.github.io/geolocation-api/#example-5-forcing-the-user-agent-to-return-a-fresh-cached-position\n return;\n } else {\n this._setErrorState();\n }\n }\n\n if (this._watchState !== 'OFF' && this.options.showUserLocation) {\n this._dotElement.classList.add('mapboxgl-user-location-dot-stale');\n }\n\n this.fire(new Event('error', error));\n\n this._finish();\n }\n\n _finish() {\n if (this._timeoutId) { clearTimeout(this._timeoutId); }\n this._timeoutId = undefined;\n }\n\n _setupUI(supported: boolean) {\n this._container.addEventListener('contextmenu', (e: MouseEvent) => e.preventDefault());\n this._geolocateButton = DOM.create('button', `mapboxgl-ctrl-geolocate`, this._container);\n DOM.create('span', `mapboxgl-ctrl-icon`, this._geolocateButton).setAttribute('aria-hidden', true);\n this._geolocateButton.type = 'button';\n\n if (supported === false) {\n warnOnce('Geolocation support is not available so the GeolocateControl will be disabled.');\n const title = this._map._getUIString('GeolocateControl.LocationNotAvailable');\n this._geolocateButton.disabled = true;\n this._geolocateButton.title = title;\n this._geolocateButton.setAttribute('aria-label', title);\n } else {\n const title = this._map._getUIString('GeolocateControl.FindMyLocation');\n this._geolocateButton.title = title;\n this._geolocateButton.setAttribute('aria-label', title);\n }\n\n if (this.options.trackUserLocation) {\n this._geolocateButton.setAttribute('aria-pressed', 'false');\n this._watchState = 'OFF';\n }\n\n // when showUserLocation is enabled, keep the Geolocate button disabled until the device location marker is setup on the map\n if (this.options.showUserLocation) {\n this._dotElement = DOM.create('div', 'mapboxgl-user-location-dot');\n\n this._userLocationDotMarker = new Marker(this._dotElement);\n\n this._circleElement = DOM.create('div', 'mapboxgl-user-location-accuracy-circle');\n this._accuracyCircleMarker = new Marker({element: this._circleElement, pitchAlignment: 'map'});\n\n if (this.options.trackUserLocation) this._watchState = 'OFF';\n\n this._map.on('zoom', this._onZoom);\n }\n\n this._geolocateButton.addEventListener('click',\n this.trigger.bind(this));\n\n this._setup = true;\n\n // when the camera is changed (and it's not as a result of the Geolocation Control) change\n // the watch mode to background watch, so that the marker is updated but not the camera.\n if (this.options.trackUserLocation) {\n this._map.on('movestart', (event) => {\n const fromResize = event.originalEvent && event.originalEvent.type === 'resize';\n if (!event.geolocateSource && this._watchState === 'ACTIVE_LOCK' && !fromResize) {\n this._watchState = 'BACKGROUND';\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');\n\n this.fire(new Event('trackuserlocationend'));\n }\n });\n }\n }\n\n /**\n * Programmatically request and move the map to the user's location.\n *\n * @returns {boolean} Returns `false` if called before control was added to a map, otherwise returns `true`.\n * @example\n * // Initialize the geolocate control.\n * var geolocate = new mapboxgl.GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * map.on('load', function() {\n * geolocate.trigger();\n * });\n */\n trigger() {\n if (!this._setup) {\n warnOnce('Geolocate control triggered before added to a map');\n return false;\n }\n if (this.options.trackUserLocation) {\n // update watchState and do any outgoing state cleanup\n switch (this._watchState) {\n case 'OFF':\n // turn on the Geolocate Control\n this._watchState = 'WAITING_ACTIVE';\n\n this.fire(new Event('trackuserlocationstart'));\n break;\n case 'WAITING_ACTIVE':\n case 'ACTIVE_LOCK':\n case 'ACTIVE_ERROR':\n case 'BACKGROUND_ERROR':\n // turn off the Geolocate Control\n numberOfWatches--;\n noTimeout = false;\n this._watchState = 'OFF';\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-active-error');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background');\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background-error');\n\n this.fire(new Event('trackuserlocationend'));\n break;\n case 'BACKGROUND':\n this._watchState = 'ACTIVE_LOCK';\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-background');\n // set camera to last known location\n if (this._lastKnownPosition) this._updateCamera(this._lastKnownPosition);\n\n this.fire(new Event('trackuserlocationstart'));\n break;\n default:\n assert(false, `Unexpected watchState ${this._watchState}`);\n }\n\n // incoming state setup\n switch (this._watchState) {\n case 'WAITING_ACTIVE':\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active');\n break;\n case 'ACTIVE_LOCK':\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active');\n break;\n case 'ACTIVE_ERROR':\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-active-error');\n break;\n case 'BACKGROUND':\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background');\n break;\n case 'BACKGROUND_ERROR':\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-background-error');\n break;\n case 'OFF':\n break;\n default:\n assert(false, `Unexpected watchState ${this._watchState}`);\n }\n\n // manage geolocation.watchPosition / geolocation.clearWatch\n if (this._watchState === 'OFF' && this._geolocationWatchID !== undefined) {\n // clear watchPosition as we've changed to an OFF state\n this._clearWatch();\n } else if (this._geolocationWatchID === undefined) {\n // enable watchPosition since watchState is not OFF and there is no watchPosition already running\n\n this._geolocateButton.classList.add('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.setAttribute('aria-pressed', 'true');\n\n numberOfWatches++;\n let positionOptions;\n if (numberOfWatches > 1) {\n positionOptions = {maximumAge:600000, timeout:0};\n noTimeout = true;\n } else {\n positionOptions = this.options.positionOptions;\n noTimeout = false;\n }\n\n this._geolocationWatchID = window.navigator.geolocation.watchPosition(\n this._onSuccess, this._onError, positionOptions);\n }\n } else {\n window.navigator.geolocation.getCurrentPosition(\n this._onSuccess, this._onError, this.options.positionOptions);\n\n // This timeout ensures that we still call finish() even if\n // the user declines to share their location in Firefox\n this._timeoutId = setTimeout(this._finish, 10000 /* 10sec */);\n }\n\n return true;\n }\n\n _clearWatch() {\n window.navigator.geolocation.clearWatch(this._geolocationWatchID);\n\n this._geolocationWatchID = (undefined: any);\n this._geolocateButton.classList.remove('mapboxgl-ctrl-geolocate-waiting');\n this._geolocateButton.setAttribute('aria-pressed', 'false');\n\n if (this.options.showUserLocation) {\n this._updateMarker(null);\n }\n }\n}\n\nexport default GeolocateControl;\n\n/* Geolocate Control Watch States\n * This is the private state of the control.\n *\n * OFF\n * off/inactive\n * WAITING_ACTIVE\n * Geolocate Control was clicked but still waiting for Geolocation API response with user location\n * ACTIVE_LOCK\n * Showing the user location as a dot AND tracking the camera to be fixed to their location. If their location changes the map moves to follow.\n * ACTIVE_ERROR\n * There was en error from the Geolocation API while trying to show and track the user location.\n * BACKGROUND\n * Showing the user location as a dot but the camera doesn't follow their location as it changes.\n * BACKGROUND_ERROR\n * There was an error from the Geolocation API while trying to show (but not track) the user location.\n */\n\n/**\n * Fired on each Geolocation API position update which returned as success.\n *\n * @event geolocate\n * @memberof GeolocateControl\n * @instance\n * @property {Position} data The returned [Position](https://developer.mozilla.org/en-US/docs/Web/API/Position) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition).\n * @example\n * // Initialize the geolocate control.\n * var geolocate = new mapboxgl.GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when a geolocate event occurs.\n * geolocate.on('geolocate', function() {\n * console.log('A geolocate event has occurred.')\n * });\n *\n */\n\n/**\n * Fired on each Geolocation API position update which returned as an error.\n *\n * @event error\n * @memberof GeolocateControl\n * @instance\n * @property {PositionError} data The returned [PositionError](https://developer.mozilla.org/en-US/docs/Web/API/PositionError) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition).\n * @example\n * // Initialize the geolocate control.\n * var geolocate = new mapboxgl.GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when an error event occurs.\n * geolocate.on('error', function() {\n * console.log('An error event has occurred.')\n * });\n *\n */\n\n/**\n * Fired on each Geolocation API position update which returned as success but user position is out of map maxBounds.\n *\n * @event outofmaxbounds\n * @memberof GeolocateControl\n * @instance\n * @property {Position} data The returned [Position](https://developer.mozilla.org/en-US/docs/Web/API/Position) object from the callback in [Geolocation.getCurrentPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) or [Geolocation.watchPosition()](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/watchPosition).\n * @example\n * // Initialize the geolocate control.\n * var geolocate = new mapboxgl.GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when an outofmaxbounds event occurs.\n * geolocate.on('outofmaxbounds', function() {\n * console.log('An outofmaxbounds event has occurred.')\n * });\n *\n */\n\n/**\n * Fired when the Geolocate Control changes to the active lock state, which happens either upon first obtaining a successful Geolocation API position for the user (a geolocate event will follow), or the user clicks the geolocate button when in the background state which uses the last known position to recenter the map and enter active lock state (no geolocate event will follow unless the users's location changes).\n *\n * @event trackuserlocationstart\n * @memberof GeolocateControl\n * @instance\n * @example\n * // Initialize the geolocate control.\n * var geolocate = new mapboxgl.GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when a trackuserlocationstart event occurs.\n * geolocate.on('trackuserlocationstart', function() {\n * console.log('A trackuserlocationstart event has occurred.')\n * });\n *\n */\n\n/**\n * Fired when the Geolocate Control changes to the background state, which happens when a user changes the camera during an active position lock. This only applies when trackUserLocation is true. In the background state, the dot on the map will update with location updates but the camera will not.\n *\n * @event trackuserlocationend\n * @memberof GeolocateControl\n * @instance\n * @example\n * // Initialize the geolocate control.\n * var geolocate = new mapboxgl.GeolocateControl({\n * positionOptions: {\n * enableHighAccuracy: true\n * },\n * trackUserLocation: true\n * });\n * // Add the control to the map.\n * map.addControl(geolocate);\n * // Set an event listener that fires\n * // when a trackuserlocationend event occurs.\n * geolocate.on('trackuserlocationend', function() {\n * console.log('A trackuserlocationend event has occurred.')\n * });\n *\n */\n","// @flow\n\nimport DOM from '../../util/dom';\nimport {extend, bindAll} from '../../util/util';\n\nimport type Map from '../map';\n\ntype Unit = 'imperial' | 'metric' | 'nautical';\n\ntype Options = {\n maxWidth?: number,\n unit?: Unit;\n};\n\nconst defaultOptions: Options = {\n maxWidth: 100,\n unit: 'metric'\n};\n\n/**\n * A `ScaleControl` control displays the ratio of a distance on the map to the corresponding distance on the ground.\n *\n * @implements {IControl}\n * @param {Object} [options]\n * @param {number} [options.maxWidth='100'] The maximum length of the scale control in pixels.\n * @param {string} [options.unit='metric'] Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`).\n * @example\n * var scale = new mapboxgl.ScaleControl({\n * maxWidth: 80,\n * unit: 'imperial'\n * });\n * map.addControl(scale);\n *\n * scale.setUnit('metric');\n */\nclass ScaleControl {\n _map: Map;\n _container: HTMLElement;\n options: Options;\n\n constructor(options: Options) {\n this.options = extend({}, defaultOptions, options);\n\n bindAll([\n '_onMove',\n 'setUnit'\n ], this);\n }\n\n getDefaultPosition() {\n return 'bottom-left';\n }\n\n _onMove() {\n updateScale(this._map, this._container, this.options);\n }\n\n onAdd(map: Map) {\n this._map = map;\n this._container = DOM.create('div', 'mapboxgl-ctrl mapboxgl-ctrl-scale', map.getContainer());\n\n this._map.on('move', this._onMove);\n this._onMove();\n\n return this._container;\n }\n\n onRemove() {\n DOM.remove(this._container);\n this._map.off('move', this._onMove);\n this._map = (undefined: any);\n }\n\n /**\n * Set the scale's unit of the distance\n *\n * @param unit Unit of the distance (`'imperial'`, `'metric'` or `'nautical'`).\n */\n setUnit(unit: Unit) {\n this.options.unit = unit;\n updateScale(this._map, this._container, this.options);\n }\n}\n\nexport default ScaleControl;\n\nfunction updateScale(map, container, options) {\n // A horizontal scale is imagined to be present at center of the map\n // container with maximum length (Default) as 100px.\n // Using spherical law of cosines approximation, the real distance is\n // found between the two coordinates.\n const maxWidth = options && options.maxWidth || 100;\n\n const y = map._container.clientHeight / 2;\n const left = map.unproject([0, y]);\n const right = map.unproject([maxWidth, y]);\n const maxMeters = left.distanceTo(right);\n // The real distance corresponding to 100px scale length is rounded off to\n // near pretty number and the scale length for the same is found out.\n // Default unit of the scale is based on User's locale.\n if (options && options.unit === 'imperial') {\n const maxFeet = 3.2808 * maxMeters;\n if (maxFeet > 5280) {\n const maxMiles = maxFeet / 5280;\n setScale(container, maxWidth, maxMiles, map._getUIString('ScaleControl.Miles'));\n } else {\n setScale(container, maxWidth, maxFeet, map._getUIString('ScaleControl.Feet'));\n }\n } else if (options && options.unit === 'nautical') {\n const maxNauticals = maxMeters / 1852;\n setScale(container, maxWidth, maxNauticals, map._getUIString('ScaleControl.NauticalMiles'));\n } else if (maxMeters >= 1000) {\n setScale(container, maxWidth, maxMeters / 1000, map._getUIString('ScaleControl.Kilometers'));\n } else {\n setScale(container, maxWidth, maxMeters, map._getUIString('ScaleControl.Meters'));\n }\n}\n\nfunction setScale(container, maxWidth, maxDistance, unit) {\n const distance = getRoundNum(maxDistance);\n const ratio = distance / maxDistance;\n container.style.width = `${maxWidth * ratio}px`;\n container.innerHTML = `${distance} ${unit}`;\n}\n\nfunction getDecimalRoundNum(d) {\n const multiplier = Math.pow(10, Math.ceil(-Math.log(d) / Math.LN10));\n return Math.round(d * multiplier) / multiplier;\n}\n\nfunction getRoundNum(num) {\n const pow10 = Math.pow(10, (`${Math.floor(num)}`).length - 1);\n let d = num / pow10;\n\n d = d >= 10 ? 10 :\n d >= 5 ? 5 :\n d >= 3 ? 3 :\n d >= 2 ? 2 :\n d >= 1 ? 1 : getDecimalRoundNum(d);\n\n return pow10 * d;\n}\n","// @flow\n\nimport DOM from '../../util/dom';\n\nimport {bindAll, warnOnce} from '../../util/util';\nimport window from '../../util/window';\n\nimport type Map from '../map';\n\ntype Options = {\n container?: HTMLElement\n};\n\n/**\n * A `FullscreenControl` control contains a button for toggling the map in and out of fullscreen mode.\n *\n * @implements {IControl}\n * @param {Object} [options]\n * @param {HTMLElement} [options.container] `container` is the [compatible DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element/requestFullScreen#Compatible_elements) which should be made full screen. By default, the map container element will be made full screen.\n *\n * @example\n * map.addControl(new mapboxgl.FullscreenControl({container: document.querySelector('body')}));\n * @see [View a fullscreen map](https://www.mapbox.com/mapbox-gl-js/example/fullscreen/)\n */\n\nclass FullscreenControl {\n _map: Map;\n _controlContainer: HTMLElement;\n _fullscreen: boolean;\n _fullscreenchange: string;\n _fullscreenButton: HTMLElement;\n _container: HTMLElement;\n\n constructor(options: Options) {\n this._fullscreen = false;\n if (options && options.container) {\n if (options.container instanceof window.HTMLElement) {\n this._container = options.container;\n } else {\n warnOnce('Full screen control \\'container\\' must be a DOM element.');\n }\n }\n bindAll([\n '_onClickFullscreen',\n '_changeIcon'\n ], this);\n if ('onfullscreenchange' in window.document) {\n this._fullscreenchange = 'fullscreenchange';\n } else if ('onmozfullscreenchange' in window.document) {\n this._fullscreenchange = 'mozfullscreenchange';\n } else if ('onwebkitfullscreenchange' in window.document) {\n this._fullscreenchange = 'webkitfullscreenchange';\n } else if ('onmsfullscreenchange' in window.document) {\n this._fullscreenchange = 'MSFullscreenChange';\n }\n }\n\n onAdd(map: Map) {\n this._map = map;\n if (!this._container) this._container = this._map.getContainer();\n this._controlContainer = DOM.create('div', `mapboxgl-ctrl mapboxgl-ctrl-group`);\n if (this._checkFullscreenSupport()) {\n this._setupUI();\n } else {\n this._controlContainer.style.display = 'none';\n warnOnce('This device does not support fullscreen mode.');\n }\n return this._controlContainer;\n }\n\n onRemove() {\n DOM.remove(this._controlContainer);\n this._map = (null: any);\n window.document.removeEventListener(this._fullscreenchange, this._changeIcon);\n }\n\n _checkFullscreenSupport() {\n return !!(\n window.document.fullscreenEnabled ||\n (window.document: any).mozFullScreenEnabled ||\n (window.document: any).msFullscreenEnabled ||\n (window.document: any).webkitFullscreenEnabled\n );\n }\n\n _setupUI() {\n const button = this._fullscreenButton = DOM.create('button', (`mapboxgl-ctrl-fullscreen`), this._controlContainer);\n DOM.create('span', `mapboxgl-ctrl-icon`, button).setAttribute('aria-hidden', true);\n button.type = 'button';\n this._updateTitle();\n this._fullscreenButton.addEventListener('click', this._onClickFullscreen);\n window.document.addEventListener(this._fullscreenchange, this._changeIcon);\n }\n\n _updateTitle() {\n const title = this._getTitle();\n this._fullscreenButton.setAttribute(\"aria-label\", title);\n this._fullscreenButton.title = title;\n }\n\n _getTitle() {\n return this._map._getUIString(this._isFullscreen() ? 'FullscreenControl.Exit' : 'FullscreenControl.Enter');\n }\n\n _isFullscreen() {\n return this._fullscreen;\n }\n\n _changeIcon() {\n const fullscreenElement =\n window.document.fullscreenElement ||\n (window.document: any).mozFullScreenElement ||\n (window.document: any).webkitFullscreenElement ||\n (window.document: any).msFullscreenElement;\n\n if ((fullscreenElement === this._container) !== this._fullscreen) {\n this._fullscreen = !this._fullscreen;\n this._fullscreenButton.classList.toggle(`mapboxgl-ctrl-shrink`);\n this._fullscreenButton.classList.toggle(`mapboxgl-ctrl-fullscreen`);\n this._updateTitle();\n }\n }\n\n _onClickFullscreen() {\n if (this._isFullscreen()) {\n if (window.document.exitFullscreen) {\n (window.document: any).exitFullscreen();\n } else if (window.document.mozCancelFullScreen) {\n (window.document: any).mozCancelFullScreen();\n } else if (window.document.msExitFullscreen) {\n (window.document: any).msExitFullscreen();\n } else if (window.document.webkitCancelFullScreen) {\n (window.document: any).webkitCancelFullScreen();\n }\n } else if (this._container.requestFullscreen) {\n this._container.requestFullscreen();\n } else if ((this._container: any).mozRequestFullScreen) {\n (this._container: any).mozRequestFullScreen();\n } else if ((this._container: any).msRequestFullscreen) {\n (this._container: any).msRequestFullscreen();\n } else if ((this._container: any).webkitRequestFullscreen) {\n (this._container: any).webkitRequestFullscreen();\n }\n }\n}\n\nexport default FullscreenControl;\n","// @flow\n\nimport {extend, bindAll} from '../util/util';\nimport {Event, Evented} from '../util/evented';\nimport {MapMouseEvent} from '../ui/events';\nimport DOM from '../util/dom';\nimport LngLat from '../geo/lng_lat';\nimport Point from '@mapbox/point-geometry';\nimport window from '../util/window';\nimport smartWrap from '../util/smart_wrap';\nimport {type Anchor, anchorTranslate, applyAnchorClass} from './anchor';\n\nimport type Map from './map';\nimport type {LngLatLike} from '../geo/lng_lat';\nimport type {PointLike} from '@mapbox/point-geometry';\n\nconst defaultOptions = {\n closeButton: true,\n closeOnClick: true,\n focusAfterOpen: true,\n className: '',\n maxWidth: \"240px\"\n};\n\nexport type Offset = number | PointLike | {[_: Anchor]: PointLike};\n\nexport type PopupOptions = {\n closeButton?: boolean,\n closeOnClick?: boolean,\n closeOnMove?: boolean,\n focusAfterOpen?: boolean,\n anchor?: Anchor,\n offset?: Offset,\n className?: string,\n maxWidth?: string\n};\n\nconst focusQuerySelector = [\n \"a[href]\",\n \"[tabindex]:not([tabindex='-1'])\",\n \"[contenteditable]:not([contenteditable='false'])\",\n \"button:not([disabled])\",\n \"input:not([disabled])\",\n \"select:not([disabled])\",\n \"textarea:not([disabled])\",\n].join(\", \");\n\n/**\n * A popup component.\n *\n * @param {Object} [options]\n * @param {boolean} [options.closeButton=true] If `true`, a close button will appear in the\n * top right corner of the popup.\n * @param {boolean} [options.closeOnClick=true] If `true`, the popup will closed when the\n * map is clicked.\n * @param {boolean} [options.closeOnMove=false] If `true`, the popup will closed when the\n * map moves.\n * @param {boolean} [options.focusAfterOpen=true] If `true`, the popup will try to focus the\n * first focusable element inside the popup.\n * @param {string} [options.anchor] - A string indicating the part of the Popup that should\n * be positioned closest to the coordinate set via {@link Popup#setLngLat}.\n * Options are `'center'`, `'top'`, `'bottom'`, `'left'`, `'right'`, `'top-left'`,\n * `'top-right'`, `'bottom-left'`, and `'bottom-right'`. If unset the anchor will be\n * dynamically set to ensure the popup falls within the map container with a preference\n * for `'bottom'`.\n * @param {number|PointLike|Object} [options.offset] -\n * A pixel offset applied to the popup's location specified as:\n * - a single number specifying a distance from the popup's location\n * - a {@link PointLike} specifying a constant offset\n * - an object of {@link Point}s specifing an offset for each anchor position\n * Negative offsets indicate left and up.\n * @param {string} [options.className] Space-separated CSS class names to add to popup container\n * @param {string} [options.maxWidth='240px'] -\n * A string that sets the CSS property of the popup's maximum width, eg `'300px'`.\n * To ensure the popup resizes to fit its content, set this property to `'none'`.\n * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width\n * @example\n * var markerHeight = 50, markerRadius = 10, linearOffset = 25;\n * var popupOffsets = {\n * 'top': [0, 0],\n * 'top-left': [0,0],\n * 'top-right': [0,0],\n * 'bottom': [0, -markerHeight],\n * 'bottom-left': [linearOffset, (markerHeight - markerRadius + linearOffset) * -1],\n * 'bottom-right': [-linearOffset, (markerHeight - markerRadius + linearOffset) * -1],\n * 'left': [markerRadius, (markerHeight - markerRadius) * -1],\n * 'right': [-markerRadius, (markerHeight - markerRadius) * -1]\n * };\n * var popup = new mapboxgl.Popup({offset: popupOffsets, className: 'my-class'})\n * .setLngLat(e.lngLat)\n * .setHTML(\"

Hello World!

\")\n * .setMaxWidth(\"300px\")\n * .addTo(map);\n * @see [Display a popup](https://www.mapbox.com/mapbox-gl-js/example/popup/)\n * @see [Display a popup on hover](https://www.mapbox.com/mapbox-gl-js/example/popup-on-hover/)\n * @see [Display a popup on click](https://www.mapbox.com/mapbox-gl-js/example/popup-on-click/)\n * @see [Attach a popup to a marker instance](https://www.mapbox.com/mapbox-gl-js/example/set-popup/)\n */\nexport default class Popup extends Evented {\n _map: Map;\n options: PopupOptions;\n _content: HTMLElement;\n _container: HTMLElement;\n _closeButton: HTMLElement;\n _tip: HTMLElement;\n _lngLat: LngLat;\n _trackPointer: boolean;\n _pos: ?Point;\n\n constructor(options: PopupOptions) {\n super();\n this.options = extend(Object.create(defaultOptions), options);\n bindAll(['_update', '_onClose', 'remove', '_onMouseMove', '_onMouseUp', '_onDrag'], this);\n }\n\n /**\n * Adds the popup to a map.\n *\n * @param {Map} map The Mapbox GL JS map to add the popup to.\n * @returns {Popup} `this`\n * @example\n * new mapboxgl.Popup()\n * .setLngLat([0, 0])\n * .setHTML(\"

Null Island

\")\n * .addTo(map);\n * @see [Display a popup](https://docs.mapbox.com/mapbox-gl-js/example/popup/)\n * @see [Display a popup on hover](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-hover/)\n * @see [Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/)\n * @see [Show polygon information on click](https://docs.mapbox.com/mapbox-gl-js/example/polygon-popup-on-click/)\n */\n addTo(map: Map) {\n if (this._map) this.remove();\n\n this._map = map;\n if (this.options.closeOnClick) {\n this._map.on('click', this._onClose);\n }\n\n if (this.options.closeOnMove) {\n this._map.on('move', this._onClose);\n }\n\n this._map.on('remove', this.remove);\n this._update();\n this._focusFirstElement();\n\n if (this._trackPointer) {\n this._map.on('mousemove', this._onMouseMove);\n this._map.on('mouseup', this._onMouseUp);\n if (this._container) {\n this._container.classList.add('mapboxgl-popup-track-pointer');\n }\n this._map._canvasContainer.classList.add('mapboxgl-track-pointer');\n } else {\n this._map.on('move', this._update);\n }\n\n /**\n * Fired when the popup is opened manually or programatically.\n *\n * @event open\n * @memberof Popup\n * @instance\n * @type {Object}\n * @property {Popup} popup object that was opened\n *\n * @example\n * // Create a popup\n * var popup = new mapboxgl.Popup();\n * // Set an event listener that will fire\n * // any time the popup is opened\n * popup.on('open', function(){\n * console.log('popup was opened');\n * });\n *\n */\n this.fire(new Event('open'));\n\n return this;\n }\n\n /**\n * @returns {boolean} `true` if the popup is open, `false` if it is closed.\n */\n isOpen() {\n return !!this._map;\n }\n\n /**\n * Removes the popup from the map it has been added to.\n *\n * @example\n * var popup = new mapboxgl.Popup().addTo(map);\n * popup.remove();\n * @returns {Popup} `this`\n */\n remove() {\n if (this._content) {\n DOM.remove(this._content);\n }\n\n if (this._container) {\n DOM.remove(this._container);\n delete this._container;\n }\n\n if (this._map) {\n this._map.off('move', this._update);\n this._map.off('move', this._onClose);\n this._map.off('click', this._onClose);\n this._map.off('remove', this.remove);\n this._map.off('mousemove', this._onMouseMove);\n this._map.off('mouseup', this._onMouseUp);\n this._map.off('drag', this._onDrag);\n delete this._map;\n }\n\n /**\n * Fired when the popup is closed manually or programatically.\n *\n * @event close\n * @memberof Popup\n * @instance\n * @type {Object}\n * @property {Popup} popup object that was closed\n *\n * @example\n * // Create a popup\n * var popup = new mapboxgl.Popup();\n * // Set an event listener that will fire\n * // any time the popup is closed\n * popup.on('close', function(){\n * console.log('popup was closed');\n * });\n *\n */\n this.fire(new Event('close'));\n\n return this;\n }\n\n /**\n * Returns the geographical location of the popup's anchor.\n *\n * The longitude of the result may differ by a multiple of 360 degrees from the longitude previously\n * set by `setLngLat` because `Popup` wraps the anchor longitude across copies of the world to keep\n * the popup on screen.\n *\n * @returns {LngLat} The geographical location of the popup's anchor.\n */\n getLngLat() {\n return this._lngLat;\n }\n\n /**\n * Sets the geographical location of the popup's anchor, and moves the popup to it. Replaces trackPointer() behavior.\n *\n * @param lnglat The geographical location to set as the popup's anchor.\n * @returns {Popup} `this`\n */\n setLngLat(lnglat: LngLatLike) {\n this._lngLat = LngLat.convert(lnglat);\n this._pos = null;\n\n this._trackPointer = false;\n\n this._update();\n\n if (this._map) {\n this._map.on('move', this._update);\n this._map.off('mousemove', this._onMouseMove);\n if (this._container) {\n this._container.classList.remove('mapboxgl-popup-track-pointer');\n }\n this._map._canvasContainer.classList.remove('mapboxgl-track-pointer');\n }\n\n return this;\n }\n\n /**\n * Tracks the popup anchor to the cursor position on screens with a pointer device (it will be hidden on touchscreens). Replaces the `setLngLat` behavior.\n * For most use cases, set `closeOnClick` and `closeButton` to `false`.\n * @example\n * var popup = new mapboxgl.Popup({ closeOnClick: false, closeButton: false })\n * .setHTML(\"

Hello World!

\")\n * .trackPointer()\n * .addTo(map);\n * @returns {Popup} `this`\n */\n trackPointer() {\n this._trackPointer = true;\n this._pos = null;\n this._update();\n if (this._map) {\n this._map.off('move', this._update);\n this._map.on('mousemove', this._onMouseMove);\n this._map.on('drag', this._onDrag);\n if (this._container) {\n this._container.classList.add('mapboxgl-popup-track-pointer');\n }\n this._map._canvasContainer.classList.add('mapboxgl-track-pointer');\n }\n\n return this;\n\n }\n\n /**\n * Returns the `Popup`'s HTML element.\n * @example\n * // Change the `Popup` element's font size\n * var popup = new mapboxgl.Popup()\n * .setLngLat([-96, 37.8])\n * .setHTML(\"

Hello World!

\")\n * .addTo(map);\n * var popupElem = popup.getElement();\n * popupElem.style.fontSize = \"25px\";\n * @returns {HTMLElement} element\n */\n getElement() {\n return this._container;\n }\n\n /**\n * Sets the popup's content to a string of text.\n *\n * This function creates a [Text](https://developer.mozilla.org/en-US/docs/Web/API/Text) node in the DOM,\n * so it cannot insert raw HTML. Use this method for security against XSS\n * if the popup content is user-provided.\n *\n * @param text Textual content for the popup.\n * @returns {Popup} `this`\n * @example\n * var popup = new mapboxgl.Popup()\n * .setLngLat(e.lngLat)\n * .setText('Hello, world!')\n * .addTo(map);\n */\n setText(text: string) {\n return this.setDOMContent(window.document.createTextNode(text));\n }\n\n /**\n * Sets the popup's content to the HTML provided as a string.\n *\n * This method does not perform HTML filtering or sanitization, and must be\n * used only with trusted content. Consider {@link Popup#setText} if\n * the content is an untrusted text string.\n *\n * @param html A string representing HTML content for the popup.\n * @returns {Popup} `this`\n * @example\n * var popup = new mapboxgl.Popup()\n * .setLngLat(e.lngLat)\n * .setHTML(\"

Hello World!

\")\n * .addTo(map);\n * @see [Display a popup](https://docs.mapbox.com/mapbox-gl-js/example/popup/)\n * @see [Display a popup on hover](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-hover/)\n * @see [Display a popup on click](https://docs.mapbox.com/mapbox-gl-js/example/popup-on-click/)\n * @see [Attach a popup to a marker instance](https://docs.mapbox.com/mapbox-gl-js/example/set-popup/)\n */\n setHTML(html: string) {\n const frag = window.document.createDocumentFragment();\n const temp = window.document.createElement('body');\n let child;\n temp.innerHTML = html;\n while (true) {\n child = temp.firstChild;\n if (!child) break;\n frag.appendChild(child);\n }\n\n return this.setDOMContent(frag);\n }\n\n /**\n * Returns the popup's maximum width.\n *\n * @returns {string} The maximum width of the popup.\n */\n getMaxWidth() {\n return this._container && this._container.style.maxWidth;\n }\n\n /**\n * Sets the popup's maximum width. This is setting the CSS property `max-width`.\n * Available values can be found here: https://developer.mozilla.org/en-US/docs/Web/CSS/max-width\n *\n * @param maxWidth A string representing the value for the maximum width.\n * @returns {Popup} `this`\n */\n setMaxWidth(maxWidth: string) {\n this.options.maxWidth = maxWidth;\n this._update();\n return this;\n }\n\n /**\n * Sets the popup's content to the element provided as a DOM node.\n *\n * @param htmlNode A DOM node to be used as content for the popup.\n * @returns {Popup} `this`\n * @example\n * // create an element with the popup content\n * var div = window.document.createElement('div');\n * div.innerHTML = 'Hello, world!';\n * var popup = new mapboxgl.Popup()\n * .setLngLat(e.lngLat)\n * .setDOMContent(div)\n * .addTo(map);\n */\n setDOMContent(htmlNode: Node) {\n if (this._content) {\n // Clear out children first.\n while (this._content.hasChildNodes()) {\n if (this._content.firstChild) {\n this._content.removeChild(this._content.firstChild);\n }\n }\n } else {\n this._content = DOM.create('div', 'mapboxgl-popup-content', this._container);\n }\n\n // The close button should be the last tabbable element inside the popup for a good keyboard UX.\n this._content.appendChild(htmlNode);\n this._createCloseButton();\n this._update();\n this._focusFirstElement();\n return this;\n }\n\n /**\n * Adds a CSS class to the popup container element.\n *\n * @param {string} className Non-empty string with CSS class name to add to popup container\n *\n * @example\n * let popup = new mapboxgl.Popup()\n * popup.addClassName('some-class')\n */\n addClassName(className: string) {\n if (this._container) {\n this._container.classList.add(className);\n }\n }\n\n /**\n * Removes a CSS class from the popup container element.\n *\n * @param {string} className Non-empty string with CSS class name to remove from popup container\n *\n * @example\n * let popup = new mapboxgl.Popup()\n * popup.removeClassName('some-class')\n */\n removeClassName(className: string) {\n if (this._container) {\n this._container.classList.remove(className);\n }\n }\n\n /**\n * Sets the popup's offset.\n *\n * @param offset Sets the popup's offset.\n * @returns {Popup} `this`\n */\n setOffset (offset?: Offset) {\n this.options.offset = offset;\n this._update();\n return this;\n }\n\n /**\n * Add or remove the given CSS class on the popup container, depending on whether the container currently has that class.\n *\n * @param {string} className Non-empty string with CSS class name to add/remove\n *\n * @returns {boolean} if the class was removed return false, if class was added, then return true\n *\n * @example\n * let popup = new mapboxgl.Popup()\n * popup.toggleClassName('toggleClass')\n */\n toggleClassName(className: string) {\n if (this._container) {\n return this._container.classList.toggle(className);\n }\n }\n\n _createCloseButton() {\n if (this.options.closeButton) {\n this._closeButton = DOM.create('button', 'mapboxgl-popup-close-button', this._content);\n this._closeButton.type = 'button';\n this._closeButton.setAttribute('aria-label', 'Close popup');\n this._closeButton.innerHTML = '×';\n this._closeButton.addEventListener('click', this._onClose);\n }\n }\n\n _onMouseUp(event: MapMouseEvent) {\n this._update(event.point);\n }\n\n _onMouseMove(event: MapMouseEvent) {\n this._update(event.point);\n }\n\n _onDrag(event: MapMouseEvent) {\n this._update(event.point);\n }\n\n _update(cursor: ?PointLike) {\n const hasPosition = this._lngLat || this._trackPointer;\n\n if (!this._map || !hasPosition || !this._content) { return; }\n\n if (!this._container) {\n this._container = DOM.create('div', 'mapboxgl-popup', this._map.getContainer());\n this._tip = DOM.create('div', 'mapboxgl-popup-tip', this._container);\n this._container.appendChild(this._content);\n if (this.options.className) {\n this.options.className.split(' ').forEach(name =>\n this._container.classList.add(name));\n }\n\n if (this._trackPointer) {\n this._container.classList.add('mapboxgl-popup-track-pointer');\n }\n }\n\n if (this.options.maxWidth && this._container.style.maxWidth !== this.options.maxWidth) {\n this._container.style.maxWidth = this.options.maxWidth;\n }\n\n if (this._map.transform.renderWorldCopies && !this._trackPointer) {\n this._lngLat = smartWrap(this._lngLat, this._pos, this._map.transform);\n }\n\n if (this._trackPointer && !cursor) return;\n\n const pos = this._pos = this._trackPointer && cursor ? cursor : this._map.project(this._lngLat);\n\n let anchor: ?Anchor = this.options.anchor;\n const offset = normalizeOffset(this.options.offset);\n\n if (!anchor) {\n const width = this._container.offsetWidth;\n const height = this._container.offsetHeight;\n let anchorComponents;\n\n if (pos.y + offset.bottom.y < height) {\n anchorComponents = ['top'];\n } else if (pos.y > this._map.transform.height - height) {\n anchorComponents = ['bottom'];\n } else {\n anchorComponents = [];\n }\n\n if (pos.x < width / 2) {\n anchorComponents.push('left');\n } else if (pos.x > this._map.transform.width - width / 2) {\n anchorComponents.push('right');\n }\n\n if (anchorComponents.length === 0) {\n anchor = 'bottom';\n } else {\n anchor = (anchorComponents.join('-'): any);\n }\n }\n\n const offsetedPos = pos.add(offset[anchor]).round();\n DOM.setTransform(this._container, `${anchorTranslate[anchor]} translate(${offsetedPos.x}px,${offsetedPos.y}px)`);\n applyAnchorClass(this._container, anchor, 'popup');\n }\n\n _focusFirstElement() {\n if (!this.options.focusAfterOpen || !this._container) return;\n\n const firstFocusable = this._container.querySelector(focusQuerySelector);\n\n if (firstFocusable) firstFocusable.focus();\n }\n\n _onClose() {\n this.remove();\n }\n}\n\nfunction normalizeOffset(offset: ?Offset) {\n if (!offset) {\n return normalizeOffset(new Point(0, 0));\n\n } else if (typeof offset === 'number') {\n // input specifies a radius from which to calculate offsets at all positions\n const cornerOffset = Math.round(Math.sqrt(0.5 * Math.pow(offset, 2)));\n return {\n 'center': new Point(0, 0),\n 'top': new Point(0, offset),\n 'top-left': new Point(cornerOffset, cornerOffset),\n 'top-right': new Point(-cornerOffset, cornerOffset),\n 'bottom': new Point(0, -offset),\n 'bottom-left': new Point(cornerOffset, -cornerOffset),\n 'bottom-right': new Point(-cornerOffset, -cornerOffset),\n 'left': new Point(offset, 0),\n 'right': new Point(-offset, 0)\n };\n\n } else if (offset instanceof Point || Array.isArray(offset)) {\n // input specifies a single offset to be applied to all positions\n const convertedOffset = Point.convert(offset);\n return {\n 'center': convertedOffset,\n 'top': convertedOffset,\n 'top-left': convertedOffset,\n 'top-right': convertedOffset,\n 'bottom': convertedOffset,\n 'bottom-left': convertedOffset,\n 'bottom-right': convertedOffset,\n 'left': convertedOffset,\n 'right': convertedOffset\n };\n\n } else {\n // input specifies an offset per position\n return {\n 'center': Point.convert(offset['center'] || [0, 0]),\n 'top': Point.convert(offset['top'] || [0, 0]),\n 'top-left': Point.convert(offset['top-left'] || [0, 0]),\n 'top-right': Point.convert(offset['top-right'] || [0, 0]),\n 'bottom': Point.convert(offset['bottom'] || [0, 0]),\n 'bottom-left': Point.convert(offset['bottom-left'] || [0, 0]),\n 'bottom-right': Point.convert(offset['bottom-right'] || [0, 0]),\n 'left': Point.convert(offset['left'] || [0, 0]),\n 'right': Point.convert(offset['right'] || [0, 0])\n };\n }\n}\n","// @flow\n\nimport assert from 'assert';\nimport supported from '@mapbox/mapbox-gl-supported';\n\nimport {version} from '../package.json';\nimport Map from './ui/map';\nimport NavigationControl from './ui/control/navigation_control';\nimport GeolocateControl from './ui/control/geolocate_control';\nimport AttributionControl from './ui/control/attribution_control';\nimport ScaleControl from './ui/control/scale_control';\nimport FullscreenControl from './ui/control/fullscreen_control';\nimport Popup from './ui/popup';\nimport Marker from './ui/marker';\nimport Style from './style/style';\nimport LngLat from './geo/lng_lat';\nimport LngLatBounds from './geo/lng_lat_bounds';\nimport Point from '@mapbox/point-geometry';\nimport MercatorCoordinate from './geo/mercator_coordinate';\nimport {Evented} from './util/evented';\nimport config from './util/config';\nimport {Debug} from './util/debug';\nimport {isSafari} from './util/util';\nimport {setRTLTextPlugin, getRTLTextPluginStatus} from './source/rtl_text_plugin';\nimport WorkerPool from './util/worker_pool';\nimport {prewarm, clearPrewarmedResources} from './util/global_worker_pool';\nimport {clearTileCache} from './util/tile_request_cache';\nimport {PerformanceUtils} from './util/performance';\n\nconst exported = {\n version,\n supported,\n setRTLTextPlugin,\n getRTLTextPluginStatus,\n Map,\n NavigationControl,\n GeolocateControl,\n AttributionControl,\n ScaleControl,\n FullscreenControl,\n Popup,\n Marker,\n Style,\n LngLat,\n LngLatBounds,\n Point,\n MercatorCoordinate,\n Evented,\n config,\n /**\n * Initializes resources like WebWorkers that can be shared across maps to lower load\n * times in some situations. `mapboxgl.workerUrl` and `mapboxgl.workerCount`, if being\n * used, must be set before `prewarm()` is called to have an effect.\n *\n * By default, the lifecycle of these resources is managed automatically, and they are\n * lazily initialized when a Map is first created. By invoking `prewarm()`, these\n * resources will be created ahead of time, and will not be cleared when the last Map\n * is removed from the page. This allows them to be re-used by new Map instances that\n * are created later. They can be manually cleared by calling\n * `mapboxgl.clearPrewarmedResources()`. This is only necessary if your web page remains\n * active but stops using maps altogether.\n *\n * This is primarily useful when using GL-JS maps in a single page app, wherein a user\n * would navigate between various views that can cause Map instances to constantly be\n * created and destroyed.\n *\n * @function prewarm\n * @example\n * mapboxgl.prewarm()\n */\n prewarm,\n /**\n * Clears up resources that have previously been created by `mapboxgl.prewarm()`.\n * Note that this is typically not necessary. You should only call this function\n * if you expect the user of your app to not return to a Map view at any point\n * in your application.\n *\n * @function clearPrewarmedResources\n * @example\n * mapboxgl.clearPrewarmedResources()\n */\n clearPrewarmedResources,\n\n /**\n * Gets and sets the map's [access token](https://www.mapbox.com/help/define-access-token/).\n *\n * @var {string} accessToken\n * @returns {string} The currently set access token.\n * @example\n * mapboxgl.accessToken = myAccessToken;\n * @see [Display a map](https://www.mapbox.com/mapbox-gl-js/examples/)\n */\n get accessToken(): ?string {\n return config.ACCESS_TOKEN;\n },\n\n set accessToken(token: string) {\n config.ACCESS_TOKEN = token;\n },\n\n /**\n * Gets and sets the map's default API URL for requesting tiles, styles, sprites, and glyphs\n *\n * @var {string} baseApiUrl\n * @returns {string} The current base API URL.\n * @example\n * mapboxgl.baseApiUrl = 'https://api.mapbox.com';\n */\n get baseApiUrl(): ?string {\n return config.API_URL;\n },\n\n set baseApiUrl(url: string) {\n config.API_URL = url;\n },\n\n /**\n * Gets and sets the number of web workers instantiated on a page with GL JS maps.\n * By default, it is set to half the number of CPU cores (capped at 6).\n * Make sure to set this property before creating any map instances for it to have effect.\n *\n * @var {string} workerCount\n * @returns {number} Number of workers currently configured.\n * @example\n * mapboxgl.workerCount = 2;\n */\n get workerCount(): number {\n return WorkerPool.workerCount;\n },\n\n set workerCount(count: number) {\n WorkerPool.workerCount = count;\n },\n\n /**\n * Gets and sets the maximum number of images (raster tiles, sprites, icons) to load in parallel,\n * which affects performance in raster-heavy maps. 16 by default.\n *\n * @var {string} maxParallelImageRequests\n * @returns {number} Number of parallel requests currently configured.\n * @example\n * mapboxgl.maxParallelImageRequests = 10;\n */\n get maxParallelImageRequests(): number {\n return config.MAX_PARALLEL_IMAGE_REQUESTS;\n },\n\n set maxParallelImageRequests(numRequests: number) {\n config.MAX_PARALLEL_IMAGE_REQUESTS = numRequests;\n },\n\n /**\n * Clears browser storage used by this library. Using this method flushes the Mapbox tile\n * cache that is managed by this library. Tiles may still be cached by the browser\n * in some cases.\n *\n * This API is supported on browsers where the [`Cache` API](https://developer.mozilla.org/en-US/docs/Web/API/Cache)\n * is supported and enabled. This includes all major browsers when pages are served over\n * `https://`, except Internet Explorer and Edge Mobile.\n *\n * When called in unsupported browsers or environments (private or incognito mode), the\n * callback will be called with an error argument.\n *\n * @function clearStorage\n * @param {Function} callback Called with an error argument if there is an error.\n * @example\n * mapboxgl.clearStorage();\n */\n clearStorage(callback?: (err: ?Error) => void) {\n clearTileCache(callback);\n },\n\n workerUrl: ''\n};\n\n//This gets automatically stripped out in production builds.\nDebug.extend(exported, {isSafari, getPerformanceMetrics: PerformanceUtils.getPerformanceMetrics});\n\n/**\n * The version of Mapbox GL JS in use as specified in `package.json`,\n * `CHANGELOG.md`, and the GitHub release.\n *\n * @var {string} version\n */\n\n/**\n * Test whether the browser [supports Mapbox GL JS](https://www.mapbox.com/help/mapbox-browser-support/#mapbox-gl-js).\n *\n * @function supported\n * @param {Object} [options]\n * @param {boolean} [options.failIfMajorPerformanceCaveat=false] If `true`,\n * the function will return `false` if the performance of Mapbox GL JS would\n * be dramatically worse than expected (e.g. a software WebGL renderer would be used).\n * @return {boolean}\n * @example\n * // Show an alert if the browser does not support Mapbox GL\n * if (!mapboxgl.supported()) {\n * alert('Your browser does not support Mapbox GL');\n * }\n * @see [Check for browser support](https://www.mapbox.com/mapbox-gl-js/example/check-for-support/)\n */\n\n/**\n * Sets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text).\n * Necessary for supporting the Arabic and Hebrew languages, which are written right-to-left. Mapbox Studio loads this plugin by default.\n *\n * @function setRTLTextPlugin\n * @param {string} pluginURL URL pointing to the Mapbox RTL text plugin source.\n * @param {Function} callback Called with an error argument if there is an error.\n * @param {boolean} lazy If set to `true`, mapboxgl will defer loading the plugin until rtl text is encountered,\n * rtl text will then be rendered only after the plugin finishes loading.\n * @example\n * mapboxgl.setRTLTextPlugin('https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.0/mapbox-gl-rtl-text.js');\n * @see [Add support for right-to-left scripts](https://www.mapbox.com/mapbox-gl-js/example/mapbox-gl-rtl-text/)\n */\n\n/**\n * Gets the map's [RTL text plugin](https://www.mapbox.com/mapbox-gl-js/plugins/#mapbox-gl-rtl-text) status.\n * The status can be `unavailable` (i.e. not requested or removed), `loading`, `loaded` or `error`.\n * If the status is `loaded` and the plugin is requested again, an error will be thrown.\n *\n * @function getRTLTextPluginStatus\n * @example\n * const pluginStatus = mapboxgl.getRTLTextPluginStatus();\n */\n\nexport default exported;\n\n// canary assert: used to confirm that asserts have been removed from production build\nassert(true, 'canary assert');\n"],"names":["isSupported","options","notSupportedReason","window","document","Array","prototype","every","filter","forEach","indexOf","lastIndexOf","map","some","reduce","reduceRight","isArray","Function","bind","Object","keys","create","getPrototypeOf","getOwnPropertyNames","isSealed","isFrozen","isExtensible","getOwnPropertyDescriptor","defineProperty","defineProperties","seal","freeze","preventExtensions","JSON","supported","worker","blob","Blob","type","workerURL","URL","createObjectURL","Worker","e","terminate","revokeObjectURL","isWorkerSupported","ArrayBuffer","isView","const","canvas","createElement","width","height","context","getContext","imageData","getImageData","isCanvasGetImageDataSupported","undefined","isWebGLSupportedCache","failIfMajorPerformanceCaveat","gl","attributes","webGLContextAttributes","probablySupportsContext","supportsContext","getWebGLContext","shader","createShader","VERTEX_SHADER","isContextLost","shaderSource","compileShader","getShaderParameter","COMPILE_STATUS","isWebGLSupported","module","exports","mapboxgl","antialias","alpha","stencil","depth","UnitBezier","p1x","p1y","p2x","p2y","this","cx","bx","ax","cy","by","ay","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","deepEqual","length","let","key","MAX_SAFE_INTEGER","pow","bezier","ease","clamp","n","min","max","wrap","d","w","asyncAll","array","fn","callback","remaining","results","error","item","err","result","values","obj","push","extend","dest","sources","src","pick","properties","id","uniqueId","uuid","random","toString","replace","validateUuid","str","test","bindAll","fns","endsWith","string","suffix","mapObject","input","iterator","output","call","filterObject","warnOnceHistory","warnOnce","message","console","warn","isCounterClockwise","c","calculateSignedArea","ring","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","storage","setItem","removeItem","linkEl","reducedMotionQuery","now","performance","Date","raf","requestAnimationFrame","mozRequestAnimationFrame","webkitRequestAnimationFrame","msRequestAnimationFrame","cancel","cancelAnimationFrame","mozCancelAnimationFrame","webkitCancelAnimationFrame","msCancelAnimationFrame","exported","frame","img","padding","Error","drawImage","resolveURL","path","href","hardwareConcurrency","devicePixelRatio","prefersReducedMotion","matchMedia","matches","DOM","tagName","className","container","el","appendChild","namespaceURI","createElementNS","docStyle","documentElement","style","testProp","props","userSelect","selectProp","disableDrag","enableDrag","transformProp","setTransform","passiveSupported","get","addEventListener","removeEventListener","target","capture","suppressClick","preventDefault","stopPropagation","setTimeout","mousePos","rect","getBoundingClientRect","clientX","left","clientLeft","clientY","top","clientTop","touchPos","touches","points","mouseButton","InstallTrigger","button","ctrlKey","platform","toUpperCase","remove","node","parentNode","removeChild","glForTesting","webpImgTest","config","API_URL","EVENTS_URL","FEEDBACK_URL","REQUIRE_ACCESS_TOKEN","ACCESS_TOKEN","MAX_PARALLEL_IMAGE_REQUESTS","webpCheckComplete","webpImgTestOnloadComplete","testWebpTextureUpload","texture","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","deleteTexture","onload","onerror","SKU_ID","RequestManager","transformRequestFn","customAccessToken","_transformRequestFn","_customAccessToken","_createSkuToken","isMapboxURL","url","skuToken","sessionRandomizer","floor","join","createSkuToken","_skuToken","token","_skuTokenExpiresAt","tokenExpiresAt","_isSkuTokenExpired","transformRequest","normalizeStyleURL","accessToken","urlObject","parseUrl","_makeAPIURL","normalizeGlyphsURL","normalizeSourceURL","authority","params","normalizeSpriteURL","format","extension","formatUrl","normalizeTileURL","tileURL","tileSize","browser","webpSupported","getAccessToken","canonicalizeTileURL","removeAccessToken","canonicalizeTileset","tileJSON","sourceURL","canonical","tiles","isMapboxHTTPURL","help","apiUrlObject","protocol","splice","mapboxHTTPURLRe","urlRe","parts","split","parseAccessToken","parse","decodeURIComponent","atob","charCodeAt","slice","TelemetryEvent","anonId","eventData","queue","pendingRequest","getStorageKey","domain","u","tokenData","btoa","encodeURIComponent","String","fromCharCode","Number","telemEventKey","fetchEventData","isLocalStorageAvailable","storageKey","uuidKey","data","localStorage","getItem","saveEventData","stringify","processRequests","_","postEvent","timestamp","additionalPayload","eventsUrlObject","payload","event","created","toISOString","sdkIdentifier","skuId","userId","finalPayload","request","headers","Content-Type","body","postData","queueRequest","sharedCache","responseConstructorSupportsReadableStream","MapLoadEvent","super","success","postMapLoadEvent","tileUrls","mapId","accessTokenIsSet","usesMapboxTiles","shift","turnstileEvent_","postTurnstileEvent","lastSuccess","tokenU","dueForEvent","nextUpdate","lastUpdate","nextDate","daysElapsed","getDate","enabled.telemetry","mapLoadEvent_","cacheLimit","cacheCheckThreshold","cacheOpen","caches","open","stripQueryParameters","start","supportsOffscreenCanvas","globalEntryCounter","Infinity","cacheEntryPossiblyAdded","dispatcher","getActor","send","offscreenCanvasSupported","OffscreenCanvas","createImageBitmap","ResourceType","Unknown","Style","Source","Tile","Glyphs","SpriteImage","SpriteJSON","Image","AJAXError","status","name","constructor","getReferrer","referrer","location","parent","imageQueue","numImageRequests","makeRequest","requestParameters","fetch","Request","AbortController","hasOwnProperty","controller","method","credentials","signal","complete","aborted","cacheIgnoringSearch","set","validateOrFetch","cachedResponse","responseIsFresh","finishRequest","requestTime","then","response","ok","cacheableResponse","statusText","catch","code","arrayBuffer","json","text","Headers","v","toUTCString","getTime","Response","ReadableStream","prepareBody","clonedResponse","cache","put","cachePut","strippedURL","fresh","expires","isFresh","delete","cacheGet","abort","makeFetchRequest","actor","xhr","XMLHttpRequest","responseType","setRequestHeader","withCredentials","getResponseHeader","makeXMLHttpRequest","getJSON","getArrayBuffer","transparentPngUrl","getImage","accept","queued","cancelled","advanced","advanceImageRequestQueue","Uint8Array","imgBitmap","arrayBufferToImageBitmap","byteLength","arrayBufferToImage","_addEventListener","listener","listenerList","_removeEventListener","index","Event","ErrorEvent","Evented","on","_listeners","off","_oneTimeListeners","once","fire","listens","_eventedParent","_eventedParentData","setEventedParent","ValidationError","identifier","__line__","line","validateConstants","constants","inputs","unbundle","Boolean","valueOf","deepUnbundle","unbundledValue","ParsingError","Scope","bindings","concat","has","NullType","kind","NumberType","StringType","BooleanType","ColorType","ObjectType","ValueType","CollatorType","FormattedType","ResolvedImageType","itemType","N","valueMemberTypes","checkSubtype","expected","isValidType","provided","allowedTypes","isValidNativeType","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","css_str","iv","substr","op","ep","fname","pop","s","l","Color","r","g","rgba","parseCSSColor","toArray","Collator","caseSensitive","diacriticSensitive","locale","sensitivity","collator","Intl","usage","compare","lhs","rhs","resolvedLocale","resolvedOptions","FormattedSection","image","scale","fontStack","textColor","Formatted","sections","fromString","unformatted","isEmpty","section","factory","serialize","serialized","ResolvedImage","available","validateRGBA","isValue","mixed","typeOf","Literal","args","expectedType","evaluate","eachChild","outputDefined","RuntimeError","toJSON","types","number","boolean","object","Assertion","parsed","ctx","arg","FormatExpression","firstArg","nextTokenMayBeObject","font","lastExpression","content","evaluatedContent","ImageExpression","evaluatedImageName","availableImages","to-boolean","to-color","to-number","to-string","Coercion","parseColor","num","valueToString","child","geometryTypes","EvaluationContext","globals","feature","featureState","formattedSection","_parseColorCache","geometryType","geometry","canonicalID","cached","CompoundExpression","_evaluate","definition","definitions","availableOverloads","overloads","signature","signatureContext","ParsingContext","registry","parsedArgs","argParseFailed","errors","signatures","actualTypes","register","CollatorExpression","updateBBox","bbox","coord","boxWithinBox","bbox1","bbox2","getTileCoordinates","PI","log","tilesAtZoom","z","rayIntersect","pointWithinPolygon","point","rings","x1","y1","y2","inside","len2","pointWithinPolygons","polygons","twoSided","q1","q2","x3","y3","det1","det2","lineIntersectPolygon","polygon","v1","v2","lineStringWithinPolygon","lineStringWithinPolygons","getTilePolygon","coordinates","getTilePolygons","updatePoint","polyBBox","worldSize","halfWorldSize","getTilePoints","pointBBox","shifts","tilePoints","getTileLines","lineBBox","tileLines","tileLine","Within","geojson","geometries","isFeatureConstant","isStateConstant","isGlobalPropertyConstant","features","polygonGeometry","tilePolygon","tilePolygons","pointsWithinPolygons","linesWithinPolygons","Var","boundExpression","part","findStopLessThanOrEqualTo","stops","currentValue","lastIndex","lowerIndex","upperIndex","currentIndex","expr","_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","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","minimumFractionDigits","maximumFractionDigits","Length","expressions","==","!=",">","<",">=","<=","at","case","coalesce","in","index-of","interpolate-hcl","interpolate-lab","literal","number-format","step","var","within","varargs","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","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","featureFunctions","featureFunctionStops","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","deserialize","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","source","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","paintProperty","layoutProperty","validateStyle","emitValidationErrors","emitter","hasErrors","GridIndex","extent","cells","Int32Array","end","subarray","bboxesOffset","bboxes","insert","_insertReadonly","uid","_forEachCell","_insertCell","cellIndex","query","intersectionTest","_queryCell","seenUids","cell","offset","arg1","arg2","cx1","_convertToCellCoord","cy1","cx2","cy2","_convertFromCellCoord","toArrayBuffer","metadataLength","totalCellLength","buffer","klass","writeable","omit","shallow","Grid","grid","transferables","_classRegistryKey","isArrayBuffer","isImageBitmap","ImageBitmap","RegExp","view","ImageData","$name","ZoomHistory","first","update","floorZ","lastIntegerZoom","lastIntegerZoomTime","lastZoom","lastFloorZoom","unicodeBlockLookup","char","allowsVerticalWritingMode","chars","charHasUprightVerticalOrientation","isChar","charHasRotatedVerticalOrientation","charHasNeutralVerticalOrientation","charInRTLScript","charInSupportedScript","canRenderRTL","stringContainsRTLText","_completionCallback","pluginStatus","pluginURL","triggerPluginCompletionEvent","sendPluginStateToWorker","evented","getRTLTextPluginStatus","downloadRTLTextPlugin","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","sprite","is3D","isTileClipped","hasOffscreenPass","resize","viewTypes","Int8","Int8Array","Uint8","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","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","right","pivot","swap","numValue","arr","tmp","Uniform","Uniform1i","current","uniform1i","Uniform1f","uniform1f","Uniform2f","uniform2f","Uniform3f","uniform3f","Uniform4f","uniform4f","UniformColor","emptyMat4","UniformMatrix4f","uniformMatrix4fv","packColor","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","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","glMatrix","identity","invert","a00","a01","a02","a03","a10","a11","a12","a13","a20","a21","a22","a23","a30","a31","a32","a33","b00","b01","b02","b03","b04","b05","b06","b07","b08","b09","b10","b11","det","multiply","b2","b3","rotateZ","rad","ortho","bottom","near","far","lr","bt","nf","hypot","arguments","mul","transformMat4","sqrLen","CircleStyleLayer","createBucket","queryRadius","circleBucket","queryIntersectsFeature","transform","pixelPosMatrix","translatedPolygon","alignWithMap","transformedPolygon","projectPoint","projectQueryGeometry","transformedSize","transformedPoint","adjustedSize","projectedCenter","vec4","cameraToCenterDistance","HeatmapBucket","createImage","channels","Uint8ClampedArray","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","renderColorRamp","evaluationGlobals","resolution","clips","renderPixel","stride","evaluationKey","pxColor","clip","HeatmapStyleLayer","_updateColorRamp","colorRamp","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","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","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","collisionCircleLayout","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","readFontstacks","readMessage","readFontstack","readGlyph","bitmap","metrics","advance","glyph","readBytes","potpack","boxes","maxWidth","box","spaces","space","fill","readField","skip","readFixed32","readSFixed32","readFixed64","readSFixed64","ieee754","readVarintRemainder","decode","readUtf8TextDecoder","bytesPerSequence","readUtf8","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","position","WritingMode","horizontal","vertical","horizontalOnly","SectionOptions","imageName","forText","textOptions","forImage","imageOptions","TaggedString","sectionIndex","imageSectionID","fromFeature","defaultFontStack","addImageSection","addTextSection","getSection","getSectionIndex","getCharCode","verticalizePunctuation","nextCharCode","prevCharCode","trim","beginningWhitespace","whitespace","trailingWhitespace","substring","getMaxScale","nextImageSectionCharCode","getNextImageSectionCharCode","getAnchorAlignment","anchor","horizontalAlign","verticalAlign","getSizeData","tileZoom","minZoom","maxZoom","evaluateSizeForFeature","sizeData","uSize","evaluateSizeForZoom","uSizeT","layoutSize","minSize","Anchor","INVALID_TEXT_OFFSET","POSITIVE_INFINITY","evaluateVariableOffset","offsetX","offsetY","fromTextOffset","radialOffset","hypotenuse","fromRadialOffset","shaderOpacityAttributes","ox","oy","tx","ty","sizeVertex","isSDF","pixelOffsetX","pixelOffsetY","minFontScaleX","minFontScaleY","aSizeX","MAX_GLYPH_ICON_SIZE","aSizeY","addDynamicAttributes","dynamicLayoutVertexArray","containsRTLText","formattedText","SymbolBuffers","SymbolLayoutArray","SymbolDynamicLayoutArray","opacityVertexArray","SymbolOpacityArray","placedSymbolArray","dynamicIndexBuffer","dynamicLayoutVertexBuffer","opacityVertexBuffer","itemSize","CollisionBuffers","LayoutArray","IndexArray","collisionVertexArray","CollisionVertexArray","collisionVertexBuffer","SymbolBucket","collisionBoxArray","hasRTLText","sortKeyRanges","collisionCircleArray","placementInvProjMatrix","mat4","placementViewportMatrix","unevaluatedLayoutValues","textSizeData","iconSizeData","canOverlap","sortFeaturesByKey","sortFeaturesByY","writingModes","wm","sourceID","createArrays","icon","glyphOffsetArray","lineVertexArray","symbolInstances","calculateGlyphDependencies","stack","textAlongLine","allowVerticalPlacement","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","addToLineVertexArray","sumForwardLength","sumBackwardLength","tileUnitDistanceFromAnchor","vertex","addSymbols","arrays","quads","alongLine","labelAnchor","glyphOffsetArrayStart","glyphOffset","tex","pixelOffsetTL","tr","pixelOffsetBR","bl","_addCollisionDebugVertex","addCollisionDebugVertices","boxAnchorPoint","symbolInstance","addDebugCollisionBoxes","startIndex","isText","generateCollisionDebugBuffers","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","addToSortKeyRanges","symbolInstanceIndex","symbolInstanceEnd","symbolInstanceStart","sortFeatures","featureSortOrder","MAX_GLYPHS","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","Texture","renderStyleImage","userImage","render","useMipmap","pixelStoreUnpackFlipY","pixelStoreUnpack","pixelStoreUnpackPremultiplyAlpha","premultiply","HTMLImageElement","HTMLCanvasElement","HTMLVideoElement","texSubImage2D","isSizePowerOfTwo","generateMipmap","minFilter","LINEAR_MIPMAP_NEAREST","LINEAR","texParameteri","TEXTURE_MAG_FILTER","TEXTURE_MIN_FILTER","TEXTURE_WRAP_S","TEXTURE_WRAP_T","ImageManager","callbackDispatchedThisFrame","loaded","requestors","atlasImage","setLoaded","_notify","addImage","valid","_validateStretch","_validateContent","stretch","updateImage","removeImage","listImages","getImages","hasAllDependencies","sdf","getPixelSize","getPattern","pattern","_updatePatternAtlas","atlasTexture","CLAMP_TO_EDGE","dst","beginFrame","TinySDF","INF","fontSize","cutoff","fontFamily","fontWeight","textBaseline","fillStyle","gridOuter","gridInner","middle","edt","edt1d","draw","clearRect","fillText","imgData","alphaChannel","GlyphManager","requestManager","localIdeographFontFamily","entries","setURL","getGlyphs","entry","requests","ranges","_tinySDF","range","loadGlyphRange","_doesCharSupportLocalGlyph","cb","family","tinySDF","fontstack","urlTemplate","Protobuf","parseGlyphPBF","LightPositionProperty","azimuthal","polar","intensity","Light","lightOptions","_transitionable","setLight","_transitioning","getLight","LineAtlas","nextRow","dashEntry","getDash","dasharray","addDash","getDashRanges","lineAtlasWidth","isDash","zeroLength","currentDashLength","dashLength","addRoundDash","halfStretch","currIndex","distLeft","distRight","minDist","signedDistance","distMiddle","distEdge","addRegularDash","ALPHA","REPEAT","ThrottledInvoker","_callback","_triggered","MessageChannel","_channel","port2","onmessage","trigger","port1","postMessage","Actor","callbacks","tasks","taskQueue","cancelCallbacks","invoker","process","receive","globalScope","targetMapId","mustQueue","buffers","hasCallback","sourceMapId","processTask","task","completed","done","getWorkerSource","Dispatcher","workerPool","actors","currentActor","workers","acquire","getMercCoords","broadcast","release","LngLatBounds","sw","ne","setSouthWest","setNorthEast","_ne","LngLat","lng","lat","_sw","sw2","ne2","getCenter","getSouthWest","getNorthEast","getNorthWest","getWest","getNorth","getSouthEast","getEast","getSouth","contains","lnglat","containsLongitude","distanceTo","lngLat","lat1","lat2","toBounds","latAccuracy","lngAccuracy","lon","earthCircumfrence","circumferenceAtLatitude","latitude","mercatorXfromLng","mercatorYfromLat","mercatorZfromAltitude","altitude","latFromMercatorY","MercatorCoordinate","fromLngLat","lngLatLike","toLngLat","toAltitude","meterInMercatorCoordinateUnits","CanonicalTileID","calculateKey","urls","scheme","quadkey","mask","getQuadkey","getTilePoint","UnwrappedTileID","OverscaledTileID","overscaledZ","vector_layers","vectorLayers","vectorLayerIds","scaledTo","targetZ","zDifference","calculateScaledKey","withWrap","isChildOf","children","sourceMaxZoom","isLessThan","wrapped","unwrapTo","overscaleFactor","toUnwrapped","TileBounds","bounds","validateBounds","tileID","level","VectorTileSource","eventedParent","reparseOverscaled","_loaded","_options","_collectResourceTiming","collectResourceTiming","load","dataType","_tileJSONRequest","loadTileJSON","_requestManager","tileBounds","_getMapId","sourceDataType","hasTile","setSourceProperty","sourceCaches","clearTiles","setTiles","setUrl","loadTile","tile","showCollisionBoxes","resourceTiming","_refreshExpiredTiles","setExpiryData","loadVectorData","reloadCallback","abortTile","unloadTile","unloadVectorData","RasterTileSource","roundZoom","getTileTexture","extTextureFilterAnisotropic","texParameterf","TEXTURE_MAX_ANISOTROPY_EXT","extTextureFilterAnisotropicMax","saveTileTexture","DEMData","encoding","_idx","pixels","_unpackTerrarium","_unpackMapbox","getUnpackVector","getPixels","backfillBorder","borderTile","xMin","xMax","yMin","yMax","RasterDEMTileSource","dem","needsHillshadePrepare","rawImageData","neighboringTiles","_getNeighboringTiles","pxw","nxw","backfilled","demTexture","fbo","GeoJSONSource","_removed","_data","_resourceTiming","attribution","workerOptions","geojsonVtOptions","tolerance","generateId","superclusterOptions","clusterMaxZoom","minPoints","clusterMinPoints","clusterRadius","_updateWorkerData","setData","getClusterExpansionZoom","clusterId","getClusterChildren","getClusterLeaves","limit","abandoned","ImageSource","newCoordinates","successCallback","_finishLoading","setCoordinates","cornerCoords","dMax","getCoordinatesCenterTileID","tileCoords","_boundsArray","RasterBoundsArray","boundsBuffer","prepare","rasterBoundsAttributes","boundsSegments","buckets","VideoSource","video","muted","onloadstart","loop","setAttribute","triggerRepaint","play","host","crossOrigin","getVideo","pause","seek","seconds","seekableRange","seekable","currentTime","readyState","paused","CanvasSource","animate","getElementById","_hasInvalidDimensions","_playing","getCanvas","sourceTypes","vector","raster-dem","rasterDem","getPixelPosMatrix","calculatePosMatrix","queryRenderedFeatures","sourceCache","styleLayers","serializedLayers","has3DLayer","queryIncludes3DLayer","maxPitchScaleFactor","tilesIn","sortTilesIn","renderedFeatureLayers","tileIn","wrappedTileID","queryResults","_state","cameraQueryGeometry","wrappedIDLayerMap","wrappedID","wrappedIDLayers","layerID","tileFeatures","wrappedIDFeatures","resultFeatures","tileFeature","mergeRenderedFeatureLayers","featureWrapper","getFeatureState","idA","idB","DictionaryCoder","strings","_stringToNumber","_numberToString","encode","Feature","vectorTileFeature","_vectorTileFeature","_z","_x","_y","SourceFeatureState","stateChanges","deletedStates","updateState","featureId","newState","ft","removeFeatureState","getState","reconciledState","featureDeletions","initializeTileState","setFeatureState","coalesceChanges","featuresChanged","layerStates","FeatureIndex","grid3D","featureIndexArray","evaluateProperties","serializedProperties","styleLayerProperties","getBounds","topDownFeatureComparator","loadVTLayers","vtLayers","vt","VectorTile","rawTileData","sourceLayerCoder","sourceFeatureState","featureFilter","queryPadding","matching","cameraBounds","matching3D","bx1","by1","bx2","by2","boxX1","boxY1","boxX2","boxY2","polygonIntersectsBox","previousIndex","featureGeometry","loadMatchingFeature","filterLayerIDs","layerIDs","bucketLayerIDs","arraysIntersect","sourceLayerName","getId","serializedLayer","intersectionZ","geojsonFeature","GeoJSONFeature","layerResult","lookupSymbolFeatures","symbolFeatureIndexes","hasLayer","sourceLayerId","uses","expirationTime","hasSymbolBuckets","dependencies","expiredRequestCount","registerFadeDuration","fadeEndTime","timeAdded","wasRequested","justReloaded","hasData","latestFeatureIndex","latestRawTileData","getLayer","lId","deserializeBucket","imageAtlas","glyphAtlasImage","imageAtlasTexture","glyphAtlasTexture","getBucket","querySourceFeatures","_geojsonTileLayer","patternsLoaded","parsedCC","isExpired","delta","getExpiryTimeout","sourceLayerStates","holdingForFade","symbolFadeHoldUntil","symbolFadeFinished","clearFadeHold","setHoldDuration","setDependencies","namespace","hasDependency","namespaces","TileCache","reset","removedData","timeout","clearTimeout","order","expiryTimeout","dataWrapper","_getAndRemoveByKey","getAndRemove","getByKey","dataIndex","setMaxSize","filterFn","removed","IndexBuffer","dynamicDraw","createBuffer","unbindVAO","bindElementBuffer","bufferData","ELEMENT_ARRAY_BUFFER","DYNAMIC_DRAW","STATIC_DRAW","bufferSubData","deleteBuffer","AttributeType","VertexBuffer","bindVertexBuffer","ARRAY_BUFFER","enableAttributes","program","attribIndex","enableVertexAttribArray","setVertexAttribPointers","vertexAttribPointer","BaseValue","getDefault","setDefault","ClearColor","clearColor","ClearDepth","clearDepth","ClearStencil","clearStencil","ColorMask","colorMask","DepthMask","depthMask","StencilMask","stencilMask","StencilFunc","func","ALWAYS","stencilFunc","StencilOp","KEEP","stencilOp","StencilTest","enable","STENCIL_TEST","disable","DepthRange","depthRange","DepthTest","DEPTH_TEST","DepthFunc","LESS","depthFunc","Blend","BLEND","BlendFunc","ONE","ZERO","blendFunc","BlendColor","blendColor","BlendEquation","FUNC_ADD","blendEquation","CullFace","CULL_FACE","CullFaceSide","BACK","cullFace","FrontFace","CCW","frontFace","Program","useProgram","ActiveTextureUnit","TEXTURE0","activeTexture","Viewport","drawingBufferWidth","drawingBufferHeight","viewport","BindFramebuffer","bindFramebuffer","FRAMEBUFFER","BindRenderbuffer","bindRenderbuffer","RENDERBUFFER","BindTexture","BindVertexBuffer","bindBuffer","BindElementBuffer","BindVertexArrayOES","vao","extVertexArrayObject","bindVertexArrayOES","PixelStoreUnpack","pixelStorei","UNPACK_ALIGNMENT","PixelStoreUnpackPremultiplyAlpha","UNPACK_PREMULTIPLY_ALPHA_WEBGL","PixelStoreUnpackFlipY","UNPACK_FLIP_Y_WEBGL","FramebufferAttachment","ColorAttachment","setDirty","framebufferTexture2D","COLOR_ATTACHMENT0","DepthAttachment","framebufferRenderbuffer","DEPTH_ATTACHMENT","Framebuffer","hasDepth","framebuffer","createFramebuffer","colorAttachment","depthAttachment","renderbuffer","deleteRenderbuffer","deleteFramebuffer","DepthMode","ReadOnly","ReadWrite","disabled","StencilMode","fail","depthFail","ColorMode","blendFunction","Replace","unblended","alphaBlended","CullFaceMode","mode","backCCW","Context","getExtension","stencilTest","depthTest","blend","cullFaceSide","getParameter","MAX_TEXTURE_MAX_ANISOTROPY_EXT","extTextureHalfFloat","extRenderToTextureHalfFloat","extTimerQuery","maxTextureSize","MAX_TEXTURE_SIZE","createRenderbuffer","storageFormat","rbo","renderbufferStorage","COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","setCullFace","cullFaceMode","setDepthMode","depthMode","setStencilMode","stencilMode","setColorMode","colorMode","SourceCache","_sourceLoaded","_paused","reload","_sourceErrored","_source","createSource","_tiles","_cache","_unloadTile","_timers","_cacheTimers","_maxTileCacheSize","_loadedParentTiles","_coveredTiles","getSource","resume","shouldReload","_shouldReloadOnResume","_loadTile","_abortTile","getIds","compareTileId","getRenderableIds","symbolLayer","renderables","_isIdRenderable","a_","b_","rotatedA","rotatedB","hasRenderableParent","parentTile","findLoadedParent","_reloadTile","_tileLoaded","previousState","refreshedUponExpiration","_setTileReloadTimer","_backfillDEM","borderId","getTileByID","fillBorder","getTile","_retainLoadedChildren","idealTiles","maxCoveringZoom","retain","topmostLoadedID","parentID","minCoveringZoom","parentTileID","_getLoadedTile","updateCacheSize","widthInTiles","heightInTiles","viewDependentMaxSize","handleWrapJump","wrapDelta","_prevLng","idealTileIDs","center","used","getVisibleUnwrappedCoordinates","unwrapped","coveringTiles","coveringZoomLevel","maxOverzooming","maxUnderzooming","_updateRetainedTiles","isRasterType","parentsForFading","fadingTiles","_addTile","retainedId","keysDifference","_fadeDuration","_removeTile","_updateLoadedParentTileCache","releaseSymbolFadeTiles","checked","missingTiles","childCoord","childTile","parentWasRequested","parentId","tileKey","currentId","pointQueryGeometry","tileResults","cameraPointQueryGeometry","getCameraQueryGeometry","pointCoordinate","tileSpaceBounds","tileSpaceQueryGeometry","tileSpaceCameraQueryGeometry","getVisibleCoordinates","posMatrix","reloadTilesForDependencies","aWrap","bWrap","workerUrl","PRELOAD_POOL_ID","WorkerPool","active","workerCount","WebWorker","numActive","isPreloaded","globalWorkerPool","availableLogicalProcessors","getGlobalWorkerPool","deref","refProperties","derefLayers","operations","setStyle","addLayer","removeLayer","setFilter","addSource","removeSource","setGeoJSONSourceData","setLayerZoomRange","setLayerProperty","setCenter","setZoom","setBearing","setPitch","setSprite","setGlyphs","sourceId","after","commands","command","sourcesRemoved","updateSource","canUpdateGeoJSON","before","isEqual","diffLayerPropertyChanges","pluckId","indexById","group","PathInterpolator","points_","padding_","_distances","paddedLength","lerp","distOfCurrentIdx","distToTarget","idxOfPrevPoint","distOfPrevIdx","segmentLength","segmentT","cellSize","boxCells","circleCells","xCellCount","yCellCount","circleKeys","boxKeys","circles","xScale","yScale","boxUid","circleUid","getLabelPlaneMatrix","pitchWithMap","rotateWithMap","labelPlaneMatrix","getGlCoordMatrix","glCoordMatrix","matrix","xyTransformMat4","signedDistanceFromCamera","getPerspectiveRatio","isVisible","anchorPos","clippingBuffer","updateLineLabels","keepUpright","partiallyEvaluatedSize","symbolSize","placedSymbols","aspectRatio","useVertical","hideGlyphs","perspectiveRatio","pitchScaledFontSize","tileAnchorPoint","projectionCache","placeUnflipped","placeGlyphsAlongLine","notEnoughRoom","needsFlipping","placeFirstAndLastGlyph","fontScale","flip","glyphEndIndex","lineEndIndex","firstGlyphOffset","lastGlyphOffset","firstPlacedGlyph","placeGlyphAlongLine","lastPlacedGlyph","requiresOrientationChange","firstPoint","lastPoint","placedGlyphs","firstAndLastGlyph","orientationChange","glyphIndex","tileVertexIndex","tileSegmentEnd","projectedVertex","projectTruncatedLineSegment","singleGlyph","previousTilePoint","currentTilePoint","previousProjectedPoint","minimumLength","projectionMatrix","projectedUnitVertex","projectedUnitSegment","anchorSegment","combinedOffsetX","distanceToPrev","currentSegmentDistance","absOffsetX","pathVertices","projection","previousLineVertexIndex","segmentInterpolationT","prevToCurrent","segmentAngle","keysLength","_insertBoxCell","insertCircle","_insertCircleCell","_query","hitTest","predicate","_queryCircle","_queryCellCircle","hitTestCircle","queryArgs","boxCell","circleCell","_circleAndRectCollide","_circlesCollide","_convertToXCellCoord","_convertToYCellCoord","r1","r2","bothRadii","circleX","circleY","halfRectWidth","distX","halfRectHeight","distY","hiddenGlyphAttributes","CollisionIndex","ignoredGrid","pitchfactor","_pitch","screenRightBoundary","screenBottomBoundary","gridRightBoundary","gridBottomBoundary","pixelValue","placeCollisionBox","collisionBox","allowOverlap","textPixelRatio","collisionGroupPredicate","projectedPoint","projectAndGetPerspectiveRatio","tileToViewport","tlX","tlY","brX","brY","isInsideGrid","offscreen","isOffscreen","placeCollisionCircles","labelToScreenMatrix","showCollisionCircles","circlePixelDiameter","textPixelPadding","placedCollisionCircles","tileUnitAnchorPoint","screenAnchorPoint","labelPlaneFontScale","labelPlaneAnchorPoint","collisionDetected","inGrid","entirelyOffscreen","screenPlaneMin","screenPlaneMax","interpolator","projectedPath","circleDist","screenSpacePath","minPoint","maxPoint","clippedLines","clippedLine","p0","clipLine","numCircles","circlePosition","centerX","centerY","queryRenderedSymbols","viewportQueryGeometry","gridPoint","seenFeatures","featureKey","bucketInstanceId","intersectionTests","insertCollisionBox","ignorePlacement","collisionGroupID","insertCollisionCircles","collisionCircles","getViewportMatrix","OpacityState","prevState","increment","placed","skipFade","opacity","JointOpacityState","placedText","placedIcon","JointPlacement","CollisionCircleArray","invProjMatrix","viewportMatrix","RetainedQueryData","CollisionGroups","crossSourceCollisions","maxGroupID","collisionGroups","calculateVariableLayoutShift","textOffset","shiftX","shiftY","shiftVariableCollisionBox","rotatedOffset","ID","nextGroupID","Placement","prevPlacement","collisionIndex","placements","opacities","variableOffsets","stale","commitTime","retainedQueryData","collisionCircleArrays","placedOrientations","updateCollisionVertices","notUsed","getBucketParts","sortAcrossTiles","symbolBucket","bucketFeatureIndex","pixelsToTiles","textLabelPlaneMatrix","partiallyEvaluatedTextSize","collisionGroup","attemptAnchorPlacement","textAllowOverlap","orientation","prevAnchor","placedGlyphBoxes","markUsedJustification","markUsedOrientation","placeLayerBucketPart","bucketPart","seenCrossTileIDs","textOptional","iconOptional","iconAllowOverlap","hasIconTextFit","zOrderByViewportY","alwaysShowText","alwaysShowIcon","placeSymbol","placeText","placeIcon","placedVerticalText","placedGlyphCircles","placedIconBoxes","updatePreviousOrientationIfNotPlaced","isPlaced","previousOrientation","prevPlacedOrientation","placeTextForPlacementModes","placeHorizontalFn","placeVerticalFn","anchors","prevOffsets","unshift","placeBoxForVariableAnchors","collisionTextBox","collisionIconBox","variableIconBox","placedBox","placementAttempts","prevOrientation","prevOffset","placeBox","placedFeature","placeIconFeature","shiftedIconBox","iconWithoutText","textWithoutIcon","circleArray","symbolIndexes","symbolIndex","placedAnchor","autoIndex","getAnchorJustification","commit","zoomAtLastRecencyCheck","placementChanged","prevZoomAdjustment","zoomAdjustment","symbolFadeChange","prevOpacities","prevOrientations","jointPlacement","prevOpacity","jointOpacity","lastPlacementChangeTime","updateLayerOpacities","updateBucketOpacities","duplicateOpacityState","variablePlacement","defaultOpacityState","addOpacities","opacityState","horizontalHidden","verticalHidden","packedOpacity","packOpacity","PACKED_HIDDEN_OPACITY","symbolHidden","useHorizontal","variableOffset","verticalIconUsed","instance","hasTransitions","stillRecent","durationAdjustment","setStale","shift25","shift24","shift17","shift16","shift9","shift8","shift1","targetBit","opacityBits","LayerPlacement","_sortAcrossTiles","_currentTileIndex","_currentPartIndex","_seenCrossTileIDs","_bucketParts","continuePlacement","placement","shouldPausePlacement","bucketParts","PauseablePlacement","forceFullPlacement","_currentPlacementIndex","_forceFullPlacement","_showCollisionBoxes","_done","isDone","layerTiles","startTime","elapsedTime","placementZoom","_inProgressLayer","TileLayerIndex","indexedSymbolInstances","getScaledCoordinates","childTileID","findMatches","newTileID","zoomCrossTileIDs","indexedInstances","scaledSymbolCoord","thisTileSymbol","CrossTileIDs","maxCrossTileID","generate","CrossTileSymbolLayerIndex","indexes","usedCrossTileIDs","zoomIndexes","newZoomIndex","addBucket","crossTileIDs","removeBucketCrossTileIDs","childIndex","parentIndex","removedBucket","removeStaleBuckets","currentIDs","tilesChanged","CrossTileSymbolIndex","layerIndexes","maxBucketInstanceId","bucketsInCurrentPlacement","layerIndex","symbolBucketsChanged","currentBucketIDs","pruneUnusedLayers","usedLayers","usedLayerMap","usedLayer","_emitValidationErrors","supportedDiffOperations","diffOperations","ignoredDiffOperations","empty","latest","styleKey","emptyStyle","getWorkerPool","glyphManager","lineAtlas","crossTileSymbolIndex","_layers","_serializedLayers","_order","_availableImages","_resetUpdates","_rtlTextPluginCallback","registerForPluginStateChange","elem","_validateLayer","loadURL","_request","_load","loadJSON","loadEmpty","stylesheet","_loadSprite","_serializeLayers","_spriteRequest","baseURL","jsonRequest","maybeComplete","imageRequest","loadSprite","_updatedSources","_checkLoaded","changed","_changed","updatedIds","_updatedLayers","removedIds","_removedLayers","_updateWorkerLayers","action","_reloadSource","_clearSource","_updateTilesForChangedImages","_updatedPaintProps","sourcesUsedBefore","changedImages","_changedImages","nextState","changes","pitch","removeOrAddSourceCommands","diffSources","beforeLayers","beforeLayer","afterLayer","insertBeforeLayerId","beforeOrder","afterOrder","beforeIndex","afterIndex","tracker","clean","diffLayers","diffStyles","unimplementedOps","_afterImageUpdated","isSourceLoaded","layerObject","validateCustomStyleLayer","_layerOrderChanged","_updateLayer","moveLayer","newIndex","getFilter","_flattenAndSortRenderedFeatures","sourceResults","isLayer3D","features3D","layerFeatures","topmost3D","includedSources","renderedSymbols","bucketQueryData","queryData","bucketSymbols","layerSymbols","sortedA","layerName","dataTiles","dataID","addSourceType","SourceType","getSourceType","setSourceType","workerSourceURL","_update","_remove","rtlTextPluginEvented","_updateSources","_generateCollisionBoxes","_updatePlacement","placementCommitted","layerBucketsChanged","pauseablePlacement","_releaseSymbolFadeTiles","getResource","prelude","compile","backgroundPattern","clippingMask","heatmapTexture","collisionCircle","debug","fillOutline","fillOutlinePattern","fillPattern","fillExtrusionPattern","hillshadePrepare","lineGradient","linePattern","lineSDF","symbolIcon","symbolSDF","symbolTextAndIcon","fragmentSource","vertexSource","re","staticAttributes","fragmentUniforms","vertexUniforms","staticUniforms","fragmentPragmas","operation","precision","attrType","unpackType","VertexArrayObject","boundProgram","boundLayoutVertexBuffer","boundPaintVertexBuffers","boundIndexBuffer","boundVertexOffset","boundDynamicVertexBuffer","getTokenizedAttributesAndUniforms","paintVertexBuffers","dynamicVertexBuffer","dynamicVertexBuffer2","paintBuffersDiffer","boundDynamicVertexBuffer2","freshBind","numPrevAttributes","numNextAttributes","numAttributes","createVertexArrayOES","currentNumAttributes","disableVertexAttribArray","vertexBuffer","deleteVertexArrayOES","configuration","fixedUniforms","showOverdrawInspector","createProgram","staticAttrInfo","dynamicAttrInfo","allAttrInfo","staticUniformsInfo","dynamicUniformsInfo","allUniformsInfo","fragmentShader","FRAGMENT_SHADER","failedToCreate","attachShader","vertexShader","uniformLocations","bindAttribLocation","linkProgram","deleteShader","it","uniformLocation","getUniformLocation","patternUniformValues","tileRatio","numTiles","tileSizeAtNearestZoom","pixelX","pixelY","u_image","u_texsize","u_scale","u_fade","u_pixel_coord_upper","u_pixel_coord_lower","drawMode","uniformValues","currentProperties","dynamicLayoutBuffer","dynamicLayoutBuffer2","primitiveSize","LINES","TRIANGLES","LINE_STRIP","drawElements","UNSIGNED_SHORT","fillExtrusionUniformValues","shouldUseVerticalGradient","_lp","lightPos","lightMat","mat3","vec3","lightColor","u_matrix","u_lightpos","u_lightintensity","u_lightcolor","u_vertical_gradient","u_opacity","fillExtrusionPatternUniformValues","u_height_factor","fillUniformValues","fillPatternUniformValues","fillOutlineUniformValues","drawingBufferSize","u_world","fillOutlinePatternUniformValues","circleUniformValues","extrudeScale","pixelsToGLUnits","u_camera_to_center_distance","u_scale_with_map","translatePosMatrix","u_pitch_with_map","u_device_pixel_ratio","u_extrude_scale","collisionUniformValues","u_pixels_to_tile_units","u_overscale_factor","collisionCircleUniformValues","invMatrix","u_inv_matrix","u_viewport_size","debugUniformValues","scaleRatio","u_color","u_overlay","u_overlay_scale","clippingMaskUniformValues","heatmapUniformValues","u_intensity","lineUniformValues","calculateMatrix","u_ratio","u_units_to_pixels","lineGradientUniformValues","imageHeight","u_image_height","linePatternUniformValues","tileZoomRatio","calculateTileRatio","lineSDFUniformValues","posA","posB","widthA","widthB","u_patternscale_a","u_patternscale_b","u_sdfgamma","u_tex_y_a","u_tex_y_b","u_mix","rasterUniformValues","parentTL","parentScaleBy","fade","u_tl_parent","u_scale_parent","u_buffer_scale","u_fade_t","mix","u_image0","u_image1","u_brightness_low","u_brightness_high","u_saturation_factor","saturation","u_contrast_factor","contrast","u_spin_weights","spinWeights","quadTriangles","symbolIconUniformValues","rotateInShader","texSize","u_is_size_zoom_constant","u_is_size_feature_constant","u_size_t","u_size","u_pitch","u_rotate_symbol","u_aspect_ratio","u_fade_change","u_label_plane_matrix","u_coord_matrix","u_is_text","u_texture","symbolSDFUniformValues","isHalo","u_gamma_scale","u_is_halo","symbolTextAndIconUniformValues","texSizeSDF","texSizeIcon","u_texsize_icon","u_texture_icon","backgroundUniformValues","backgroundPatternUniformValues","imagePosA","imagePosB","u_pattern_tl_a","u_pattern_br_a","u_pattern_tl_b","u_pattern_br_b","u_pattern_size_a","u_pattern_size_b","u_scale_a","u_scale_b","u_tile_units_to_pixels","bgPatternUniformValues","programUniforms","u_color_ramp","u_latrange","u_light","u_shadow","u_highlight","u_accent","u_dimension","u_zoom","u_unpack","drawCollisionDebug","tileBatches","circleCount","circleOffset","invTransform","colorModeForRenderPass","circleProgram","vertexData","CollisionCircleLayoutArray","batch","circleIdx","collision","quadCount","triCount","QuadTriangleArray","idx","createQuadTriangles","identityMat4","calculateVariableRenderShift","renderTextSize","updateVariableAnchorsForBucket","tileScale","updateTextFitIcon","dynamicTextLayoutVertexArray","dynamicIconLayoutVertexArray","placedTextShifts","tileAnchor","projectedAnchor","symbolProjection","tilePixelRatio","shiftedAnchor","placedIcons","getSymbolProgramName","iconsInText","drawLayerSymbols","rotationAlignment","pitchAlignment","hasSortKey","depthModeForSublayer","tileRenderState","programConfiguration","sdfIcons","transformed","atlasInterpolation","atlasTextureIcon","atlasInterpolationIcon","rotating","zooming","NEAREST","iconScaled","iconsNeedLinear","hasVariableAnchors","uLabelPlaneMatrix","uglCoordMatrix","hasHalo","segmentState","TEXTURE1","drawSymbolElements","drawFillTiles","isOutline","programName","atlas","tileMatrix","stencilModeForClipping","drawExtrusionTiles","renderHillshade","shadow","highlight","accent","moving","hillshadeUniformValues","rasterBoundsBuffer","quadTriangleIndexBuffer","rasterBoundsSegments","prepareHillshade","textureStride","pixelData","renderTexture","hillshadeUniformPrepareValues","getFadeValues","sinceTile","sinceParent","idealZ","fadeIn","childOpacity","topColor","btmColor","leftColor","rightColor","centerColor","drawHorizontalLine","drawDebugSSRect","drawVerticalLine","SCISSOR_TEST","scissor","drawDebugTile","emptyTexture","debugBuffer","tileBorderIndexBuffer","debugSegments","tileRawData","tileSizeKb","tileIdText","initDebugOverlayCanvas","debugOverlayCanvas","ctx2d","shadowColor","shadowBlur","strokeStyle","strokeText","debugOverlayTexture","drawTextToOverlay","renderPass","pixelToTileScale","updateVariableAnchors","strokeWidth","strokeOpacity","segmentsRenderStates","segmentsState","HALF_FLOAT_OES","bindTextureToFramebuffer","textureUnit","colorRampUnit","heatmapTextureUniformValues","viewportBuffer","viewportSegments","renderTextureToMap","gradient","programId","firstTile","prevProgram","programChanged","layerGradient","gradientTexture","textureResolution","potentialOverzoom","opaquePassEnabledForLayer","LEQUAL","depthRangeFor3D","stencilModeFor3D","tileIDs","stencilConfigForOverlap","stencilModes","minTileZ","textureFilter","isPatternMissing","tileExtentBuffer","tileExtentSegments","setCustomLayerDefaults","customLayerMatrix","setBaseState","Painter","_tileTextures","setup","numSublayers","depthEpsilon","gpuTimers","tileExtentArray","PosArray","posAttributes","debugArray","rasterBoundsArray","viewportArray","tileLineStripIndices","LineStripIndexArray","quadTriangleIndices","stencilClearMode","nextStencilID","currentStencilSource","_renderTileClippingMasks","_tileClippingMaskIDs","REPLACE","NOTEQUAL","EQUAL","stencilValues","zToStencilMode","GEQUAL","_showOverdrawInspector","CONSTANT_COLOR","currentLayer","opaquePassCutoff","selectedSource","coordsAscending","coordsDescending","coordsDescendingSymbol","renderLayer","showTileBoundaries","showPadding","centerPoint","drawCrosshair","drawDebugPadding","gpuTimingStart","gpuTimingEnd","gpuTiming","ext","layerTimer","calls","cpuTime","createQueryEXT","beginQueryEXT","TIME_ELAPSED_EXT","endQueryEXT","collectGpuTimers","currentLayerTimers","queryGpuTimers","gpuTimer","gpuTime","getQueryObjectEXT","QUERY_RESULT_EXT","deleteQueryEXT","inViewportPixelUnitsUnits","sinA","cosA","translation","translatedMatrix","textures","shaders","Frustum","planes_","planes","fromInvProjectionMatrix","invProj","frustumCoords","frustumPlanes","az","bz","Aabb","min_","max_","quadrant","qMin","qMax","axis","distanceX","distanceY","frustum","aabbPoints","fullyInside","plane","pointsInside","projMin","MAX_VALUE","projMax","EdgeInsets","Transform","minPitch","maxPitch","renderWorldCopies","maxValidLatitude","_renderWorldCopies","_minZoom","_maxZoom","_minPitch","_maxPitch","setMaxBounds","_center","_fov","_unmodified","_edgeInsets","_posMatrixCache","_alignedPosMatrixCache","latRange","_calcMatrices","centerOffset","rotationMatrix","mat2","a3","fov","_zoom","zoomScale","zoomFraction","_constrain","isPaddingEqual","interpolatePadding","scaleZoom","utl","utr","ubl","ubr","w0","w1","actualZ","centerCoord","cameraFrustum","newRootTile","aabb","fullyVisible","intersectResult","longestDim","distanceSq","vec2","childX","childY","unmodified","unproject","setLocationAtPoint","loc","locationCoordinate","newCenter","coordinateLocation","locationPoint","coordinatePoint","pointLocation","coord0","coord1","pixelMatrixInverse","z0","z1","pixelMatrix","getMaxBounds","lngRange","unwrappedTileID","aligned","posMatrixKey","unwrappedX","alignedProjMatrix","projMatrix","mercatorMatrix","_constraining","sy","sx","h2","w2","groundAngle","fovAboveCenter","topHalfSurfaceDistance","farZ","nearZ","fovy","aspect","xShift","yShift","angleCos","angleSin","alignedM","getCameraPoint","yOffset","Hash","hashName","pending","timerId","later","_hashName","_updateHash","_updateHashUnthrottled","addTo","_map","_onHashChange","getHashString","mapFeedback","getZoom","getBearing","getPitch","hash","found","_getCurrentHash","keyval","dragRotate","isEnabled","touchZoomRotate","jumpTo","history","replaceState","SecurityError","defaultInertiaOptions","linearity","easing","defaultPanInertiaOptions","deceleration","maxSpeed","defaultZoomInertiaOptions","defaultBearingInertiaOptions","defaultPitchInertiaOptions","HandlerInertia","extendDuration","easeOptions","calculateEasing","amount","inertiaDuration","inertiaOptions","speed","_inertiaBuffer","record","settings","_drainInertiaBuffer","time","inertia","_onMoveEnd","panInertiaOptions","deltas","pan","pinchAround","around","zoomDelta","bearingDelta","pitchDelta","panDelta","noMoveStart","MapMouseEvent","originalEvent","getCanvasContainer","_defaultPrevented","defaultPrevented","MapTouchEvent","changedTouches","lngLats","curr","MapWheelEvent","MapEventHandler","_clickTolerance","clickTolerance","_mousedownPos","wheel","_firePreventable","mousedown","mouseup","click","dblclick","mouseover","mouseout","touchstart","touchmove","touchend","touchcancel","mapEvent","isActive","BlockableMapEventHandler","_delayContextMenu","_contextMenuEvent","mousemove","contextmenu","BoxZoomHandler","_el","_container","getContainer","indexTouches","_enabled","_active","shiftKey","_startPos","_lastPos","mousemoveWindow","_box","classList","_fireEvent","mouseupWindow","cameraAnimation","fitScreenCoordinates","linear","keydown","keyCode","blur","SingleTapRecognizer","numTouches","centroid","mapTouches","timeStamp","getCentroid","newTouches","TapRecognizer","singleTap","numTaps","lastTime","lastTap","count","tap","soonEnough","closeEnough","TapZoomHandler","_zoomIn","_zoomOut","zoomInPoint","zoomOutPoint","easeTo","BUTTONS_FLAGS","MouseHandler","_moved","_lastPoint","_eventButton","_correctButton","_move","eventButton","flag","buttons","buttonStillPressed","MousePanHandler","MouseRotateHandler","MousePitchHandler","TouchPanHandler","_minTouches","_touches","_sum","_calculateTransform","touchPointSum","touchDeltaSum","touchDeltaCount","prevPoint","TwoTouchHandler","getTouchById","getZoomDelta","lastDistance","_firstTwoTouches","_start","_aroundCenter","TouchZoomHandler","_distance","_startDistance","getBearingDelta","TouchRotateHandler","_minDiameter","_startVector","_vector","lastVector","_isBelowThreshold","threshold","bearingDeltaSinceStart","isVertical","TouchPitchHandler","_valid","_firstMove","_lastPoints","vectorA","vectorB","gestureBeginsVertically","movedA","movedB","isSameDirection","defaultOptions","panStep","bearingStep","pitchStep","KeyboardHandler","stepOptions","_panStep","_bearingStep","_pitchStep","_rotationDisabled","easeOut","altKey","metaKey","zoomDir","bearingDir","pitchDir","xDir","yDir","easeId","disableRotation","enableRotation","ScrollZoomHandler","handler","_handler","_delta","_defaultZoomRate","_wheelZoomRate","setZoomRate","zoomRate","setWheelZoomRate","wheelZoomRate","_finishTimeout","isZooming","_zooming","deltaMode","WheelEvent","DOM_DELTA_LINE","deltaY","timeDelta","_lastWheelEventTime","_type","_lastValue","_timeout","_onTimeout","_lastWheelEvent","initialEvent","_frameId","_around","_aroundPoint","_triggerRenderFrame","renderFrame","_targetZoom","_startZoom","_easing","_smoothOutEasing","targetZoom","startZoom","finished","noInertia","needsRenderFrame","_ease","_prevEase","DoubleClickZoomHandler","clickZoom","TapZoom","_clickZoom","_tapZoom","ClickZoomHandler","TapDragZoomHandler","_tap","_swipePoint","_swipeTouch","_tapTime","newSwipePoint","DragPanHandler","mousePan","touchPan","_mousePan","_touchPan","_inertiaOptions","DragRotateHandler","mouseRotate","mousePitch","_pitchWithRotate","pitchWithRotate","_mouseRotate","_mousePitch","TouchZoomRotateHandler","touchZoom","touchRotate","tapDragZoom","_touchZoom","_touchRotate","_tapDragZoom","isMoving","drag","RenderFrameEvent","hasChange","HandlerManager","_handlers","_handlersById","_changes","_inertia","_bearingSnap","bearingSnap","_previousActiveHandlers","_eventsInProgress","_addDefaultHandlers","passive","handleWindowEvent","handleEvent","boxZoom","tapZoom","doubleClickZoom","touchPitch","dragPan","scrollZoom","keyboard","interactive","handlerName","allowed","allowEndAnimation","_updatingCamera","_fireEvents","isRotating","_blockedByActive","activeHandlers","myName","_getMapTouches","eventName","inputEvent","mergedHandlerResult","eventsInProgress","mergeHandlerResult","deactivatedHandlers","_stop","handlerResult","_applyChanges","combined","combinedEventsInProgress","combinedDeactivatedHandlers","change","_updateMapTransform","combinedResult","newEventsInProgress","wasMoving","nowMoving","startEvents","originalEndEvent","endEvents","stillMoving","inertialEase","shouldSnapToNorth","resetNorth","_requestFrame","_renderTaskQueue","Camera","_moving","panBy","panTo","zoomTo","zoomIn","zoomOut","getPadding","setPadding","rotateTo","resetNorthPitch","snapToNorth","cameraForBounds","_cameraForBoxAndBearing","defaultPadding","edgePadding","p0world","p1world","p0rotated","p1rotated","upperRight","lowerLeft","scaleX","scaleY","rotatedPaddingOffset","offsetAtFinalZoom","fitBounds","_fitInternal","calculatedOptions","flyTo","zoomChanged","bearingChanged","pitchChanged","defaultEasing","essential","startBearing","startPitch","startPadding","_normalizeBearing","offsetAsPoint","pointAtOffset","locationAtOffset","_normalizeCenter","aroundPoint","finalScale","currently","_rotating","pitching","_pitching","_padding","_easeId","_prepareEase","speedup","_fireMoveEvents","interruptingEaseId","_afterEase","wasZooming","wasRotating","wasPitching","coercedOptions","curve","rho","u1","wMax","rho2","sinh","cosh","r0","S","screenSpeed","maxDuration","isEasing","_easeFrameId","allowGestures","_cancelRenderFrame","_onEaseFrame","_onEaseEnd","onEaseEnd","handlers","_easeStart","_easeOptions","_requestRenderFrame","_renderFrameCallback","currentBearing","diff","AttributionControl","getDefaultPosition","compact","_compactButton","_toggleAttribution","_setElementTitle","_innerContainer","_updateAttributions","_updateEditLink","_updateData","_updateCompact","_attribHTML","element","title","_getUIString","editLink","_editLink","querySelector","styleOwner","styleId","paramString","acc","_hash","rel","attributions","customAttribution","owner","attribHTML","attrib","innerHTML","offsetWidth","LogoControl","display","_updateLogo","_logoRequired","mapbox_logo","containerChildren","TaskQueue","_queue","_id","_cleared","_currentlyRunning","running","run","defaultLocale","AttributionControl.ToggleAttribution","AttributionControl.MapFeedback","FullscreenControl.Enter","FullscreenControl.Exit","GeolocateControl.FindMyLocation","GeolocateControl.LocationNotAvailable","LogoControl.Title","NavigationControl.ResetBearing","NavigationControl.ZoomIn","NavigationControl.ZoomOut","ScaleControl.Feet","ScaleControl.Meters","ScaleControl.Kilometers","ScaleControl.Miles","ScaleControl.NauticalMiles","attributionControl","preserveDrawingBuffer","trackResize","refreshExpiredTiles","maxTileCacheSize","Map","_interactive","_failIfMajorPerformanceCaveat","_preserveDrawingBuffer","_antialias","_trackResize","_crossSourceCollisions","_crossFadingFactor","_controls","_mapId","_locale","HTMLElement","maxBounds","_setupContainer","_setupPainter","_onWindowOnline","_onWindowResize","fitBoundsOptions","_localIdeographFontFamily","addControl","logoPosition","control","controlElement","positionContainer","_controlPositions","insertBefore","firstChild","removeControl","ci","hasControl","_containerDimensions","_resizeCanvas","fireMoving","setMinZoom","getMinZoom","setMaxZoom","getMaxZoom","setMinPitch","getMinPitch","setMaxPitch","getMaxPitch","getRenderWorldCopies","setRenderWorldCopies","_createDelegatedListener","mousein","delegates","delegatedListener","_delegatedListeners","delegatedListeners","listeners","removeDelegatedListener","_diffStyle","_updateStyle","_lazyInitEmptyStyle","_updateDiff","getStyle","isStyleLoaded","areTilesLoaded","existingImage","hasImage","loadImage","beforeId","_canvasContainer","_canvas","clientWidth","clientHeight","_detectMissingCSS","getComputedStyle","_missingCSSCanary","getPropertyValue","canvasContainer","_contextLost","_contextRestored","controlContainer","_controlContainer","positionName","_onMapScroll","testSupport","_frame","scrollTop","scrollLeft","_styleDirty","_sourcesDirty","updateStyle","_render","paintStartTimeStamp","frameStartTime","crossFading","_placementDirty","renderCPUTime","renderGPUTime","frameLayerQueries","renderedLayerTimes","layerTimes","somethingDirty","_repaint","_fullyLoaded","loseContext","_showTileBoundaries","_showPadding","repaint","_vertices","_setCacheLimits","checkThreshold","setCacheLimits","showCompass","showZoom","visualizePitch","NavigationControl","_zoomInButton","_createButton","_zoomOutButton","_compass","_compassIcon","_updateZoomButtons","isMax","isMin","_rotateCompassArrow","_setButtonTitle","MouseRotateWrapper","priorPos","down","move","offTemp","targetTouches","anchorTranslate","top-left","top-right","bottom-left","bottom-right","applyAnchorClass","prefix","supportsGeolocation","Marker","legacyOptions","_anchor","_color","_scale","_draggable","draggable","_isDragging","_rotation","rotation","_rotationAlignment","_pitchAlignment","_element","_offset","_defaultMarker","svg","createNS","setAttributeNS","defaultHeight","defaultWidth","markerLarge","page1","rx","ry","ellipse","bgPath","border","borderPath","maki","circleContainer","circle1","circle2","_popup","setDraggable","_onMapClick","_addDragHandler","_onUp","_onMove","getLngLat","_lngLat","setLngLat","_pos","getElement","setPopup","popup","_onKeyPress","_originalTabIndex","removeAttribute","linearOffset","markerHeight","getAttribute","legacyCode","charCode","togglePopup","targetElement","getPopup","isOpen","smartWrap","getOffset","setOffset","_pointerdownPos","_positionDelta","pointerEvents","shouldBeDraggable","isDraggable","setRotation","getRotation","setRotationAlignment","getRotationAlignment","setPitchAlignment","getPitchAlignment","positionOptions","enableHighAccuracy","maximumAge","trackUserLocation","showAccuracyCircle","showUserLocation","numberOfWatches","noTimeout","GeolocateControl","_setupUI","permissions","geolocation","_geolocationWatchID","clearWatch","_userLocationDotMarker","_accuracyCircleMarker","_onZoom","_isOutOfMapMaxBounds","longitude","_setErrorState","_watchState","_geolocateButton","_onSuccess","_updateMarker","_finish","_lastKnownPosition","_updateCamera","_dotElement","accuracy","geolocateSource","_accuracy","_updateCircleRadius","metersPerPixel","circleDiameter","_circleElement","_onError","_clearWatch","_timeoutId","_setup","watchPosition","getCurrentPosition","ScaleControl","updateScale","maxMeters","maxFeet","setScale","maxDistance","pow10","multiplier","getDecimalRoundNum","setUnit","FullscreenControl","_fullscreen","_fullscreenchange","_checkFullscreenSupport","_changeIcon","fullscreenEnabled","mozFullScreenEnabled","msFullscreenEnabled","webkitFullscreenEnabled","_fullscreenButton","_updateTitle","_onClickFullscreen","_getTitle","_isFullscreen","fullscreenElement","mozFullScreenElement","webkitFullscreenElement","msFullscreenElement","toggle","exitFullscreen","mozCancelFullScreen","msExitFullscreen","webkitCancelFullScreen","requestFullscreen","mozRequestFullScreen","msRequestFullscreen","webkitRequestFullscreen","closeButton","closeOnClick","focusAfterOpen","focusQuerySelector","Popup","_onClose","closeOnMove","_focusFirstElement","_trackPointer","_onMouseMove","_onMouseUp","_content","_onDrag","trackPointer","setText","setDOMContent","createTextNode","setHTML","html","frag","createDocumentFragment","temp","getMaxWidth","setMaxWidth","htmlNode","hasChildNodes","_createCloseButton","addClassName","removeClassName","toggleClassName","_closeButton","cursor","_tip","normalizeOffset","cornerOffset","convertedOffset","anchorComponents","offsetHeight","offsetedPos","firstFocusable","focus","deferred","pool","baseApiUrl","maxParallelImageRequests","numRequests","clearStorage","promise","clearTileCache"],"mappings":"iRAkBA,SAASA,EAAYC,GACjB,OAAQC,EAAmBD,GAG/B,SAASC,EAAmBD,GACxB,MAayB,oBAAXE,QAA8C,oBAAbC,SAbtB,gBAkBrBC,MAAMC,WACND,MAAMC,UAAUC,OAChBF,MAAMC,UAAUE,QAChBH,MAAMC,UAAUG,SAChBJ,MAAMC,UAAUI,SAChBL,MAAMC,UAAUK,aAChBN,MAAMC,UAAUM,KAChBP,MAAMC,UAAUO,MAChBR,MAAMC,UAAUQ,QAChBT,MAAMC,UAAUS,aAChBV,MAAMW,QAKHC,SAASX,WAAaW,SAASX,UAAUY,KAK5CC,OAAOC,MACPD,OAAOE,QACPF,OAAOG,gBACPH,OAAOI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