显示客户端IP的详细信息
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1 lines
3.5 MiB

{"version":3,"file":"mapbox-gl.js","sources":["../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/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_terrain.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/shaders/encode_attribute.js","../src/util/struct_array.js","../src/data/array_types.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/style/style_layer.js","../src/data/bucket/circle_attributes.js","../src/data/segment.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/mat3.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/quat.js","../src/util/primitives.js","../src/style/style_layer/circle_style_layer.js","../src/data/bucket/heatmap_bucket.js","../src/util/image.js","../src/style/style_layer/heatmap_style_layer_properties.js","../src/util/color_ramp.js","../src/style/style_layer/hillshade_style_layer_properties.js","../src/data/bucket/fill_attributes.js","../node_modules/earcut/src/earcut.js","../node_modules/quickselect/index.js","../src/util/classify_rings.js","../src/data/bucket/pattern_bucket_features.js","../src/data/bucket/fill_bucket.js","../src/style/style_layer/fill_style_layer_properties.js","../src/data/bucket/fill_extrusion_attributes.js","../node_modules/@mapbox/vector-tile/lib/vectortilefeature.js","../node_modules/@mapbox/vector-tile/lib/vectortilelayer.js","../node_modules/@mapbox/vector-tile/lib/vectortile.js","../node_modules/@mapbox/vector-tile/index.js","../src/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/symbol_size.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/anchor.js","../src/symbol/check_max_angle.js","../src/symbol/get_anchors.js","../src/symbol/clip_line.js","../node_modules/@mapbox/tiny-sdf/index.js","../src/render/glyph_manager.js","../src/symbol/quads.js","../src/style/load_glyph_range.js","../node_modules/tinyqueue/index.js","../src/util/find_pole_of_inaccessibility.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/raster_style_layer_properties.js","../src/style/style_layer/custom_style_layer.js","../src/style/style_layer/sky_style_layer_properties.js","../src/style/style_layer/sky_style_layer.js","../src/style/create_style_layer.js","../src/style/style_layer/heatmap_style_layer.js","../src/style/style_layer/hillshade_style_layer.js","../src/style/style_layer/fill_style_layer.js","../src/style/style_layer/background_style_layer.js","../src/style/style_layer/raster_style_layer.js","../src/render/texture.js","../src/util/throttled_invoker.js","../src/util/performance.js","../src/util/scheduler.js","../src/geo/lng_lat_bounds.js","../src/geo/lng_lat.js","../src/geo/mercator_coordinate.js","../node_modules/@mapbox/whoots-js/index.mjs","../src/source/tile_id.js","../src/util/dictionary_coder.js","../src/util/vectortile_to_geojson.js","../src/source/tile.js","../src/data/bucket.js","../src/source/source_state.js","../src/data/dem_tree.js","../src/data/dem_data.js","../src/source/tile_cache.js","../src/gl/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/source/source_cache.js","../src/terrain/elevation.js","../src/data/feature_index.js","../src/render/glyph_atlas.js","../src/source/worker_tile.js","../src/source/vector_tile_worker_source.js","../src/util/actor.js","../src/gl/context.js","../node_modules/gl-matrix/esm/mat2.js","../src/style-spec/group_by_layout.js","../src/style/style_layer_index.js","../src/source/raster_dem_tile_worker_source.js","../node_modules/@mapbox/geojson-rewind/index.js","../src/source/geojson_wrapper.js","../node_modules/vt-pbf/lib/geojson_wrapper.js","../node_modules/vt-pbf/index.js","../node_modules/kdbush/src/sort.js","../node_modules/kdbush/src/within.js","../node_modules/kdbush/src/index.js","../node_modules/kdbush/src/range.js","../node_modules/supercluster/index.js","../node_modules/geojson-vt/src/simplify.js","../node_modules/geojson-vt/src/feature.js","../node_modules/geojson-vt/src/convert.js","../node_modules/geojson-vt/src/clip.js","../node_modules/geojson-vt/src/wrap.js","../node_modules/geojson-vt/src/transform.js","../node_modules/geojson-vt/src/tile.js","../node_modules/geojson-vt/src/index.js","../src/source/geojson_worker_source.js","../src/source/worker.js","../node_modules/@mapbox/mapbox-gl-supported/index.js","../src/util/dom.js","../src/style/style_image.js","../src/render/image_manager.js","../src/style/light.js","../src/style/terrain.js","../src/render/line_atlas.js","../src/util/dispatcher.js","../src/source/pixels_to_tile_units.js","../src/style/query_geometry.js","../src/source/load_tilejson.js","../src/source/tile_bounds.js","../src/source/raster_tile_source.js","../src/data/raster_bounds_attributes.js","../src/source/image_source.js","../src/source/source.js","../src/source/vector_tile_source.js","../src/source/raster_dem_tile_source.js","../src/source/geojson_source.js","../src/source/video_source.js","../src/source/canvas_source.js","../src/source/query_features.js","../src/util/browser/web_worker.js","../src/util/worker_pool.js","../src/util/global_worker_pool.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/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/shaders/shaders.js","../src/render/vertex_array_object.js","../src/render/program/hillshade_program.js","../src/render/draw_hillshade.js","../src/terrain/terrain_raster_program.js","../src/terrain/draw_terrain_raster.js","../src/render/program/clipping_mask_program.js","../src/render/raster_fade.js","../src/terrain/terrain.js","../src/render/program.js","../src/render/program/pattern.js","../src/render/program/fill_extrusion_program.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/heatmap_program.js","../src/render/program/line_program.js","../src/render/program/raster_program.js","../src/render/program/symbol_program.js","../src/render/program/background_program.js","../src/render/program/program_uniforms.js","../src/render/program/skybox_program.js","../src/render/program/skybox_capture_program.js","../src/render/draw_collision_debug.js","../src/render/draw_symbol.js","../src/render/draw_fill.js","../src/render/draw_fill_extrusion.js","../src/render/draw_debug.js","../src/render/skybox_attributes.js","../src/render/skybox_geometry.js","../src/render/draw_sky.js","../src/render/painter.js","../src/render/draw_circle.js","../src/render/draw_heatmap.js","../src/render/draw_line.js","../src/render/draw_raster.js","../src/render/draw_background.js","../src/render/draw_custom.js","../src/geo/edge_insets.js","../src/ui/free_camera.js","../src/geo/transform.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/popup.js","../src/index.js","../src/ui/control/fullscreen_control.js","../rollup/mapboxgl.js"],"sourcesContent":["/*\n * Copyright (C) 2008 Apple Inc. All Rights Reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY\n * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Ported from Webkit\n * http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h\n */\n\nmodule.exports = UnitBezier;\n\nfunction UnitBezier(p1x, p1y, p2x, p2y) {\n // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).\n this.cx = 3.0 * p1x;\n this.bx = 3.0 * (p2x - p1x) - this.cx;\n this.ax = 1.0 - this.cx - this.bx;\n\n this.cy = 3.0 * p1y;\n this.by = 3.0 * (p2y - p1y) - this.cy;\n this.ay = 1.0 - this.cy - this.by;\n\n this.p1x = p1x;\n this.p1y = p2y;\n this.p2x = p2x;\n this.p2y = p2y;\n}\n\nUnitBezier.prototype.sampleCurveX = function(t) {\n // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.\n return ((this.ax * t + this.bx) * t + this.cx) * t;\n};\n\nUnitBezier.prototype.sampleCurveY = function(t) {\n return ((this.ay * t + this.by) * t + this.cy) * t;\n};\n\nUnitBezier.prototype.sampleCurveDerivativeX = function(t) {\n return (3.0 * this.ax * t + 2.0 * this.bx) * t + this.cx;\n};\n\nUnitBezier.prototype.solveCurveX = function(x, epsilon) {\n if (typeof epsilon === 'undefined') epsilon = 1e-6;\n\n var t0, t1, t2, x2, i;\n\n // First try a few iterations of Newton's method -- normally very fast.\n for (t2 = x, i = 0; i < 8; i++) {\n\n x2 = this.sampleCurveX(t2) - x;\n if (Math.abs(x2) < epsilon) return t2;\n\n var d2 = this.sampleCurveDerivativeX(t2);\n if (Math.abs(d2) < 1e-6) break;\n\n t2 = t2 - x2 / d2;\n }\n\n // Fall back to the bisection method for reliability.\n t0 = 0.0;\n t1 = 1.0;\n t2 = x;\n\n if (t2 < t0) return t0;\n if (t2 > t1) return t1;\n\n while (t0 < t1) {\n\n x2 = this.sampleCurveX(t2);\n if (Math.abs(x2 - x) < epsilon) return t2;\n\n if (x > x2) {\n t0 = t2;\n } else {\n t1 = t2;\n }\n\n t2 = (t1 - t0) * 0.5 + t0;\n }\n\n // Failure.\n return t2;\n};\n\nUnitBezier.prototype.solve = function(x, epsilon) {\n return this.sampleCurveY(this.solveCurveX(x, epsilon));\n};\n","'use strict';\n\nmodule.exports = Point;\n\n/**\n * A standalone point geometry with useful accessor, comparison, and\n * modification methods.\n *\n * @class Point\n * @param {Number} x the x-coordinate. this could be longitude or screen\n * pixels, or any other sort of unit.\n * @param {Number} y the y-coordinate. this could be latitude or screen\n * pixels, or any other sort of unit.\n * @example\n * var point = new Point(-77, 38);\n */\nfunction Point(x, y) {\n this.x = x;\n this.y = y;\n}\n\nPoint.prototype = {\n\n /**\n * Clone this point, returning a new point that can be modified\n * without affecting the old one.\n * @return {Point} the clone\n */\n clone: function() { return new Point(this.x, this.y); },\n\n /**\n * Add this point's x & y coordinates to another point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n add: function(p) { return this.clone()._add(p); },\n\n /**\n * Subtract this point's x & y coordinates to from point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n sub: function(p) { return this.clone()._sub(p); },\n\n /**\n * Multiply this point's x & y coordinates by point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n multByPoint: function(p) { return this.clone()._multByPoint(p); },\n\n /**\n * Divide this point's x & y coordinates by point,\n * yielding a new point.\n * @param {Point} p the other point\n * @return {Point} output point\n */\n divByPoint: function(p) { return this.clone()._divByPoint(p); },\n\n /**\n * Multiply this point's x & y coordinates by a factor,\n * yielding a new point.\n * @param {Point} k factor\n * @return {Point} output point\n */\n mult: function(k) { return this.clone()._mult(k); },\n\n /**\n * Divide this point's x & y coordinates by a factor,\n * yielding a new point.\n * @param {Point} k factor\n * @return {Point} output point\n */\n div: function(k) { return this.clone()._div(k); },\n\n /**\n * Rotate this point around the 0, 0 origin by an angle a,\n * given in radians\n * @param {Number} a angle to rotate around, in radians\n * @return {Point} output point\n */\n rotate: function(a) { return this.clone()._rotate(a); },\n\n /**\n * Rotate this point around p point by an angle a,\n * given in radians\n * @param {Number} a angle to rotate around, in radians\n * @param {Point} p Point to rotate around\n * @return {Point} output point\n */\n rotateAround: function(a,p) { return this.clone()._rotateAround(a,p); },\n\n /**\n * Multiply this point by a 4x1 transformation matrix\n * @param {Array<Number>} m transformation matrix\n * @return {Point} output point\n */\n matMult: function(m) { return this.clone()._matMult(m); },\n\n /**\n * Calculate this point but as a unit vector from 0, 0, meaning\n * that the distance from the resulting point to the 0, 0\n * coordinate will be equal to 1 and the angle from the resulting\n * point to the 0, 0 coordinate will be the same as before.\n * @return {Point} unit vector point\n */\n unit: function() { return this.clone()._unit(); },\n\n /**\n * Compute a perpendicular point, where the new y coordinate\n * is the old x coordinate and the new x coordinate is the old y\n * coordinate multiplied by -1\n * @return {Point} perpendicular point\n */\n perp: function() { return this.clone()._perp(); },\n\n /**\n * Return a version of this point with the x & y coordinates\n * rounded to integers.\n * @return {Point} rounded point\n */\n round: function() { return this.clone()._round(); },\n\n /**\n * Return the magitude of this point: this is the Euclidean\n * distance from the 0, 0 coordinate to this point's x and y\n * coordinates.\n * @return {Number} magnitude\n */\n mag: function() {\n return Math.sqrt(this.x * this.x + this.y * this.y);\n },\n\n /**\n * Judge whether this point is equal to another point, returning\n * true or false.\n * @param {Point} other the other point\n * @return {boolean} whether the points are equal\n */\n equals: function(other) {\n return this.x === other.x &&\n this.y === other.y;\n },\n\n /**\n * Calculate the distance from this point to another point\n * @param {Point} p the other point\n * @return {Number} distance\n */\n dist: function(p) {\n return Math.sqrt(this.distSqr(p));\n },\n\n /**\n * Calculate the distance from this point to another point,\n * without the square root step. Useful if you're comparing\n * relative distances.\n * @param {Point} p the other point\n * @return {Number} distance\n */\n distSqr: function(p) {\n var dx = p.x - this.x,\n dy = p.y - this.y;\n return dx * dx + dy * dy;\n },\n\n /**\n * Get the angle from the 0, 0 coordinate to this point, in radians\n * coordinates.\n * @return {Number} angle\n */\n angle: function() {\n return Math.atan2(this.y, this.x);\n },\n\n /**\n * Get the angle from this point to another point, in radians\n * @param {Point} b the other point\n * @return {Number} angle\n */\n angleTo: function(b) {\n return Math.atan2(this.y - b.y, this.x - b.x);\n },\n\n /**\n * Get the angle between this point and another point, in radians\n * @param {Point} b the other point\n * @return {Number} angle\n */\n angleWith: function(b) {\n return this.angleWithSep(b.x, b.y);\n },\n\n /*\n * Find the angle of the two vectors, solving the formula for\n * the cross product a x b = |a||b|sin(θ) for θ.\n * @param {Number} x the x-coordinate\n * @param {Number} y the y-coordinate\n * @return {Number} the angle in radians\n */\n angleWithSep: function(x, y) {\n return Math.atan2(\n this.x * y - this.y * x,\n this.x * x + this.y * y);\n },\n\n _matMult: function(m) {\n var x = m[0] * this.x + m[1] * this.y,\n y = m[2] * this.x + m[3] * this.y;\n this.x = x;\n this.y = y;\n return this;\n },\n\n _add: function(p) {\n this.x += p.x;\n this.y += p.y;\n return this;\n },\n\n _sub: function(p) {\n this.x -= p.x;\n this.y -= p.y;\n return this;\n },\n\n _mult: function(k) {\n this.x *= k;\n this.y *= k;\n return this;\n },\n\n _div: function(k) {\n this.x /= k;\n this.y /= k;\n return this;\n },\n\n _multByPoint: function(p) {\n this.x *= p.x;\n this.y *= p.y;\n return this;\n },\n\n _divByPoint: function(p) {\n this.x /= p.x;\n this.y /= p.y;\n return this;\n },\n\n _unit: function() {\n this._div(this.mag());\n return this;\n },\n\n _perp: function() {\n var y = this.y;\n this.y = this.x;\n this.x = -y;\n return this;\n },\n\n _rotate: function(angle) {\n var cos = Math.cos(angle),\n sin = Math.sin(angle),\n x = cos * this.x - sin * this.y,\n y = sin * this.x + cos * this.y;\n this.x = x;\n this.y = y;\n return this;\n },\n\n _rotateAround: function(angle, p) {\n var cos = Math.cos(angle),\n sin = Math.sin(angle),\n x = p.x + cos * (this.x - p.x) - sin * (this.y - p.y),\n y = p.y + sin * (this.x - p.x) + cos * (this.y - p.y);\n this.x = x;\n this.y = y;\n return this;\n },\n\n _round: function() {\n this.x = Math.round(this.x);\n this.y = Math.round(this.y);\n return this;\n }\n};\n\n/**\n * Construct a point from an array if necessary, otherwise if the input\n * is already a Point, or an unknown type, return it unchanged\n * @param {Array<Number>|Point|*} a any kind of input value\n * @return {Point} constructed point, or passed-through value.\n * @example\n * // this\n * var point = Point.convert([0, 1]);\n * // is equivalent to\n * var point = new Point(0, 1);\n */\nPoint.convert = function (a) {\n if (a instanceof Point) {\n return a;\n }\n if (Array.isArray(a)) {\n return new Point(a[0], a[1]);\n }\n return a;\n};\n","// @flow\n/* eslint-env browser */\nimport type {Window} from '../../types/window';\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';\nimport assert from 'assert';\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\nconst DEG_TO_RAD = Math.PI / 180;\nconst RAD_TO_DEG = 180 / Math.PI;\n\n/**\n * Converts an angle in degrees to radians\n * copy all properties from the source objects into the destination.\n * The last source object given overrides properties from previous\n * source objects.\n *\n * @param a angle to convert\n * @returns the angle in radians\n * @private\n */\nexport function degToRad(a: number): number {\n return a * DEG_TO_RAD;\n}\n\n/**\n * Converts an angle in radians to degrees\n * copy all properties from the source objects into the destination.\n * The last source object given overrides properties from previous\n * source objects.\n *\n * @param a angle to convert\n * @returns the angle in degrees\n * @private\n */\nexport function radToDeg(a: number): number {\n return a * RAD_TO_DEG;\n}\n\n/**\n * @module util\n * @private\n */\n\n/**\n * Given a value `t` that varies between 0 and 1, return\n * an interpolation function that eases between 0 and 1 in a pleasing\n * cubic in-out fashion.\n *\n * @private\n */\nexport function easeCubicInOut(t: number): number {\n if (t <= 0) return 0;\n if (t >= 1) return 1;\n const t2 = t * t,\n t3 = t2 * t;\n return 4 * (t < 0.5 ? t3 : 3 * (t - t2) + t3 - 0.75);\n}\n\n/**\n * Computes an AABB for a set of points.\n *\n * @param {Point[]} points\n * @returns {{ min: Point, max: Point}}\n * @private\n */\nexport function getBounds(points: Point[]): { min: Point, max: Point} {\n let minX = Infinity;\n let minY = Infinity;\n let maxX = -Infinity;\n let maxY = -Infinity;\n for (const p of points) {\n minX = Math.min(minX, p.x);\n minY = Math.min(minY, p.y);\n maxX = Math.max(maxX, p.x);\n maxY = Math.max(maxY, p.y);\n }\n\n return {\n min: new Point(minX, minY),\n max: new Point(maxX, maxY),\n };\n}\n\n/**\n * Converts a AABB into a polygon with clockwise winding order.\n *\n * @param {Point} min The top left point.\n * @param {Point} max The bottom right point.\n * @param {number} [buffer=0] The buffer width.\n * @param {boolean} [close=true] Whether to close the polygon or not.\n * @returns {Point[]} The polygon.\n */\nexport function polygonizeBounds(min: Point, max: Point, buffer: number = 0, close: boolean = true): Point[] {\n const offset = new Point(buffer, buffer);\n const minBuf = min.sub(offset);\n const maxBuf = max.add(offset);\n const polygon = [minBuf, new Point(maxBuf.x, minBuf.y), maxBuf, new Point(minBuf.x, maxBuf.y)];\n\n if (close) {\n polygon.push(minBuf);\n }\n return polygon;\n}\n\n/**\n * Takes a convex ring and expands it outward by applying a buffer around it.\n * This function assumes that the ring is in clockwise winding order.\n *\n * @param {Point[]} ring The input ring.\n * @param {number} buffer The buffer width.\n * @returns {Point[]} The expanded ring.\n */\nexport function bufferConvexPolygon(ring: Point[], buffer: number): Point[] {\n assert(ring.length > 2, 'bufferConvexPolygon requires the ring to have atleast 3 points');\n const output = [];\n for (let currIdx = 0; currIdx < ring.length; currIdx++) {\n const prevIdx = wrap(currIdx - 1, -1, ring.length - 1);\n const nextIdx = wrap(currIdx + 1, -1, ring.length - 1);\n const prev = ring[prevIdx];\n const curr = ring[currIdx];\n const next = ring[nextIdx];\n const p1 = prev.sub(curr).unit();\n const p2 = next.sub(curr).unit();\n const interiorAngle = p2.angleWithSep(p1.x, p1.y);\n // Calcuate a vector that points in the direction of the angle bisector between two sides.\n // Scale it based on a right angled triangle constructed at that corner.\n const offset = p1.add(p2).unit().mult(-1 * buffer / Math.sin(interiorAngle / 2));\n output.push(curr.add(offset));\n }\n return output;\n}\n\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<Item, Result>(\n array: Array<Item>,\n fn: (item: Item, fnCallback: Callback<Result>) => void,\n callback: Callback<Array<Result>>\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<T>(obj: {[key: string]: T}): Array<T> {\n const result = [];\n for (const k in obj) {\n result.push(obj[k]);\n }\n return result;\n}\n\n/*\n * Compute the difference between the keys in one object and the keys\n * in another object.\n *\n * @returns keys difference\n * @private\n */\nexport function keysDifference<S, T>(obj: {[key: string]: S}, other: {[key: string]: T}): Array<string> {\n const difference = [];\n for (const i in obj) {\n if (!(i in other)) {\n difference.push(i);\n }\n }\n return difference;\n}\n\n/**\n * Given a destination object and optionally many source objects,\n * copy all properties from the source objects into the destination.\n * The last source object given overrides properties from previous\n * source objects.\n *\n * @param dest destination object\n * @param sources sources from which properties are pulled\n * @private\n */\nexport function extend(dest: Object, ...sources: Array<?Object>): Object {\n for (const src of sources) {\n for (const k in src) {\n dest[k] = src[k];\n }\n }\n return dest;\n}\n\n/**\n * Given an object and a number of properties as strings, return version\n * of that object with only those properties.\n *\n * @param src the object\n * @param properties an array of property names chosen\n * to appear on the resulting object.\n * @returns object with limited properties.\n * @example\n * var foo = { name: 'Charlie', age: 10 };\n * var justName = pick(foo, ['name']);\n * // justName = { name: 'Charlie' }\n * @private\n */\nexport function pick(src: Object, properties: Array<string>): Object {\n const result = {};\n for (let i = 0; i < properties.length; i++) {\n const k = properties[i];\n if (k in src) {\n result[k] = src[k];\n }\n }\n return result;\n}\n\nlet id = 1;\n\n/**\n * Return a unique numeric id, starting at 1 and incrementing with\n * each call.\n *\n * @returns unique numeric id.\n * @private\n */\nexport function uniqueId(): number {\n return id++;\n}\n\n/**\n * Return a random UUID (v4). Taken from: https://gist.github.com/jed/982883\n * @private\n */\nexport function uuid(): string {\n function b(a) {\n return a ? (a ^ Math.random() * 16 >> a / 4).toString(16) :\n //$FlowFixMe: Flow doesn't like the implied array literal conversion here\n ([1e7] + -[1e3] + -4e3 + -8e3 + -1e11).replace(/[018]/g, b);\n }\n return b();\n}\n\n/**\n * Return whether a given value is a power of two\n * @private\n */\nexport function isPowerOfTwo(value: number): boolean {\n return (Math.log(value) / Math.LN2) % 1 === 0;\n}\n\n/**\n * Return the next power of two, or the input value if already a power of two\n * @private\n */\nexport function nextPowerOfTwo(value: number): number {\n if (value <= 1) return 1;\n return Math.pow(2, Math.ceil(Math.log(value) / Math.LN2));\n}\n\n/**\n * Return the previous power of two, or the input value if already a power of two\n * @private\n */\nexport function prevPowerOfTwo(value: number): number {\n if (value <= 1) return 1;\n return Math.pow(2, Math.floor(Math.log(value) / Math.LN2));\n}\n\n/**\n * Validate a string to match UUID(v4) of the\n * form: xxxxxxxx-xxxx-4xxx-[89ab]xxx-xxxxxxxxxxxx\n * @param str string to validate.\n * @private\n */\nexport function validateUuid(str: ?string): boolean {\n return str ? /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(str) : false;\n}\n\n/**\n * Given an array of member function names as strings, replace all of them\n * with bound versions that will always refer to `context` as `this`. This\n * is useful for classes where otherwise event bindings would reassign\n * `this` to the evented object or some other value: this lets you ensure\n * the `this` value always.\n *\n * @param fns list of member function names\n * @param context the context value\n * @example\n * function MyClass() {\n * bindAll(['ontimer'], this);\n * this.name = 'Tom';\n * }\n * MyClass.prototype.ontimer = function() {\n * alert(this.name);\n * };\n * var myClass = new MyClass();\n * setTimeout(myClass.ontimer, 100);\n * @private\n */\nexport function bindAll(fns: Array<string>, context: Object): void {\n fns.forEach((fn) => {\n if (!context[fn]) { return; }\n context[fn] = context[fn].bind(context);\n });\n}\n\n/**\n * Determine if a string ends with a particular substring\n *\n * @private\n */\nexport function endsWith(string: string, suffix: string): boolean {\n return string.indexOf(suffix, string.length - suffix.length) !== -1;\n}\n\n/**\n * Create an object by mapping all the values of an existing object while\n * preserving their keys.\n *\n * @private\n */\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<T>(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<T>(a: Array<T>, b: Array<T>): boolean {\n for (let l = 0; l < a.length; l++) {\n if (b.indexOf(a[l]) >= 0) return true;\n }\n return false;\n}\n\n/**\n * Print a warning message to the console and ensure duplicate warning messages\n * are not printed.\n *\n * @private\n */\nconst warnOnceHistory: {[key: string]: boolean} = {};\n\nexport function warnOnce(message: string): void {\n if (!warnOnceHistory[message]) {\n // console isn't defined in some WebWorkers, see #2558\n if (typeof console !== \"undefined\") console.warn(message);\n warnOnceHistory[message] = true;\n }\n}\n\n/**\n * Indicates if the provided Points are in a counter clockwise (true) or clockwise (false) order\n *\n * @private\n * @returns true for a counter clockwise set of points\n */\n// http://bryceboe.com/2006/10/23/line-segment-intersection-algorithm/\nexport function isCounterClockwise(a: Point, b: Point, c: Point): boolean {\n return (c.y - a.y) * (b.x - a.x) > (b.y - a.y) * (c.x - a.x);\n}\n\n/**\n * Returns the signed area for the polygon ring. Postive areas are exterior rings and\n * have a clockwise winding. Negative areas are interior rings and have a counter clockwise\n * ordering.\n *\n * @private\n * @param ring Exterior or interior ring\n */\nexport function calculateSignedArea(ring: Array<Point>): number {\n let sum = 0;\n for (let i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) {\n p1 = ring[i];\n p2 = ring[j];\n sum += (p2.x - p1.x) * (p1.y + p2.y);\n }\n return sum;\n}\n\n/**\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<Point>): 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/* 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\nlet linkEl;\n\nlet reducedMotionQuery: MediaQueryList;\n\nlet errorState = false;\n\nlet stubTime;\n\n/**\n * @private\n */\nconst exported = {\n /**\n * Returns either performance.now() or a value set by setNow.\n * @returns Time value in milliseconds.\n */\n now(): number {\n if (stubTime !== undefined) {\n return stubTime;\n }\n return window.performance.now();\n },\n\n setErrorState() {\n errorState = true;\n },\n\n setNow(time: number) {\n stubTime = time;\n },\n\n restoreNow() {\n stubTime = undefined;\n },\n\n frame(fn: (paintStartTimestamp: number) => void): Cancelable {\n if (errorState) return {cancel: () => { }};\n const frame = window.requestAnimationFrame(fn);\n return {cancel: () => window.cancelAnimationFrame(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 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\ntype Config = {|\n API_URL: string,\n API_URL_REGEX: RegExp,\n EVENTS_URL: ?string,\n SESSION_PATH: string,\n FEEDBACK_URL: string,\n REQUIRE_ACCESS_TOKEN: boolean,\n TILE_URL_VERSION: string,\n RASTER_URL_PREFIX: string,\n ACCESS_TOKEN: ?string,\n MAX_PARALLEL_IMAGE_REQUESTS: number\n|};\n\nlet mapboxHTTPURLRegex;\n\nconst config: Config = {\n API_URL: 'https://api.mapbox.com',\n get API_URL_REGEX () {\n if (mapboxHTTPURLRegex == null) {\n const prodMapboxHTTPURLRegex = /^((https?:)?\\/\\/)?([^\\/]+\\.)?mapbox\\.c(n|om)(\\/|\\?|$)/i;\n try {\n mapboxHTTPURLRegex = (process.env.API_URL_REGEX != null) ? new RegExp(process.env.API_URL_REGEX) : prodMapboxHTTPURLRegex;\n } catch (e) {\n mapboxHTTPURLRegex = prodMapboxHTTPURLRegex;\n }\n }\n\n return mapboxHTTPURLRegex;\n },\n get 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 SESSION_PATH: '/map-sessions/v1',\n FEEDBACK_URL: 'https://apps.mapbox.com/feedback',\n TILE_URL_VERSION: 'v4',\n RASTER_URL_PREFIX: 'raster/v1',\n REQUIRE_ACCESS_TOKEN: true,\n ACCESS_TOKEN: null,\n MAX_PARALLEL_IMAGE_REQUESTS: 16\n};\n\nexport default config;\n","// @flow strict\n\nimport window from './window';\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 REMOVAL OR MODIFICATION OF THE\n* FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******\n* The following code is used to access Mapbox's APIs. Removal or modification\n* of this code can result in higher fees and/or\n* termination of your account with Mapbox.\n*\n* Under the Mapbox Terms of Service, you may not use this code to access Mapbox\n* Mapping APIs other than through Mapbox SDKs.\n*\n* The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps\n* and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/\n******************************************************************************/\n\ntype SkuTokenObject = {|\n token: string,\n tokenExpiresAt: number\n|};\n\nconst SKU_ID = '01';\n\nfunction createSkuToken(): SkuTokenObject {\n // SKU_ID and TOKEN_VERSION are specified by an internal schema and should not change\n const TOKEN_VERSION = '1';\n const base62chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';\n // sessionRandomizer is a randomized 10-digit base-62 number\n let sessionRandomizer = '';\n for (let i = 0; i < 10; i++) {\n sessionRandomizer += base62chars[Math.floor(Math.random() * 62)];\n }\n const expiration = 12 * 60 * 60 * 1000; // 12 hours\n const token = [TOKEN_VERSION, SKU_ID, sessionRandomizer].join('');\n const tokenExpiresAt = Date.now() + expiration;\n\n return {token, tokenExpiresAt};\n}\n\nexport {createSkuToken, SKU_ID};\n\n/***** END WARNING - REMOVAL OR MODIFICATION OF THE\nPRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******/\n","// @flow\n\n/***** START WARNING REMOVAL OR MODIFICATION OF THE\n* FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******\n* The following code is used to access Mapbox's APIs. Removal or modification\n* of this code can result in higher fees and/or\n* termination of your account with Mapbox.\n*\n* Under the Mapbox Terms of Service, you may not use this code to access Mapbox\n* Mapping APIs other than through Mapbox SDKs.\n*\n* The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps\n* and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/\n******************************************************************************/\n\nimport config from './config';\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, getData} from './ajax';\n\nimport type {RequestParameters} from './ajax';\nimport type {Cancelable} from '../types/cancelable';\nimport type {TileJSON} from '../types/tilejson';\n\ntype ResourceTypeEnum = $Keys<typeof ResourceType>;\nexport type RequestTransformFunction = (url: string, resourceType?: ResourceTypeEnum) => RequestParameters;\n\ntype UrlObject = {|\n protocol: string,\n authority: string,\n path: string,\n params: Array<string>\n|};\n\nexport const AUTH_ERR_MSG: string = 'NO_ACCESS_TOKEN';\n\nexport class RequestManager {\n _skuToken: string;\n _skuTokenExpiresAt: number;\n _transformRequestFn: ?RequestTransformFunction;\n _customAccessToken: ?string;\n\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, use2x?: boolean, rasterTileSize?: number): string {\n if (this._isSkuTokenExpired()) {\n this._createSkuToken();\n }\n\n if (tileURL && !isMapboxURL(tileURL)) return tileURL;\n\n const urlObject = parseUrl(tileURL);\n const imageExtensionRe = /(\\.(png|jpg)\\d*)(?=$)/;\n const extension = webpSupported.supported ? '.webp' : '$1';\n\n // The v4 mapbox tile API supports 512x512 image tiles but they must be requested as '@2x' tiles.\n const use2xAs512 = rasterTileSize && urlObject.authority !== 'raster' && rasterTileSize === 512;\n\n const suffix = use2x || use2xAs512 ? '@2x' : '';\n urlObject.path = urlObject.path.replace(imageExtensionRe, `${suffix}${extension}`);\n\n if (urlObject.authority === 'raster') {\n urlObject.path = `/${config.RASTER_URL_PREFIX}${urlObject.path}`;\n } else {\n const tileURLAPIPrefixRe = /^.+\\/v4\\//;\n urlObject.path = urlObject.path.replace(tileURLAPIPrefixRe, '/');\n urlObject.path = `/${config.TILE_URL_VERSION}${urlObject.path}`;\n }\n\n const accessToken = this._customAccessToken || getAccessToken(urlObject.params) || config.ACCESS_TOKEN;\n if (config.REQUIRE_ACCESS_TOKEN && accessToken && this._skuToken) {\n urlObject.params.push(`sku=${this._skuToken}`);\n }\n\n return this._makeAPIURL(urlObject, accessToken);\n }\n\n canonicalizeTileURL(url: string, removeAccessToken: boolean) {\n // matches any file extension specified by a dot and one or more alphanumeric characters\n const extensionRe = /\\.[\\w]+$/;\n\n const urlObject = parseUrl(url);\n // Make sure that we are dealing with a valid Mapbox tile URL.\n // Has to begin with /v4/ or /raster/v1, with a valid filename + extension\n if (!urlObject.path.match(/^(\\/v4\\/|\\/raster\\/v1\\/)/) || !urlObject.path.match(extensionRe)) {\n // Not a proper Mapbox tile URL.\n return url;\n }\n // Reassemble the canonical URL from the parts we've parsed before.\n let result = \"mapbox://\";\n if (urlObject.path.match(/^\\/raster\\/v1\\//)) {\n // If the tile url has /raster/v1/, make the final URL mapbox://raster/....\n const rasterPrefix = `/${config.RASTER_URL_PREFIX}/`;\n result += `raster/${urlObject.path.replace(rasterPrefix, '')}`;\n } else {\n const tilesPrefix = `/${config.TILE_URL_VERSION}/`;\n result += `tiles/${urlObject.path.replace(tilesPrefix, '')}`;\n }\n\n // Append the query string, minus the access token parameter.\n let params = urlObject.params;\n if (removeAccessToken) {\n params = params.filter(p => !p.match(/^access_token=/));\n }\n if (params.length) result += `?${params.join('&')}`;\n return result;\n }\n\n canonicalizeTileset(tileJSON: TileJSON, sourceURL?: string) {\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\nfunction isMapboxHTTPURL(url: string): boolean {\n return config.API_URL_REGEX.test(url);\n}\n\nfunction hasCacheDefeatingSku(url: string) {\n return url.indexOf('sku=') > 0 && isMapboxHTTPURL(url);\n}\n\nfunction getAccessToken(params: Array<string>): string | null {\n for (const param of params) {\n const match = param.match(/^access_token=(.*)$/);\n if (match) {\n return match[1];\n }\n }\n return null;\n}\n\nconst urlRe = /^(\\w+):\\/\\/([^/?]*)(\\/[^?]+)?\\??(.+)?/;\n\nfunction parseUrl(url: string): UrlObject {\n const parts = url.match(urlRe);\n if (!parts) {\n throw new Error('Unable to parse URL object');\n }\n return {\n protocol: parts[1],\n authority: parts[2],\n path: parts[3] || '/',\n params: parts[4] ? parts[4].split('&') : []\n };\n}\n\nfunction formatUrl(obj: UrlObject): string {\n const params = obj.params.length ? `?${obj.params.join('&')}` : '';\n return `${obj.protocol}://${obj.authority}${obj.path}${params}`;\n}\n\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' | 'map.auth';\n\nclass TelemetryEvent {\n eventData: any;\n anonId: ?string;\n queue: Array<any>;\n type: TelemetryEventType;\n pendingRequest: ?Cancelable;\n _customAccessToken: ?string;\n\n constructor(type: TelemetryEventType) {\n this.type = type;\n this.anonId = null;\n this.eventData = {};\n this.queue = [];\n this.pendingRequest = null;\n }\n\n getStorageKey(domain: ?string) {\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 errorCb: (err: ?Error) => void;\n\n constructor() {\n super('map.load');\n this.success = {};\n this.skuToken = '';\n }\n\n postMapLoadEvent(mapId: number, skuToken: string, customAccessToken: string, callback: (err: ?Error) => void) {\n this.skuToken = skuToken;\n this.errorCb = callback;\n\n if (config.EVENTS_URL) {\n if (customAccessToken || config.ACCESS_TOKEN) {\n this.queueRequest({id: mapId, timestamp: Date.now()}, customAccessToken);\n } else {\n this.errorCb(new Error('A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/'));\n }\n }\n }\n\n processRequests(customAccessToken?: ?string) {\n if (this.pendingRequest || this.queue.length === 0) return;\n const {id, timestamp} = this.queue.shift();\n\n // Only one load event should fire per map\n if (id && this.success[id]) return;\n\n if (!this.anonId) {\n this.fetchEventData();\n }\n\n if (!validateUuid(this.anonId)) {\n this.anonId = uuid();\n }\n\n this.postEvent(timestamp, {skuToken: this.skuToken}, (err) => {\n if (err) {\n this.errorCb(err);\n } else {\n if (id) this.success[id] = true;\n }\n\n }, customAccessToken);\n }\n}\n\nexport class MapSessionAPI extends TelemetryEvent {\n +success: {[_: number]: boolean};\n skuToken: string;\n errorCb: (err: ?Error) => void;\n\n constructor() {\n super('map.auth');\n this.success = {};\n this.skuToken = '';\n }\n\n getSession(timestamp: number, token: string, callback: (err: ?Error) => void, customAccessToken?: ?string) {\n if (!config.API_URL || !config.SESSION_PATH) return;\n const authUrlObject: UrlObject = parseUrl(config.API_URL + config.SESSION_PATH);\n authUrlObject.params.push(`sku=${token || ''}`);\n authUrlObject.params.push(`access_token=${customAccessToken || config.ACCESS_TOKEN || ''}`);\n\n const request: RequestParameters = {\n url: formatUrl(authUrlObject),\n headers: {\n 'Content-Type': 'text/plain', //Skip the pre-flight OPTIONS request\n }\n };\n\n this.pendingRequest = getData(request, (error) => {\n this.pendingRequest = null;\n callback(error);\n this.saveEventData();\n this.processRequests(customAccessToken);\n });\n }\n\n getSessionAPI(mapId: number, skuToken: string, customAccessToken: string, callback: (err: ?Error) => void) {\n this.skuToken = skuToken;\n this.errorCb = callback;\n\n if (config.SESSION_PATH && config.API_URL) {\n if (customAccessToken || config.ACCESS_TOKEN) {\n this.queueRequest({id: mapId, timestamp: Date.now()}, customAccessToken);\n } else {\n this.errorCb(new Error(AUTH_ERR_MSG));\n }\n }\n }\n\n processRequests(customAccessToken?: ?string) {\n if (this.pendingRequest || this.queue.length === 0) return;\n const {id, timestamp} = this.queue.shift();\n\n // Only one load event should fire per map\n if (id && this.success[id]) return;\n\n this.getSession(timestamp, this.skuToken, (err) => {\n if (err) {\n this.errorCb(err);\n } else {\n if (id) this.success[id] = true;\n }\n }, customAccessToken);\n }\n}\n\nexport class TurnstileEvent extends TelemetryEvent {\n constructor(customAccessToken?: ?string) {\n super('appUserTurnstile');\n this._customAccessToken = customAccessToken;\n }\n\n postTurnstileEvent(tileUrls: Array<string>, customAccessToken?: ?string) {\n //Enabled only when Mapbox Access Token is set and a source uses\n // mapbox tiles.\n if (config.EVENTS_URL &&\n config.ACCESS_TOKEN &&\n Array.isArray(tileUrls) &&\n tileUrls.some(url => isMapboxURL(url) || isMapboxHTTPURL(url))) {\n this.queueRequest(Date.now(), customAccessToken);\n }\n }\n\n processRequests(customAccessToken?: ?string) {\n if (this.pendingRequest || this.queue.length === 0) {\n return;\n }\n\n if (!this.anonId || !this.eventData.lastSuccess || !this.eventData.tokenU) {\n //Retrieve cached data\n this.fetchEventData();\n }\n\n const tokenData = parseAccessToken(config.ACCESS_TOKEN);\n const tokenU = tokenData ? tokenData['u'] : config.ACCESS_TOKEN;\n //Reset event data cache if the access token owner changed.\n let dueForEvent = tokenU !== this.eventData.tokenU;\n\n if (!validateUuid(this.anonId)) {\n this.anonId = uuid();\n dueForEvent = true;\n }\n\n const nextUpdate = this.queue.shift();\n // Record turnstile event once per calendar day.\n if (this.eventData.lastSuccess) {\n const lastUpdate = new Date(this.eventData.lastSuccess);\n const nextDate = new Date(nextUpdate);\n const daysElapsed = (nextUpdate - this.eventData.lastSuccess) / (24 * 60 * 60 * 1000);\n dueForEvent = dueForEvent || daysElapsed >= 1 || daysElapsed < -1 || lastUpdate.getDate() !== nextDate.getDate();\n } else {\n dueForEvent = true;\n }\n\n if (!dueForEvent) {\n 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\nconst mapSessionAPI_ = new MapSessionAPI();\nexport const getMapSessionAPI = mapSessionAPI_.getSessionAPI.bind(mapSessionAPI_);\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<Cache>;\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<T> = (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\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<any>): Cancelable {\n const controller = new window.AbortController();\n const request = new window.Request(requestParameters.url, {\n method: requestParameters.method || 'GET',\n body: requestParameters.body,\n credentials: requestParameters.credentials,\n headers: requestParameters.headers,\n referrer: getReferrer(),\n 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<any>): Cancelable {\n const xhr: XMLHttpRequest = new window.XMLHttpRequest();\n\n xhr.open(requestParameters.method || 'GET', requestParameters.url, true);\n if (requestParameters.type === 'arrayBuffer') {\n xhr.responseType = 'arraybuffer';\n }\n for (const k in requestParameters.headers) {\n xhr.setRequestHeader(k, requestParameters.headers[k]);\n }\n if (requestParameters.type === 'json') {\n xhr.responseType = 'text';\n xhr.setRequestHeader('Accept', 'application/json');\n }\n xhr.withCredentials = requestParameters.credentials === 'include';\n xhr.onerror = () => {\n callback(new Error(xhr.statusText));\n };\n xhr.onload = () => {\n if (((xhr.status >= 200 && xhr.status < 300) || xhr.status === 0) && xhr.response !== null) {\n let data: mixed = xhr.response;\n if (requestParameters.type === 'json') {\n // We're manually parsing JSON here to get better error messages.\n try {\n data = JSON.parse(xhr.response);\n } catch (err) {\n return callback(err);\n }\n }\n callback(null, data, xhr.getResponseHeader('Cache-Control'), xhr.getResponseHeader('Expires'));\n } else {\n callback(new AJAXError(xhr.statusText, xhr.status, requestParameters.url));\n }\n };\n xhr.send(requestParameters.body);\n return {cancel: () => xhr.abort()};\n}\n\nexport const makeRequest = function(requestParameters: RequestParameters, callback: ResponseCallback<any>): Cancelable {\n // We're trying to use the Fetch API if possible. However, in some situations we can't use it:\n // - Safari exposes window.AbortController, but it doesn't work actually abort any requests in\n // older versions (see https://bugs.webkit.org/show_bug.cgi?id=174980#c2). In this case,\n // we dispatch the request to the main thread so that we can get an accruate referrer header.\n // - Requests for resources with the file:// URI scheme don't work with the Fetch API either. In\n // this case we unconditionally use XHR on the current thread since referrers don't matter.\n if (!isFileURL(requestParameters.url)) {\n if (window.fetch && window.Request && window.AbortController && window.Request.prototype.hasOwnProperty('signal')) {\n return makeFetchRequest(requestParameters, callback);\n }\n if (isWorker() && self.worker && self.worker.actor) {\n const queueOnMainThread = true;\n return self.worker.actor.send('getResource', requestParameters, callback, undefined, queueOnMainThread);\n }\n }\n return makeXMLHttpRequest(requestParameters, callback);\n};\n\nexport const getJSON = function(requestParameters: RequestParameters, callback: ResponseCallback<Object>): Cancelable {\n return makeRequest(extend(requestParameters, {type: 'json'}), callback);\n};\n\nexport const getArrayBuffer = function(requestParameters: RequestParameters, callback: ResponseCallback<ArrayBuffer>): Cancelable {\n return makeRequest(extend(requestParameters, {type: 'arrayBuffer'}), callback);\n};\n\nexport const postData = function(requestParameters: RequestParameters, callback: ResponseCallback<string>): Cancelable {\n return makeRequest(extend(requestParameters, {method: 'POST'}), callback);\n};\n\nexport const getData = function(requestParameters: RequestParameters, callback: ResponseCallback<string>): Cancelable {\n return makeRequest(extend(requestParameters, {method: 'GET'}), callback);\n};\n\nfunction sameOrigin(url) {\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<HTMLImageElement | ImageBitmap>): Cancelable {\n if (webpSupported.supported) {\n if (!requestParameters.headers) {\n requestParameters.headers = {};\n }\n requestParameters.headers.accept = 'image/webp,*/*';\n }\n\n // limit concurrent image loads to help with raster sources performance on big screens\n if (numImageRequests >= config.MAX_PARALLEL_IMAGE_REQUESTS) {\n const queued = {\n requestParameters,\n callback,\n cancelled: false,\n 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<string>, callback: Callback<HTMLVideoElement>): Cancelable {\n const video: HTMLVideoElement = window.document.createElement('video');\n video.muted = true;\n video.onloadstart = function() {\n callback(null, video);\n };\n for (let i = 0; i < urls.length; i++) {\n const s: HTMLSourceElement = window.document.createElement('source');\n if (!sameOrigin(urls[i])) {\n video.crossOrigin = 'Anonymous';\n }\n s.src = urls[i];\n video.appendChild(s);\n }\n return {cancel: () => {}};\n};\n","// @flow\n\nimport {extend} from './util';\n\ntype Listener = (Object) => any;\ntype Listeners = {[_: string]: Array<Listener> };\n\nfunction _addEventListener(type: string, listener: Listener, listenerList: Listeners) {\n const listenerExists = listenerList[type] && listenerList[type].indexOf(listener) !== -1;\n if (!listenerExists) {\n listenerList[type] = listenerList[type] || [];\n listenerList[type].push(listener);\n }\n}\n\nfunction _removeEventListener(type: string, listener: Listener, listenerList: Listeners) {\n if (listenerList && listenerList[type]) {\n const index = listenerList[type].indexOf(listener);\n if (index !== -1) {\n listenerList[type].splice(index, 1);\n }\n }\n}\n\nexport class Event {\n +type: string;\n\n constructor(type: string, data: Object = {}) {\n extend(this, data);\n this.type = type;\n }\n}\n\ninterface ErrorLike {\n message: string;\n}\n\nexport class ErrorEvent extends Event {\n error: ErrorLike;\n\n constructor(error: ErrorLike, data: Object = {}) {\n super('error', extend({error}, data));\n }\n}\n\n/**\n * 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 (optional) The function to be called when the event is fired once.\n * If not provided, returns a Promise that will be resolved when the event is fired once.\n * @returns {Object} `this` | Promise\n */\n once(type: *, listener?: Listener): this | Promise<Event> {\n if (!listener) {\n return new Promise(resolve => this.once(type, resolve));\n }\n\n this._oneTimeListeners = this._oneTimeListeners || {};\n _addEventListener(type, listener, this._oneTimeListeners);\n\n return this;\n }\n\n fire(event: Event, properties?: Object) {\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 true if this instance of Evented or any forwarded instances of Evented have a listener for the specified type.\n *\n * @param {string} type The event type\n * @returns {boolean} `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<any>) {\n for (const input of inputs) {\n for (const k in input) {\n output[k] = input[k];\n }\n }\n return output;\n}\n","// @flow\n\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<Type>): boolean {\n return allowedTypes.some(t => t.kind === provided.kind);\n}\n\nexport function isValidNativeType(provided: any, allowedTypes: Array<NativeType>): boolean {\n return allowedTypes.some(t => {\n if (t === 'null') {\n return provided === null;\n } else if (t === 'array') {\n return Array.isArray(provided);\n } else if (t === 'object') {\n return provided && !Array.isArray(provided) && typeof provided === 'object';\n } else {\n return t === typeof provided;\n }\n });\n}\n","// (c) Dean McNamee <dean@gmail.com>, 2012.\n//\n// https://github.com/deanm/css-color-parser-js\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to\n// deal in the Software without restriction, including without limitation the\n// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n// sell copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n\n// http://www.w3.org/TR/css3-color/\nvar kCSSColorTable = {\n \"transparent\": [0,0,0,0], \"aliceblue\": [240,248,255,1],\n \"antiquewhite\": [250,235,215,1], \"aqua\": [0,255,255,1],\n \"aquamarine\": [127,255,212,1], \"azure\": [240,255,255,1],\n \"beige\": [245,245,220,1], \"bisque\": [255,228,196,1],\n \"black\": [0,0,0,1], \"blanchedalmond\": [255,235,205,1],\n \"blue\": [0,0,255,1], \"blueviolet\": [138,43,226,1],\n \"brown\": [165,42,42,1], \"burlywood\": [222,184,135,1],\n \"cadetblue\": [95,158,160,1], \"chartreuse\": [127,255,0,1],\n \"chocolate\": [210,105,30,1], \"coral\": [255,127,80,1],\n \"cornflowerblue\": [100,149,237,1], \"cornsilk\": [255,248,220,1],\n \"crimson\": [220,20,60,1], \"cyan\": [0,255,255,1],\n \"darkblue\": [0,0,139,1], \"darkcyan\": [0,139,139,1],\n \"darkgoldenrod\": [184,134,11,1], \"darkgray\": [169,169,169,1],\n \"darkgreen\": [0,100,0,1], \"darkgrey\": [169,169,169,1],\n \"darkkhaki\": [189,183,107,1], \"darkmagenta\": [139,0,139,1],\n \"darkolivegreen\": [85,107,47,1], \"darkorange\": [255,140,0,1],\n \"darkorchid\": [153,50,204,1], \"darkred\": [139,0,0,1],\n \"darksalmon\": [233,150,122,1], \"darkseagreen\": [143,188,143,1],\n \"darkslateblue\": [72,61,139,1], \"darkslategray\": [47,79,79,1],\n \"darkslategrey\": [47,79,79,1], \"darkturquoise\": [0,206,209,1],\n \"darkviolet\": [148,0,211,1], \"deeppink\": [255,20,147,1],\n \"deepskyblue\": [0,191,255,1], \"dimgray\": [105,105,105,1],\n \"dimgrey\": [105,105,105,1], \"dodgerblue\": [30,144,255,1],\n \"firebrick\": [178,34,34,1], \"floralwhite\": [255,250,240,1],\n \"forestgreen\": [34,139,34,1], \"fuchsia\": [255,0,255,1],\n \"gainsboro\": [220,220,220,1], \"ghostwhite\": [248,248,255,1],\n \"gold\": [255,215,0,1], \"goldenrod\": [218,165,32,1],\n \"gray\": [128,128,128,1], \"green\": [0,128,0,1],\n \"greenyellow\": [173,255,47,1], \"grey\": [128,128,128,1],\n \"honeydew\": [240,255,240,1], \"hotpink\": [255,105,180,1],\n \"indianred\": [205,92,92,1], \"indigo\": [75,0,130,1],\n \"ivory\": [255,255,240,1], \"khaki\": [240,230,140,1],\n \"lavender\": [230,230,250,1], \"lavenderblush\": [255,240,245,1],\n \"lawngreen\": [124,252,0,1], \"lemonchiffon\": [255,250,205,1],\n \"lightblue\": [173,216,230,1], \"lightcoral\": [240,128,128,1],\n \"lightcyan\": [224,255,255,1], \"lightgoldenrodyellow\": [250,250,210,1],\n \"lightgray\": [211,211,211,1], \"lightgreen\": [144,238,144,1],\n \"lightgrey\": [211,211,211,1], \"lightpink\": [255,182,193,1],\n \"lightsalmon\": [255,160,122,1], \"lightseagreen\": [32,178,170,1],\n \"lightskyblue\": [135,206,250,1], \"lightslategray\": [119,136,153,1],\n \"lightslategrey\": [119,136,153,1], \"lightsteelblue\": [176,196,222,1],\n \"lightyellow\": [255,255,224,1], \"lime\": [0,255,0,1],\n \"limegreen\": [50,205,50,1], \"linen\": [250,240,230,1],\n \"magenta\": [255,0,255,1], \"maroon\": [128,0,0,1],\n \"mediumaquamarine\": [102,205,170,1], \"mediumblue\": [0,0,205,1],\n \"mediumorchid\": [186,85,211,1], \"mediumpurple\": [147,112,219,1],\n \"mediumseagreen\": [60,179,113,1], \"mediumslateblue\": [123,104,238,1],\n \"mediumspringgreen\": [0,250,154,1], \"mediumturquoise\": [72,209,204,1],\n \"mediumvioletred\": [199,21,133,1], \"midnightblue\": [25,25,112,1],\n \"mintcream\": [245,255,250,1], \"mistyrose\": [255,228,225,1],\n \"moccasin\": [255,228,181,1], \"navajowhite\": [255,222,173,1],\n \"navy\": [0,0,128,1], \"oldlace\": [253,245,230,1],\n \"olive\": [128,128,0,1], \"olivedrab\": [107,142,35,1],\n \"orange\": [255,165,0,1], \"orangered\": [255,69,0,1],\n \"orchid\": [218,112,214,1], \"palegoldenrod\": [238,232,170,1],\n \"palegreen\": [152,251,152,1], \"paleturquoise\": [175,238,238,1],\n \"palevioletred\": [219,112,147,1], \"papayawhip\": [255,239,213,1],\n \"peachpuff\": [255,218,185,1], \"peru\": [205,133,63,1],\n \"pink\": [255,192,203,1], \"plum\": [221,160,221,1],\n \"powderblue\": [176,224,230,1], \"purple\": [128,0,128,1],\n \"rebeccapurple\": [102,51,153,1],\n \"red\": [255,0,0,1], \"rosybrown\": [188,143,143,1],\n \"royalblue\": [65,105,225,1], \"saddlebrown\": [139,69,19,1],\n \"salmon\": [250,128,114,1], \"sandybrown\": [244,164,96,1],\n \"seagreen\": [46,139,87,1], \"seashell\": [255,245,238,1],\n \"sienna\": [160,82,45,1], \"silver\": [192,192,192,1],\n \"skyblue\": [135,206,235,1], \"slateblue\": [106,90,205,1],\n \"slategray\": [112,128,144,1], \"slategrey\": [112,128,144,1],\n \"snow\": [255,250,250,1], \"springgreen\": [0,255,127,1],\n \"steelblue\": [70,130,180,1], \"tan\": [210,180,140,1],\n \"teal\": [0,128,128,1], \"thistle\": [216,191,216,1],\n \"tomato\": [255,99,71,1], \"turquoise\": [64,224,208,1],\n \"violet\": [238,130,238,1], \"wheat\": [245,222,179,1],\n \"white\": [255,255,255,1], \"whitesmoke\": [245,245,245,1],\n \"yellow\": [255,255,0,1], \"yellowgreen\": [154,205,50,1]}\n\nfunction clamp_css_byte(i) { // Clamp to integer 0 .. 255.\n i = Math.round(i); // Seems to be what Chrome does (vs truncation).\n return i < 0 ? 0 : i > 255 ? 255 : i;\n}\n\nfunction clamp_css_float(f) { // Clamp to float 0.0 .. 1.0.\n return f < 0 ? 0 : f > 1 ? 1 : f;\n}\n\nfunction parse_css_int(str) { // int or percentage.\n if (str[str.length - 1] === '%')\n return clamp_css_byte(parseFloat(str) / 100 * 255);\n return clamp_css_byte(parseInt(str));\n}\n\nfunction parse_css_float(str) { // float or percentage.\n if (str[str.length - 1] === '%')\n return clamp_css_float(parseFloat(str) / 100);\n return clamp_css_float(parseFloat(str));\n}\n\nfunction css_hue_to_rgb(m1, m2, h) {\n if (h < 0) h += 1;\n else if (h > 1) h -= 1;\n\n if (h * 6 < 1) return m1 + (m2 - m1) * h * 6;\n if (h * 2 < 1) return m2;\n if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6;\n return m1;\n}\n\nfunction parseCSSColor(css_str) {\n // Remove all whitespace, not compliant, but should just be more accepting.\n var str = css_str.replace(/ /g, '').toLowerCase();\n\n // Color keywords (and transparent) lookup.\n if (str in kCSSColorTable) return kCSSColorTable[str].slice(); // dup.\n\n // #abc and #abc123 syntax.\n if (str[0] === '#') {\n if (str.length === 4) {\n var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.\n if (!(iv >= 0 && iv <= 0xfff)) return null; // Covers NaN.\n return [((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),\n (iv & 0xf0) | ((iv & 0xf0) >> 4),\n (iv & 0xf) | ((iv & 0xf) << 4),\n 1];\n } else if (str.length === 7) {\n var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.\n if (!(iv >= 0 && iv <= 0xffffff)) return null; // Covers NaN.\n return [(iv & 0xff0000) >> 16,\n (iv & 0xff00) >> 8,\n iv & 0xff,\n 1];\n }\n\n return null;\n }\n\n var op = str.indexOf('('), ep = str.indexOf(')');\n if (op !== -1 && ep + 1 === str.length) {\n var fname = str.substr(0, op);\n var params = str.substr(op+1, ep-(op+1)).split(',');\n var alpha = 1; // To allow case fallthrough.\n switch (fname) {\n case 'rgba':\n if (params.length !== 4) return null;\n alpha = parse_css_float(params.pop());\n // Fall through.\n case 'rgb':\n if (params.length !== 3) return null;\n return [parse_css_int(params[0]),\n parse_css_int(params[1]),\n parse_css_int(params[2]),\n alpha];\n case 'hsla':\n if (params.length !== 4) return null;\n alpha = parse_css_float(params.pop());\n // Fall through.\n case 'hsl':\n if (params.length !== 3) return null;\n var h = (((parseFloat(params[0]) % 360) + 360) % 360) / 360; // 0 .. 1\n // NOTE(deanm): According to the CSS spec s/l should only be\n // percentages, but we don't bother and let float or percentage.\n var s = parse_css_float(params[1]);\n var l = parse_css_float(params[2]);\n var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;\n var m1 = l * 2 - m2;\n return [clamp_css_byte(css_hue_to_rgb(m1, m2, h+1/3) * 255),\n clamp_css_byte(css_hue_to_rgb(m1, m2, h) * 255),\n clamp_css_byte(css_hue_to_rgb(m1, m2, h-1/3) * 255),\n alpha];\n default:\n return null;\n }\n }\n\n return null;\n}\n\ntry { exports.parseCSSColor = parseCSSColor } catch(e) { }\n","// @flow\n\nimport {parseCSSColor} from 'csscolorparser';\n\n/**\n * An RGBA color value. Create instances from color strings using the static\n * method `Color.parse`. The constructor accepts RGB channel values in the range\n * `[0, 1]`, premultiplied by A.\n *\n * @param {number} r The red channel.\n * @param {number} g The green channel.\n * @param {number} b The blue channel.\n * @param {number} a The alpha channel.\n * @private\n */\nclass Color {\n r: number;\n g: number;\n b: number;\n a: number;\n\n constructor(r: number, g: number, b: number, a: number = 1) {\n this.r = r;\n this.g = g;\n this.b = b;\n this.a = a;\n }\n\n static black: Color;\n static white: Color;\n static transparent: Color;\n static red: Color;\n static blue: Color;\n\n /**\n * Parses valid CSS color strings and returns a `Color` instance.\n * @returns A `Color` instance, or `undefined` if the input is not a valid color string.\n */\n static parse(input?: string | Color | null): Color | void {\n if (!input) {\n return undefined;\n }\n\n if (input instanceof Color) {\n return input;\n }\n\n if (typeof input !== 'string') {\n return undefined;\n }\n\n const rgba = parseCSSColor(input);\n if (!rgba) {\n return undefined;\n }\n\n return new Color(\n rgba[0] / 255 * rgba[3],\n rgba[1] / 255 * rgba[3],\n rgba[2] / 255 * rgba[3],\n rgba[3]\n );\n }\n\n /**\n * Returns an RGBA string representing the color value.\n *\n * @returns An RGBA string.\n * @example\n * var purple = new Color.parse('purple');\n * purple.toString; // = \"rgba(128,0,128,1)\"\n * var translucentGreen = new Color.parse('rgba(26, 207, 26, .73)');\n * translucentGreen.toString(); // = \"rgba(26,207,26,0.73)\"\n */\n toString(): string {\n const [r, g, b, a] = this.toArray();\n return `rgba(${Math.round(r)},${Math.round(g)},${Math.round(b)},${a})`;\n }\n\n 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);\nColor.blue = new Color(0, 0, 1, 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<Intl$Collator>\n};\n\ndeclare class Intl$Collator {\n constructor (\n locales?: string | string[],\n options?: CollatorOptions\n ): Intl$Collator;\n\n static (\n locales?: string | string[],\n options?: CollatorOptions\n ): Intl$Collator;\n\n compare (a: string, b: string): number;\n\n resolvedOptions(): any;\n}\n\ntype CollatorOptions = {\n localeMatcher?: 'lookup' | 'best fit',\n usage?: 'sort' | 'search',\n sensitivity?: 'base' | 'accent' | 'case' | 'variant',\n ignorePunctuation?: boolean,\n numeric?: boolean,\n caseFirst?: 'upper' | 'lower' | 'false'\n}\n\nexport default class Collator {\n locale: string | null;\n sensitivity: 'base' | 'accent' | 'case' | 'variant';\n collator: Intl$Collator;\n\n constructor(caseSensitive: boolean, diacriticSensitive: boolean, locale: string | null) {\n if (caseSensitive)\n this.sensitivity = diacriticSensitive ? 'variant' : 'case';\n else\n this.sensitivity = diacriticSensitive ? 'accent' : 'base';\n\n this.locale = locale;\n this.collator = new Intl.Collator(this.locale ? this.locale : [],\n {sensitivity: this.sensitivity, usage: 'search'});\n }\n\n compare(lhs: string, rhs: string): number {\n return this.collator.compare(lhs, rhs);\n }\n\n resolvedLocale(): string {\n // We create a Collator without \"usage: search\" because we don't want\n // the search options encoded in our result (e.g. \"en-u-co-search\")\n return new Intl.Collator(this.locale ? this.locale : [])\n .resolvedOptions().locale;\n }\n}\n","// @flow\nimport type Color from '../../util/color';\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<FormattedSection>;\n\n constructor(sections: Array<FormattedSection>) {\n this.sections = sections;\n }\n\n static fromString(unformatted: string): Formatted {\n return new Formatted([new FormattedSection(unformatted, null, null, null, null)]);\n }\n\n isEmpty(): boolean {\n if (this.sections.length === 0) return true;\n return !this.sections.some(section => section.text.length !== 0 ||\n (section.image && section.image.name.length !== 0));\n }\n\n static factory(text: Formatted | string): Formatted {\n if (text instanceof Formatted) {\n return text;\n } else {\n return Formatted.fromString(text);\n }\n }\n\n toString(): string {\n if (this.sections.length === 0) return '';\n return this.sections.map(section => section.text).join('');\n }\n\n serialize(): Array<mixed> {\n const serialized: Array<mixed> = [\"format\"];\n for (const section of this.sections) {\n if (section.image) {\n serialized.push([\"image\", section.image.name]);\n continue;\n }\n serialized.push(section.text);\n const options: { [key: string]: mixed } = {};\n if (section.fontStack) {\n options[\"text-font\"] = [\"literal\", section.fontStack.split(',')];\n }\n if (section.scale) {\n options[\"font-scale\"] = section.scale;\n }\n if (section.textColor) {\n options[\"text-color\"] = ([\"rgba\"]: Array<mixed>).concat(section.textColor.toArray());\n }\n serialized.push(options);\n }\n return serialized;\n }\n}\n","// @flow\n\nexport type ResolvedImageOptions = {\n name: string,\n available: boolean\n};\n\nexport default class ResolvedImage {\n name: string;\n available: boolean;\n\n constructor(options: ResolvedImageOptions) {\n this.name = options.name;\n this.available = options.available;\n }\n\n toString(): string {\n return this.name;\n }\n\n static fromString(name: string): ResolvedImage | null {\n if (!name) return null; // treat empty values as no image\n return new ResolvedImage({name, available: false});\n }\n\n serialize(): Array<string> {\n return [\"image\", this.name];\n }\n}\n","// @flow\n\nimport assert from 'assert';\n\nimport Color from '../util/color';\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<Value> | { +[string]: Value }\n\nexport function isValue(mixed: mixed): boolean {\n if (mixed === null) {\n return true;\n } else if (typeof mixed === 'string') {\n return true;\n } else if (typeof mixed === 'boolean') {\n return true;\n } else if (typeof mixed === 'number') {\n return true;\n } else if (mixed instanceof Color) {\n return true;\n } else if (mixed instanceof Collator) {\n return true;\n } else if (mixed instanceof Formatted) {\n return true;\n } else if (mixed instanceof ResolvedImage) {\n return true;\n } else if (Array.isArray(mixed)) {\n for (const item of mixed) {\n if (!isValue(item)) {\n return false;\n }\n }\n return true;\n } else if (typeof mixed === 'object') {\n for (const key in mixed) {\n if (!isValue(mixed[key])) {\n return false;\n }\n }\n return true;\n } else {\n return false;\n }\n}\n\nexport function typeOf(value: Value): Type {\n if (value === null) {\n return NullType;\n } else if (typeof value === 'string') {\n return StringType;\n } else if (typeof value === 'boolean') {\n return BooleanType;\n } else if (typeof value === 'number') {\n return NumberType;\n } else if (value instanceof Color) {\n return ColorType;\n } else if (value instanceof Collator) {\n return CollatorType;\n } else if (value instanceof Formatted) {\n return FormattedType;\n } else if (value instanceof ResolvedImage) {\n return ResolvedImageType;\n } else if (Array.isArray(value)) {\n const length = value.length;\n let itemType: Type | typeof undefined;\n\n for (const item of value) {\n const t = typeOf(item);\n if (!itemType) {\n itemType = t;\n } else if (itemType === t) {\n continue;\n } else {\n itemType = ValueType;\n break;\n }\n }\n\n return array(itemType || ValueType, length);\n } else {\n assert(typeof value === 'object');\n return ObjectType;\n }\n}\n\nexport function toString(value: Value) {\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<mixed>, 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<mixed> {\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<Expression>;\n\n constructor(type: Type, args: Array<Expression>) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Expression {\n if (args.length < 2)\n return context.error(`Expected at least one argument.`);\n\n let i = 1;\n let type;\n\n const name: string = (args[0]: any);\n if (name === 'array') {\n let itemType;\n if (args.length > 2) {\n const type = args[1];\n if (typeof type !== 'string' || !(type in types) || type === 'object')\n return context.error('The item type argument of \"array\" must be one of string, number, boolean', 1);\n itemType = types[type];\n i++;\n } else {\n itemType = ValueType;\n }\n\n let N;\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<mixed> {\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<FormattedSectionExpression>;\n\n constructor(sections: Array<FormattedSectionExpression>) {\n this.type = FormattedType;\n this.sections = sections;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Expression {\n if (args.length < 2) {\n return context.error(`Expected at least one argument.`);\n }\n\n const firstArg = args[1];\n if (!Array.isArray(firstArg) && typeof firstArg === 'object') {\n return context.error(`First argument must be an image or text section.`);\n }\n\n const sections: Array<FormattedSectionExpression> = [];\n let nextTokenMayBeObject = false;\n for (let i = 1; i <= args.length - 1; ++i) {\n const arg = (args[i]: any);\n\n if (nextTokenMayBeObject && typeof arg === \"object\" && !Array.isArray(arg)) {\n nextTokenMayBeObject = false;\n\n let scale = null;\n if (arg['font-scale']) {\n scale = context.parse(arg['font-scale'], 1, NumberType);\n if (!scale) return null;\n }\n\n let font = null;\n if (arg['text-font']) {\n font = context.parse(arg['text-font'], 1, array(StringType));\n if (!font) return null;\n }\n\n let textColor = null;\n if (arg['text-color']) {\n textColor = context.parse(arg['text-color'], 1, ColorType);\n if (!textColor) return null;\n }\n\n const lastExpression = sections[sections.length - 1];\n lastExpression.scale = scale;\n lastExpression.font = font;\n lastExpression.textColor = textColor;\n } else {\n const content = context.parse(args[i], 1, ValueType);\n if (!content) return null;\n\n const kind = content.type.kind;\n if (kind !== 'string' && kind !== 'value' && kind !== 'null' && kind !== 'resolvedImage')\n return context.error(`Formatted text type must be 'string', 'value', 'image' or 'null'.`);\n\n nextTokenMayBeObject = true;\n sections.push({content, scale: null, font: null, textColor: null});\n }\n }\n\n return new FormatExpression(sections);\n }\n\n evaluate(ctx: EvaluationContext) {\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<mixed>, context: ParsingContext): ?Expression {\n if (args.length !== 2) {\n return context.error(`Expected two arguments.`);\n }\n\n const name = context.parse(args[1], 1, StringType);\n if (!name) return context.error(`No image name provided.`);\n\n return new ImageExpression(name);\n }\n\n evaluate(ctx: EvaluationContext) {\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<Expression>;\n\n constructor(type: Type, args: Array<Expression>) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Expression {\n if (args.length < 2)\n return context.error(`Expected at least one argument.`);\n\n const name: string = (args[0]: any);\n assert(types[name], name);\n\n if ((name === 'to-boolean' || name === 'to-string') && args.length !== 2)\n return context.error(`Expected one argument.`);\n\n const type = types[name];\n\n const parsed = [];\n for (let i = 1; i < args.length; i++) {\n const input = context.parse(args[i], i, ValueType);\n if (!input) return null;\n parsed.push(input);\n }\n\n return new Coercion(type, parsed);\n }\n\n evaluate(ctx: EvaluationContext) {\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<string>;\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<Type> | Varargs;\ntype Evaluate = (EvaluationContext, Array<Expression>) => Value;\ntype Definition = [Type, Signature, Evaluate] |\n {|type: Type, overloads: Array<[Signature, Evaluate]>|};\n\nclass CompoundExpression implements Expression {\n name: string;\n type: Type;\n _evaluate: Evaluate;\n args: Array<Expression>;\n\n static definitions: {[_: string]: Definition };\n\n constructor(name: string, type: Type, evaluate: Evaluate, args: Array<Expression>) {\n this.name = name;\n this.type = type;\n this._evaluate = evaluate;\n this.args = args;\n }\n\n evaluate(ctx: EvaluationContext) {\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<mixed> {\n return [this.name].concat(this.args.map(arg => arg.serialize()));\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext): ?Expression {\n const op: string = (args[0]: any);\n const definition = CompoundExpression.definitions[op];\n if (!definition) {\n return context.error(`Unknown expression \"${op}\". If you wanted a literal array, use [\"literal\", [...]].`, 0);\n }\n\n // Now check argument types against each signature\n const type = Array.isArray(definition) ?\n definition[0] : definition.type;\n\n const availableOverloads = Array.isArray(definition) ?\n [[definition[1], definition[2]]] :\n definition.overloads;\n\n const overloads = availableOverloads.filter(([signature]) => (\n !Array.isArray(signature) || // varags\n signature.length === args.length - 1 // correct param count\n ));\n\n let signatureContext: ParsingContext = (null: any);\n\n for (const [params, evaluate] of overloads) {\n // Use a fresh context for each attempted signature so that, if\n // we eventually succeed, we haven't polluted `context.errors`.\n signatureContext = new ParsingContext(context.registry, context.path, null, context.scope);\n\n // First parse all the args, potentially coercing to the\n // types expected by this overload.\n const parsedArgs: Array<Expression> = [];\n let argParseFailed = false;\n for (let i = 1; i < args.length; i++) {\n const arg = args[i];\n const expectedType = Array.isArray(params) ?\n params[i - 1] :\n params.type;\n\n const parsed = signatureContext.parse(arg, 1 + parsedArgs.length, expectedType);\n if (!parsed) {\n argParseFailed = true;\n break;\n }\n parsedArgs.push(parsed);\n }\n if (argParseFailed) {\n // Couldn't coerce args of this overload to expected type, move\n // on to next one.\n continue;\n }\n\n if (Array.isArray(params)) {\n if (params.length !== parsedArgs.length) {\n signatureContext.error(`Expected ${params.length} arguments, but found ${parsedArgs.length} instead.`);\n continue;\n }\n }\n\n for (let i = 0; i < parsedArgs.length; i++) {\n const expected = Array.isArray(params) ? params[i] : params.type;\n const arg = parsedArgs[i];\n signatureContext.concat(i + 1).checkSubtype(expected, arg.type);\n }\n\n if (signatureContext.errors.length === 0) {\n return new CompoundExpression(op, type, evaluate, parsedArgs);\n }\n }\n\n assert(!signatureContext || signatureContext.errors.length > 0);\n\n if (overloads.length === 1) {\n context.errors.push(...signatureContext.errors);\n } else {\n const expected = overloads.length ? overloads : availableOverloads;\n const signatures = expected\n .map(([params]) => stringifySignature(params))\n .join(' | ');\n\n const actualTypes = [];\n // For error message, re-parse arguments without trying to\n // apply any coercions\n for (let i = 1; i < args.length; i++) {\n const parsed = context.parse(args[i], 1 + actualTypes.length);\n if (!parsed) return null;\n actualTypes.push(toString(parsed.type));\n }\n context.error(`Expected arguments of type ${signatures}, but found (${actualTypes.join(', ')}) instead.`);\n }\n\n return null;\n }\n\n static register(\n registry: ExpressionRegistry,\n definitions: {[_: string]: Definition }\n ) {\n assert(!CompoundExpression.definitions);\n CompoundExpression.definitions = definitions;\n for (const name in definitions) {\n 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<mixed>, context: ParsingContext): ?Expression {\n if (args.length !== 2)\n return context.error(`Expected one argument.`);\n\n const options = (args[1]: any);\n if (typeof options !== \"object\" || Array.isArray(options))\n return context.error(`Collator options argument must be an object.`);\n\n const caseSensitive = context.parse(\n options['case-sensitive'] === undefined ? false : options['case-sensitive'], 1, BooleanType);\n if (!caseSensitive) return null;\n\n const diacriticSensitive = context.parse(\n options['diacritic-sensitive'] === undefined ? false : options['diacritic-sensitive'], 1, BooleanType);\n if (!diacriticSensitive) return null;\n\n let locale = null;\n if (options['locale']) {\n locale = context.parse(options['locale'], 1, StringType);\n if (!locale) return null;\n }\n\n return new CollatorExpression(caseSensitive, diacriticSensitive, locale);\n }\n\n evaluate(ctx: EvaluationContext) {\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<mixed>, 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<mixed> {\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<string>) {\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<mixed>, 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<number>;\n key: string;\n scope: Scope;\n errors: Array<ParsingError>;\n\n // The expected type of this expression. Provided only to allow Expression\n // implementations to infer argument types: Expression#parse() need not\n // check that the output type of the parsed expression matches\n // `expectedType`.\n expectedType: ?Type;\n\n constructor(\n registry: ExpressionRegistry,\n path: Array<number> = [],\n expectedType: ?Type,\n scope: Scope = new Scope(),\n errors: Array<ParsingError> = []\n ) {\n this.registry = registry;\n this.path = path;\n this.key = path.map(part => `[${part}]`).join('');\n this.scope = scope;\n this.errors = errors;\n this.expectedType = expectedType;\n }\n\n /**\n * @param expr the JSON expression to parse\n * @param index the optional argument index if this expression is an argument of a parent expression that's being parsed\n * @param options\n * @param options.omitTypeAnnotations set true to omit inferred type annotations. Caller beware: with this option set, the parsed expression's type will NOT satisfy `expectedType` if it would normally be wrapped in an inferred annotation.\n * @private\n */\n parse(\n expr: mixed,\n index?: number,\n expectedType?: ?Type,\n bindings?: Array<[string, Expression]>,\n options: {typeAnnotation?: 'assert' | 'coerce' | 'omit'} = {}\n ): ?Expression {\n if (index) {\n return this.concat(index, expectedType, bindings)._parse(expr, options);\n }\n return this._parse(expr, options);\n }\n\n _parse(expr: mixed, options: {typeAnnotation?: 'assert' | 'coerce' | 'omit'}): ?Expression {\n if (expr === null || typeof expr === 'string' || typeof expr === 'boolean' || typeof expr === 'number') {\n expr = ['literal', expr];\n }\n\n function annotate(parsed, 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<number>) {\n const key = `${this.key}${keys.map(k => `[${k}]`).join('')}`;\n this.errors.push(new ParsingError(key, error));\n }\n\n /**\n * Returns null if `t` is a subtype of `expected`; otherwise returns an\n * error message and also pushes it to `this.errors`.\n */\n checkSubtype(expected: Type, t: Type): ?string {\n const error = checkSubtype(expected, t);\n if (error) this.error(error);\n return error;\n }\n}\n\nexport default ParsingContext;\n\nfunction isConstant(expression: Expression) {\n if (expression instanceof Var) {\n return isConstant(expression.boundExpression);\n } else if (expression instanceof CompoundExpression && expression.name === 'error') {\n return false;\n } else if (expression instanceof CollatorExpression) {\n // Although the results of a Collator expression with fixed arguments\n // generally shouldn't change between executions, we can't serialize them\n // as constant expressions because results change based on environment.\n return false;\n } else if (expression instanceof Within) {\n return false;\n }\n\n const isTypeAnnotation = expression instanceof Coercion ||\n expression instanceof Assertion;\n\n let childrenConstant = true;\n expression.eachChild(child => {\n // We can _almost_ assume that if `expressions` children are constant,\n // they would already have been evaluated to Literal values when they\n // were parsed. Type annotations are the exception, because they might\n // have been inferred and added after a child was parsed.\n\n // So we recurse into isConstant() for the children of type annotations,\n // but otherwise simply check whether they are Literals.\n if (isTypeAnnotation) {\n childrenConstant = childrenConstant && isConstant(child);\n } else {\n childrenConstant = childrenConstant && child instanceof Literal;\n }\n });\n if (!childrenConstant) {\n return false;\n }\n\n return isFeatureConstant(expression) &&\n isGlobalPropertyConstant(expression, ['zoom', 'heatmap-density', 'line-progress', 'sky-radial-progress', 'accumulated', 'is-supported-script']);\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<number>, 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<number>;\n outputs: Array<Expression>;\n\n constructor(type: Type, input: Expression, stops: Stops) {\n this.type = type;\n this.input = input;\n\n this.labels = [];\n this.outputs = [];\n for (const [label, expression] of stops) {\n this.labels.push(label);\n this.outputs.push(expression);\n }\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext) {\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<number>, to: Array<number>, t: number): Array<number> {\n return from.map((d, i) => {\n return number(d, to[i], t);\n });\n}\n","// @flow\n\nimport Color from './color';\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<number>;\n outputs: Array<Expression>;\n\n constructor(type: Type, operator: 'interpolate' | 'interpolate-hcl' | 'interpolate-lab', interpolation: InterpolationType, input: Expression, stops: Stops) {\n this.type = type;\n this.operator = operator;\n this.interpolation = interpolation;\n this.input = input;\n\n this.labels = [];\n this.outputs = [];\n for (const [label, expression] of stops) {\n this.labels.push(label);\n this.outputs.push(expression);\n }\n }\n\n static interpolationFactor(interpolation: InterpolationType, input: number, lower: number, upper: number) {\n let t = 0;\n if (interpolation.name === 'exponential') {\n t = exponentialInterpolation(input, interpolation.base, lower, upper);\n } else if (interpolation.name === 'linear') {\n t = exponentialInterpolation(input, 1, lower, upper);\n } else if (interpolation.name === 'cubic-bezier') {\n const c = interpolation.controlPoints;\n const ub = new UnitBezier(c[0], c[1], c[2], c[3]);\n t = ub.solve(exponentialInterpolation(input, 1, lower, upper));\n }\n return t;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext) {\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<mixed> {\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<Expression>;\n\n constructor(type: Type, args: Array<Expression>) {\n this.type = type;\n this.args = args;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext) {\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<mixed>, 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<mixed>, 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<Value>);\n\n if (index < 0) {\n throw new RuntimeError(`Array index out of bounds: ${index} < 0.`);\n }\n\n if (index >= array.length) {\n throw new RuntimeError(`Array index out of bounds: ${index} > ${array.length - 1}.`);\n }\n\n if (index !== Math.floor(index)) {\n throw new RuntimeError(`Array index must be an integer, but found ${index} instead.`);\n }\n\n return array[index];\n }\n\n eachChild(fn: (_: Expression) => void) {\n fn(this.index);\n fn(this.input);\n }\n\n outputDefined() {\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<mixed>, 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<mixed>, 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<Expression>;\n otherwise: Expression;\n\n constructor(inputType: Type, outputType: Type, input: Expression, cases: Cases, outputs: Array<Expression>, otherwise: Expression) {\n this.inputType = inputType;\n this.type = outputType;\n this.input = input;\n this.cases = cases;\n this.outputs = outputs;\n this.otherwise = otherwise;\n }\n\n static parse(args: $ReadOnlyArray<mixed>, context: ParsingContext) {\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<mixed> {\n const serialized = [\"match\", this.input.serialize()];\n\n // Sort so serialization has an arbitrary defined order, even though\n // branch order doesn't affect evaluation\n const sortedLabels = Object.keys(this.cases).sort();\n\n // Group branches by unique match expression to support condensed\n // serializations of the form [case1, case2, ...] -> matchExpression\n const groupedByOutput: Array<[number, Array<number | string>]> = [];\n const outputLookup: {[index: number]: number} = {}; // lookup index into groupedByOutput for a given output expression\n for (const label of sortedLabels) {\n const outputIndex = outputLookup[this.cases[label]];\n if (outputIndex === undefined) {\n // First time seeing this output, add it to the end of the grouped list\n outputLookup[this.cases[label]] = groupedByOutput.length;\n groupedByOutput.push([this.cases[label], [label]]);\n } else {\n // We've seen this expression before, add the label to that output's group\n groupedByOutput[outputIndex][1].push(label);\n }\n }\n\n const coerceLabel = (label) => 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<mixed>, 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<mixed>, 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<mixed>, context: ParsingContext): ?Expression {\n if (args.length !== 3 && args.length !== 4)\n return context.error(`Expected two or three arguments.`);\n\n const op: ComparisonOperator = (args[0]: any);\n\n let lhs = context.parse(args[1], 1, ValueType);\n if (!lhs) return null;\n if (!isComparableType(op, lhs.type)) {\n return context.concat(1).error(`\"${op}\" comparisons are not supported for type '${toString(lhs.type)}'.`);\n }\n let rhs = context.parse(args[2], 2, ValueType);\n if (!rhs) return null;\n if (!isComparableType(op, rhs.type)) {\n return context.concat(2).error(`\"${op}\" comparisons are not supported for type '${toString(rhs.type)}'.`);\n }\n\n if (\n lhs.type.kind !== rhs.type.kind &&\n lhs.type.kind !== 'value' &&\n rhs.type.kind !== 'value'\n ) {\n return context.error(`Cannot compare types '${toString(lhs.type)}' and '${toString(rhs.type)}'.`);\n }\n\n if (isOrderComparison) {\n // typing rules specific to less/greater than operators\n if (lhs.type.kind === 'value' && rhs.type.kind !== 'value') {\n // (value, T)\n lhs = new Assertion(rhs.type, [lhs]);\n } else if (lhs.type.kind !== 'value' && rhs.type.kind === 'value') {\n // (T, value)\n rhs = new Assertion(lhs.type, [rhs]);\n }\n }\n\n let collator = null;\n if (args.length === 4) {\n if (\n lhs.type.kind !== 'string' &&\n rhs.type.kind !== 'string' &&\n lhs.type.kind !== 'value' &&\n rhs.type.kind !== 'value'\n ) {\n return context.error(`Cannot use collator to compare non-string types.`);\n }\n collator = context.parse(args[3], 3, CollatorType);\n if (!collator) return null;\n }\n\n return new Comparison(lhs, rhs, collator);\n }\n\n evaluate(ctx: EvaluationContext) {\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<Intl$NumberFormat>\n};\n\ndeclare class Intl$NumberFormat {\n constructor (\n locales?: string | string[],\n options?: NumberFormatOptions\n ): Intl$NumberFormat;\n\n static (\n locales?: string | string[],\n options?: NumberFormatOptions\n ): Intl$NumberFormat;\n\n format(a: number): string;\n\n resolvedOptions(): any;\n}\n\ntype NumberFormatOptions = {\n style?: 'decimal' | 'currency' | 'percent';\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<mixed>, context: ParsingContext): ?Expression {\n if (args.length !== 3)\n return context.error(`Expected two arguments.`);\n\n const number = context.parse(args[1], 1, NumberType);\n if (!number) return null;\n\n const options = (args[2]: any);\n if (typeof options !== \"object\" || Array.isArray(options))\n return context.error(`NumberFormat options argument must be an object.`);\n\n let locale = null;\n if (options['locale']) {\n locale = context.parse(options['locale'], 1, StringType);\n if (!locale) return null;\n }\n\n let currency = null;\n if (options['currency']) {\n currency = context.parse(options['currency'], 1, StringType);\n if (!currency) return null;\n }\n\n let 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<mixed>, 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 'sky-radial-progress': [\n NumberType,\n [],\n (ctx) => ctx.globals.skyRadialProgress || 0\n ],\n 'accumulated': [\n ValueType,\n [],\n (ctx) => ctx.globals.accumulated === undefined ? null : ctx.globals.accumulated\n ],\n '+': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => {\n let result = 0;\n for (const arg of args) {\n result += arg.evaluate(ctx);\n }\n return result;\n }\n ],\n '*': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => {\n let result = 1;\n for (const arg of args) {\n result *= arg.evaluate(ctx);\n }\n return result;\n }\n ],\n '-': {\n type: NumberType,\n overloads: [\n [\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) - b.evaluate(ctx)\n ], [\n [NumberType],\n (ctx, [a]) => -a.evaluate(ctx)\n ]\n ]\n },\n '/': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) / b.evaluate(ctx)\n ],\n '%': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [a, b]) => a.evaluate(ctx) % b.evaluate(ctx)\n ],\n 'ln2': [\n NumberType,\n [],\n () => Math.LN2\n ],\n 'pi': [\n NumberType,\n [],\n () => Math.PI\n ],\n 'e': [\n NumberType,\n [],\n () => Math.E\n ],\n '^': [\n NumberType,\n [NumberType, NumberType],\n (ctx, [b, e]) => Math.pow(b.evaluate(ctx), e.evaluate(ctx))\n ],\n 'sqrt': [\n NumberType,\n [NumberType],\n (ctx, [x]) => Math.sqrt(x.evaluate(ctx))\n ],\n 'log10': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN10\n ],\n 'ln': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx))\n ],\n 'log2': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.log(n.evaluate(ctx)) / Math.LN2\n ],\n 'sin': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.sin(n.evaluate(ctx))\n ],\n 'cos': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.cos(n.evaluate(ctx))\n ],\n 'tan': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.tan(n.evaluate(ctx))\n ],\n 'asin': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.asin(n.evaluate(ctx))\n ],\n 'acos': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.acos(n.evaluate(ctx))\n ],\n 'atan': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.atan(n.evaluate(ctx))\n ],\n 'min': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => Math.min(...args.map(arg => arg.evaluate(ctx)))\n ],\n 'max': [\n NumberType,\n varargs(NumberType),\n (ctx, args) => Math.max(...args.map(arg => arg.evaluate(ctx)))\n ],\n 'abs': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.abs(n.evaluate(ctx))\n ],\n 'round': [\n NumberType,\n [NumberType],\n (ctx, [n]) => {\n const v = n.evaluate(ctx);\n // Javascript's Math.round() rounds towards +Infinity for halfway\n // values, even when they're negative. It's more common to round\n // away from 0 (e.g., this is what python and C++ do)\n return v < 0 ? -Math.round(-v) : Math.round(v);\n }\n ],\n 'floor': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.floor(n.evaluate(ctx))\n ],\n 'ceil': [\n NumberType,\n [NumberType],\n (ctx, [n]) => Math.ceil(n.evaluate(ctx))\n ],\n 'filter-==': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => ctx.properties()[(k: any).value] === (v: any).value\n ],\n 'filter-id-==': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => ctx.id() === (v: any).value\n ],\n 'filter-type-==': [\n BooleanType,\n [StringType],\n (ctx, [v]) => ctx.geometryType() === (v: any).value\n ],\n 'filter-<': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a < b;\n }\n ],\n 'filter-id-<': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a < b;\n }\n ],\n 'filter->': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a > b;\n }\n ],\n 'filter-id->': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a > b;\n }\n ],\n 'filter-<=': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a <= b;\n }\n ],\n 'filter-id-<=': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a <= b;\n }\n ],\n 'filter->=': [\n BooleanType,\n [StringType, ValueType],\n (ctx, [k, v]) => {\n const a = ctx.properties()[(k: any).value];\n const b = (v: any).value;\n return typeof a === typeof b && a >= b;\n }\n ],\n 'filter-id->=': [\n BooleanType,\n [ValueType],\n (ctx, [v]) => {\n const a = ctx.id();\n const b = (v: any).value;\n return typeof a === typeof b && a >= b;\n }\n ],\n 'filter-has': [\n BooleanType,\n [ValueType],\n (ctx, [k]) => (k: any).value in ctx.properties()\n ],\n 'filter-has-id': [\n BooleanType,\n [],\n (ctx) => (ctx.id() !== null && ctx.id() !== undefined)\n ],\n 'filter-type-in': [\n BooleanType,\n [array(StringType)],\n (ctx, [v]) => (v: any).value.indexOf(ctx.geometryType()) >= 0\n ],\n 'filter-id-in': [\n BooleanType,\n [array(ValueType)],\n (ctx, [v]) => (v: any).value.indexOf(ctx.id()) >= 0\n ],\n 'filter-in-small': [\n BooleanType,\n [StringType, array(ValueType)],\n // assumes v is an array literal\n (ctx, [k, v]) => (v: any).value.indexOf(ctx.properties()[(k: any).value]) >= 0\n ],\n 'filter-in-large': [\n BooleanType,\n [StringType, array(ValueType)],\n // assumes v is a array literal with values sorted in ascending order and of a single type\n (ctx, [k, v]) => binarySearch(ctx.properties()[(k: any).value], (v: any).value, 0, (v: any).value.length - 1)\n ],\n 'all': {\n type: BooleanType,\n overloads: [\n [\n [BooleanType, BooleanType],\n (ctx, [a, b]) => a.evaluate(ctx) && b.evaluate(ctx)\n ],\n [\n varargs(BooleanType),\n (ctx, args) => {\n for (const arg of args) {\n if (!arg.evaluate(ctx))\n return false;\n }\n return true;\n }\n ]\n ]\n },\n 'any': {\n type: BooleanType,\n overloads: [\n [\n [BooleanType, BooleanType],\n (ctx, [a, b]) => a.evaluate(ctx) || b.evaluate(ctx)\n ],\n [\n varargs(BooleanType),\n (ctx, args) => {\n for (const arg of args) {\n if (arg.evaluate(ctx))\n return true;\n }\n return false;\n }\n ]\n ]\n },\n '!': [\n BooleanType,\n [BooleanType],\n (ctx, [b]) => !b.evaluate(ctx)\n ],\n 'is-supported-script': [\n BooleanType,\n [StringType],\n // At parse time this will always return true, so we need to exclude this expression with isGlobalPropertyConstant\n (ctx, [s]) => {\n const isSupportedScript = ctx.globals && ctx.globals.isSupportedScript;\n if (isSupportedScript) {\n return isSupportedScript(s.evaluate(ctx));\n }\n return true;\n }\n ],\n 'upcase': [\n StringType,\n [StringType],\n (ctx, [s]) => s.evaluate(ctx).toUpperCase()\n ],\n 'downcase': [\n StringType,\n [StringType],\n (ctx, [s]) => s.evaluate(ctx).toLowerCase()\n ],\n 'concat': [\n StringType,\n varargs(ValueType),\n (ctx, args) => args.map(arg => valueToString(arg.evaluate(ctx))).join('')\n ],\n 'resolved-locale': [\n StringType,\n [CollatorType],\n (ctx, [collator]) => collator.evaluate(ctx).resolvedLocale()\n ]\n});\n\nexport default expressions;\n","// @flow\n\n/**\n * A type used for returning and propagating errors. The first element of the union\n * represents success and contains a value, and the second represents an error and\n * contains an error value.\n * @private\n */\nexport type Result<T, E> =\n | {| result: 'success', value: T |}\n | {| result: 'error', value: E |};\n\nexport function success<T, E>(value: T): Result<T, E> {\n return {result: 'success', value};\n}\n\nexport function error<T, E>(value: E): Result<T, E> {\n return {result: 'error', value};\n}\n","// @flow\n\nimport type {StylePropertySpecification} from '../style-spec';\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<Array<Point>>\n};\n\nexport type FeatureState = {[_: string]: any};\n\nexport type GlobalProperties = $ReadOnly<{\n zoom: number,\n heatmapDensity?: number,\n lineProgress?: number,\n skyRadialProgress?: number,\n isSupportedScript?: (_: string) => boolean,\n accumulated?: Value\n}>;\n\nexport class StyleExpression {\n expression: Expression;\n\n _evaluator: EvaluationContext;\n _defaultValue: Value;\n _warningHistory: {[key: string]: boolean};\n _enumValues: ?{[_: string]: any};\n\n constructor(expression: Expression, propertySpec: ?StylePropertySpecification) {\n this.expression = expression;\n this._warningHistory = {};\n this._evaluator = new EvaluationContext();\n this._defaultValue = propertySpec ? getDefaultValue(propertySpec) : null;\n this._enumValues = propertySpec && propertySpec.type === 'enum' ? propertySpec.values : null;\n }\n\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection): 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<string>, 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<StyleExpression, Array<ParsingError>> {\n const parser = new ParsingContext(definitions, [], propertySpec ? getExpectedType(propertySpec) : undefined);\n\n // For string-valued properties, coerce to string at the top level rather than asserting.\n const parsed = parser.parse(expression, undefined, undefined, undefined,\n propertySpec && propertySpec.type === 'string' ? {typeAnnotation: 'coerce'} : undefined);\n\n if (!parsed) {\n assert(parser.errors.length > 0);\n return error(parser.errors);\n }\n\n return success(new StyleExpression(parsed, propertySpec));\n}\n\nexport class ZoomConstantExpression<Kind: EvaluationKind> {\n kind: Kind;\n isStateDependent: boolean;\n _styleExpression: StyleExpression;\n\n constructor(kind: Kind, expression: StyleExpression) {\n this.kind = kind;\n this._styleExpression = expression;\n this.isStateDependent = kind !== ('constant': EvaluationKind) && !isConstant.isStateConstant(expression.expression);\n }\n\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n}\n\nexport class ZoomDependentExpression<Kind: EvaluationKind> {\n kind: Kind;\n zoomStops: Array<number>;\n isStateDependent: boolean;\n\n _styleExpression: StyleExpression;\n interpolationType: ?InterpolationType;\n\n constructor(kind: Kind, expression: StyleExpression, zoomStops: Array<number>, interpolationType?: InterpolationType) {\n this.kind = kind;\n this.zoomStops = zoomStops;\n this._styleExpression = expression;\n this.isStateDependent = kind !== ('camera': EvaluationKind) && !isConstant.isStateConstant(expression.expression);\n this.interpolationType = interpolationType;\n }\n\n evaluateWithoutErrorHandling(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluateWithoutErrorHandling(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n\n evaluate(globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection): any {\n return this._styleExpression.evaluate(globals, feature, featureState, canonical, availableImages, formattedSection);\n }\n\n interpolationFactor(input: number, lower: number, upper: number): number {\n if (this.interpolationType) {\n return Interpolate.interpolationFactor(this.interpolationType, input, lower, upper);\n } else {\n return 0;\n }\n }\n}\n\nexport type ConstantExpression = {\n kind: 'constant',\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>) => any,\n}\n\nexport type SourceExpression = {\n kind: 'source',\n isStateDependent: boolean,\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection) => any,\n};\n\nexport type CameraExpression = {\n kind: 'camera',\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>) => any,\n +interpolationFactor: (input: number, lower: number, upper: number) => number,\n zoomStops: Array<number>,\n interpolationType: ?InterpolationType\n};\n\nexport type CompositeExpression = {\n kind: 'composite',\n isStateDependent: boolean,\n +evaluate: (globals: GlobalProperties, feature?: Feature, featureState?: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>, formattedSection?: FormattedSection) => any,\n +interpolationFactor: (input: number, lower: number, upper: number) => number,\n zoomStops: Array<number>,\n interpolationType: ?InterpolationType\n};\n\nexport type StylePropertyExpression =\n | ConstantExpression\n | SourceExpression\n | CameraExpression\n | CompositeExpression;\n\nexport function createPropertyExpression(expression: mixed, propertySpec: StylePropertySpecification): Result<StylePropertyExpression, Array<ParsingError>> {\n expression = createExpression(expression, propertySpec);\n if (expression.result === 'error') {\n return expression;\n }\n\n const parsed = expression.value.expression;\n\n const isFeatureConstant = isConstant.isFeatureConstant(parsed);\n if (!isFeatureConstant && !supportsPropertyExpression(propertySpec)) {\n return error([new ParsingError('', 'data expressions not supported')]);\n }\n\n const isZoomConstant = isConstant.isGlobalPropertyConstant(parsed, ['zoom']);\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<T> {\n _parameters: PropertyValueSpecification<T>;\n _specification: StylePropertySpecification;\n\n kind: EvaluationKind;\n evaluate: (globals: GlobalProperties, feature?: Feature) => any;\n interpolationFactor: ?(input: number, lower: number, upper: number) => number;\n zoomStops: ?Array<number>;\n\n constructor(parameters: PropertyValueSpecification<T>, specification: StylePropertySpecification) {\n this._parameters = parameters;\n this._specification = specification;\n extend(this, createFunction(this._parameters, this._specification));\n }\n\n static deserialize(serialized: {_parameters: PropertyValueSpecification<T>, _specification: StylePropertySpecification}) {\n return ((new StylePropertyFunction(serialized._parameters, serialized._specification)): StylePropertyFunction<T>);\n }\n\n static serialize(input: StylePropertyFunction<T>) {\n return {\n _parameters: input._parameters,\n _specification: input._specification\n };\n }\n}\n\nexport function normalizePropertyExpression<T>(value: PropertyValueSpecification<T>, specification: StylePropertySpecification): StylePropertyExpression {\n if (isFunction(value)) {\n return (new StylePropertyFunction(value, specification): any);\n\n } else if (isExpression(value)) {\n const expression = createPropertyExpression(value, specification);\n if (expression.result === 'error') {\n // this should have been caught in validation\n throw new Error(expression.value.map(err => `${err.key}: ${err.message}`).join(', '));\n }\n return expression.value;\n\n } else {\n let constant: any = value;\n if (typeof value === 'string' && specification.type === 'color') {\n constant = Color.parse(value);\n }\n return {\n kind: 'constant',\n evaluate: () => constant\n };\n }\n}\n\n// Zoom-dependent expressions may only use [\"zoom\"] as the input to a top-level \"step\" or \"interpolate\"\n// expression (collectively referred to as a \"curve\"). The curve may be wrapped in one or more \"let\" or\n// \"coalesce\" expressions.\nfunction findZoomCurve(expression: Expression): Step | Interpolate | ParsingError | null {\n let result = null;\n if (expression instanceof Let) {\n result = findZoomCurve(expression.result);\n\n } else if (expression instanceof Coalesce) {\n for (const arg of expression.args) {\n result = findZoomCurve(arg);\n if (result) {\n break;\n }\n }\n\n } else if ((expression instanceof Step || expression instanceof Interpolate) &&\n expression.input instanceof CompoundExpression &&\n expression.input.name === 'zoom') {\n\n result = expression;\n }\n\n if (result instanceof ParsingError) {\n return result;\n }\n\n expression.eachChild((child) => {\n const childResult = findZoomCurve(child);\n if (childResult instanceof ParsingError) {\n result = childResult;\n } else if (!result && childResult) {\n result = new ParsingError('', '\"zoom\" expression may only be used as input to a top-level \"step\" or \"interpolate\" expression.');\n } else if (result && childResult && result !== childResult) {\n result = new ParsingError('', 'Only one zoom-based \"step\" or \"interpolate\" subexpression may be used in an expression.');\n }\n });\n\n return result;\n}\n\nimport {ColorType, StringType, NumberType, BooleanType, ValueType, FormattedType, ResolvedImageType, array} from './types';\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 \"minimum\": arraySpec.minimum,\n \"maximum\": arraySpec.maximum\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) {\n let specMin = valueSpec.minimum;\n if (getType(valueSpec.minimum) === 'array') {\n const i = options.arrayIndex;\n specMin = valueSpec.minimum[i];\n }\n if (value < specMin) {\n return [new ValidationError(key, value, `${value} is less than the minimum value ${specMin}`)];\n }\n }\n\n if ('maximum' in valueSpec) {\n let specMax = valueSpec.maximum;\n if (getType(valueSpec.maximum) === 'array') {\n const i = options.arrayIndex;\n specMax = valueSpec.maximum[i];\n }\n if (value > specMax) {\n return [new ValidationError(key, value, `${value} is greater than the maximum value ${specMax}`)];\n }\n }\n\n return [];\n}\n","\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<ValidationError> {\n const expression = (options.expressionContext === 'property' ? createPropertyExpression : createExpression)(deepUnbundle(options.value), options.valueSpec);\n if (expression.result === 'error') {\n return expression.value.map((error) => {\n return new ValidationError(`${options.key}${error.key}`, options.value, error.message);\n });\n }\n\n const expressionObj = (expression.value: any).expression || (expression.value: any)._styleExpression.expression;\n\n if (options.expressionContext === 'property' && (options.propertyKey === 'text-font') &&\n !expressionObj.outputDefined()) {\n return [new ValidationError(options.key, options.value, `Invalid data expression for \"${options.propertyKey}\". Output values must be contained as literals within the expression.`)];\n }\n\n if (options.expressionContext === 'property' && options.propertyType === 'layout' &&\n (!isStateConstant(expressionObj))) {\n return [new ValidationError(options.key, options.value, '\"feature-state\" data expressions are not supported with layout properties.')];\n }\n\n if (options.expressionContext === 'filter' && !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<any>): mixed {\n if (!filter) return true;\n const op = filter[0];\n if (filter.length <= 1) return (op !== 'any');\n const converted =\n op === '==' ? convertComparisonOp(filter[1], filter[2], '==') :\n op === '!=' ? convertNegation(convertComparisonOp(filter[1], filter[2], '==')) :\n op === '<' ||\n op === '>' ||\n op === '<=' ||\n op === '>=' ? convertComparisonOp(filter[1], filter[2], op) :\n op === 'any' ? convertDisjunctionOp(filter.slice(1)) :\n op === 'all' ? ['all'].concat(filter.slice(1).map(convertFilter)) :\n op === 'none' ? ['all'].concat(filter.slice(1).map(convertFilter).map(convertNegation)) :\n op === 'in' ? convertInOp(filter[1], filter.slice(2)) :\n op === '!in' ? convertNegation(convertInOp(filter[1], filter.slice(2))) :\n op === 'has' ? convertHasOp(filter[1]) :\n op === '!has' ? convertNegation(convertHasOp(filter[1])) :\n op === 'within' ? filter :\n true;\n return converted;\n}\n\nfunction convertComparisonOp(property: string, value: any, op: string) {\n switch (property) {\n case '$type':\n return [`filter-type-${op}`, value];\n case '$id':\n return [`filter-id-${op}`, value];\n default:\n return [`filter-${op}`, property, value];\n }\n}\n\nfunction convertDisjunctionOp(filters: Array<Array<any>>) {\n return ['any'].concat(filters.map(convertFilter));\n}\n\nfunction convertInOp(property: string, values: Array<any>) {\n if (values.length === 0) { return false; }\n switch (property) {\n case '$type':\n return [`filter-type-in`, ['literal', values]];\n case '$id':\n return [`filter-id-in`, ['literal', values]];\n default:\n if (values.length > 200 && !values.some(v => typeof v !== typeof values[0])) {\n return ['filter-in-large', property, ['literal', values.sort(compare)]];\n } else {\n return ['filter-in-small', property, ['literal', values]];\n }\n }\n}\n\nfunction convertHasOp(property: string) {\n switch (property) {\n case '$type':\n return true;\n case '$id':\n return [`filter-has-id`];\n default:\n return [`filter-has`, property];\n }\n}\n\nfunction convertNegation(filter: mixed) {\n return ['!', filter];\n}\n","\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' || type === 'sky')) {\n if (!layer.source) {\n errors.push(new ValidationError(key, layer, 'missing required property \"source\"'));\n } else {\n const source = style.sources && style.sources[layer.source];\n const sourceType = source && unbundle(source.type);\n if (!source) {\n errors.push(new ValidationError(key, layer.source, `source \"${layer.source}\" not found`));\n } else if (sourceType === 'vector' && type === 'raster') {\n errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a raster source`));\n } else if (sourceType === 'raster' && type !== 'raster') {\n errors.push(new ValidationError(key, layer.source, `layer \"${layer.id}\" requires a vector source`));\n } else if (sourceType === 'vector' && !layer['source-layer']) {\n errors.push(new ValidationError(key, layer, `layer \"${layer.id}\" must specify a \"source-layer\"`));\n } else if (sourceType === 'raster-dem' && type !== 'hillshade') {\n errors.push(new ValidationError(key, layer.source, 'raster-dem source can only be used with layer type \\'hillshade\\'.'));\n } else if (type === 'line' && layer.paint && layer.paint['line-gradient'] &&\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 ValidationError from '../error/validation_error';\nimport validate from './validate';\nimport getType from '../util/get_type';\nimport {unbundle} from '../util/unbundle_jsonlint';\n\nexport default function validateTerrain(options) {\n const terrain = options.value;\n const key = options.key;\n const style = options.style;\n const styleSpec = options.styleSpec;\n const terrainSpec = styleSpec.terrain;\n let errors = [];\n\n const rootType = getType(terrain);\n if (terrain === undefined) {\n return errors;\n } else if (rootType !== 'object') {\n errors = errors.concat([new ValidationError('terrain', terrain, `object expected, ${rootType} found`)]);\n return errors;\n }\n\n for (const key in terrain) {\n const transitionMatch = key.match(/^(.*)-transition$/);\n\n if (transitionMatch && terrainSpec[transitionMatch[1]] && terrainSpec[transitionMatch[1]].transition) {\n errors = errors.concat(validate({\n key,\n value: terrain[key],\n valueSpec: styleSpec.transition,\n style,\n styleSpec\n }));\n } else if (terrainSpec[key]) {\n errors = errors.concat(validate({\n key,\n value: terrain[key],\n valueSpec: terrainSpec[key],\n style,\n styleSpec\n }));\n } else {\n errors = errors.concat([new ValidationError(key, terrain[key], `unknown property \"${key}\"`)]);\n }\n }\n\n if (!terrain.source) {\n errors.push(new ValidationError(key, terrain, `terrain is missing required property \"source\"`));\n } else {\n const source = style.sources && style.sources[terrain.source];\n const sourceType = source && unbundle(source.type);\n if (!source) {\n errors.push(new ValidationError(key, terrain.source, `source \"${terrain.source}\" not found`));\n } else if (sourceType !== 'raster-dem') {\n errors.push(new ValidationError(key, terrain.source, `terrain cannot be used with a source of type ${sourceType}, it only be used with a \"raster-dem\" source type`));\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 validateTerrain from './validate_terrain';\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 'terrain': validateTerrain,\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 validateTerrain from './validate/validate_terrain';\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<ValidationError>}\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.terrain = wrapCleanErrors(validateTerrain);\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<ValidationError>;\n\ntype ValidateStyle = {\n (Object, ?Object): $ReadOnlyArray<ValidationError>,\n source: Validator,\n layer: Validator,\n light: Validator,\n terrain: 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 validateTerrain = validateStyle.terrain;\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<Serialized>\n | SerializedObject;\n\ntype Registry = {\n [_: string]: {\n klass: Class<any>,\n omit: $ReadOnlyArray<string>,\n shallow: $ReadOnlyArray<string>\n }\n};\n\ntype RegisterOptions<T> = {\n omit?: $ReadOnlyArray<$Keys<T>>,\n shallow?: $ReadOnlyArray<$Keys<T>>\n}\n\nconst registry: Registry = {};\n\n/**\n * Register the given class as serializable.\n *\n * @param options\n * @param options.omit List of properties to omit from serialization (e.g., cached/computed properties)\n * @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<T: any>(name: string, klass: Class<T>, options: RegisterOptions<T> = {}) {\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<Transferable>): 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<Transferable>): Serialized {\n if (input === null ||\n input === undefined ||\n typeof input === 'boolean' ||\n typeof input === 'number' ||\n typeof input === 'string' ||\n input instanceof Boolean ||\n input instanceof Number ||\n input instanceof String ||\n input instanceof Date ||\n input instanceof RegExp) {\n return input;\n }\n\n if (isArrayBuffer(input) || isImageBitmap(input)) {\n if (transferables) {\n transferables.push(((input: any): ArrayBuffer));\n }\n return input;\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<Serialized> = [];\n for (const item of input) {\n serialized.push(serialize(item, transferables));\n }\n return serialized;\n }\n\n if (typeof input === 'object') {\n const klass = (input.constructor: any);\n const name = klass._classRegistryKey;\n if (!name) {\n throw new Error(`can't serialize object of unregistered class`);\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 <http://www.unicode.org/Public/12.0.0/ucd/Blocks.txt>.\n// Keep it synchronized with <http://www.unicode.org/Public/UCD/latest/ucd/Blocks.txt>.\n\ntype UnicodeBlockLookup = {[key: string]: (char: number) => boolean};\n\nconst unicodeBlockLookup: UnicodeBlockLookup = {\n // 'Basic Latin': (char) => char >= 0x0000 && char <= 0x007F,\n 'Latin-1 Supplement': (char) => char >= 0x0080 && char <= 0x00FF,\n // 'Latin Extended-A': (char) => char >= 0x0100 && char <= 0x017F,\n // 'Latin Extended-B': (char) => char >= 0x0180 && char <= 0x024F,\n // 'IPA Extensions': (char) => char >= 0x0250 && char <= 0x02AF,\n // 'Spacing Modifier Letters': (char) => char >= 0x02B0 && char <= 0x02FF,\n // 'Combining Diacritical Marks': (char) => char >= 0x0300 && char <= 0x036F,\n // 'Greek and Coptic': (char) => char >= 0x0370 && char <= 0x03FF,\n // 'Cyrillic': (char) => char >= 0x0400 && char <= 0x04FF,\n // 'Cyrillic Supplement': (char) => char >= 0x0500 && char <= 0x052F,\n // 'Armenian': (char) => char >= 0x0530 && char <= 0x058F,\n //'Hebrew': (char) => char >= 0x0590 && char <= 0x05FF,\n 'Arabic': (char) => char >= 0x0600 && char <= 0x06FF,\n //'Syriac': (char) => char >= 0x0700 && char <= 0x074F,\n 'Arabic Supplement': (char) => char >= 0x0750 && char <= 0x077F,\n // 'Thaana': (char) => char >= 0x0780 && char <= 0x07BF,\n // 'NKo': (char) => char >= 0x07C0 && char <= 0x07FF,\n // 'Samaritan': (char) => char >= 0x0800 && char <= 0x083F,\n // 'Mandaic': (char) => char >= 0x0840 && char <= 0x085F,\n // 'Syriac Supplement': (char) => char >= 0x0860 && char <= 0x086F,\n 'Arabic Extended-A': (char) => char >= 0x08A0 && char <= 0x08FF,\n // 'Devanagari': (char) => char >= 0x0900 && char <= 0x097F,\n // 'Bengali': (char) => char >= 0x0980 && char <= 0x09FF,\n // 'Gurmukhi': (char) => char >= 0x0A00 && char <= 0x0A7F,\n // 'Gujarati': (char) => char >= 0x0A80 && char <= 0x0AFF,\n // 'Oriya': (char) => char >= 0x0B00 && char <= 0x0B7F,\n // 'Tamil': (char) => char >= 0x0B80 && char <= 0x0BFF,\n // 'Telugu': (char) => char >= 0x0C00 && char <= 0x0C7F,\n // 'Kannada': (char) => char >= 0x0C80 && char <= 0x0CFF,\n // 'Malayalam': (char) => char >= 0x0D00 && char <= 0x0D7F,\n // 'Sinhala': (char) => char >= 0x0D80 && char <= 0x0DFF,\n // 'Thai': (char) => char >= 0x0E00 && char <= 0x0E7F,\n // 'Lao': (char) => char >= 0x0E80 && char <= 0x0EFF,\n // 'Tibetan': (char) => char >= 0x0F00 && char <= 0x0FFF,\n // 'Myanmar': (char) => char >= 0x1000 && char <= 0x109F,\n // 'Georgian': (char) => char >= 0x10A0 && char <= 0x10FF,\n 'Hangul Jamo': (char) => char >= 0x1100 && char <= 0x11FF,\n // 'Ethiopic': (char) => char >= 0x1200 && char <= 0x137F,\n // 'Ethiopic Supplement': (char) => char >= 0x1380 && char <= 0x139F,\n // 'Cherokee': (char) => char >= 0x13A0 && char <= 0x13FF,\n 'Unified Canadian Aboriginal Syllabics': (char) => char >= 0x1400 && char <= 0x167F,\n // 'Ogham': (char) => char >= 0x1680 && char <= 0x169F,\n // 'Runic': (char) => char >= 0x16A0 && char <= 0x16FF,\n // 'Tagalog': (char) => char >= 0x1700 && char <= 0x171F,\n // 'Hanunoo': (char) => char >= 0x1720 && char <= 0x173F,\n // 'Buhid': (char) => char >= 0x1740 && char <= 0x175F,\n // 'Tagbanwa': (char) => char >= 0x1760 && char <= 0x177F,\n 'Khmer': (char) => char >= 0x1780 && char <= 0x17FF,\n // 'Mongolian': (char) => char >= 0x1800 && char <= 0x18AF,\n 'Unified Canadian Aboriginal Syllabics Extended': (char) => char >= 0x18B0 && char <= 0x18FF,\n // 'Limbu': (char) => char >= 0x1900 && char <= 0x194F,\n // 'Tai Le': (char) => char >= 0x1950 && char <= 0x197F,\n // 'New Tai Lue': (char) => char >= 0x1980 && char <= 0x19DF,\n // 'Khmer Symbols': (char) => char >= 0x19E0 && char <= 0x19FF,\n // 'Buginese': (char) => char >= 0x1A00 && char <= 0x1A1F,\n // 'Tai Tham': (char) => char >= 0x1A20 && char <= 0x1AAF,\n // 'Combining Diacritical Marks Extended': (char) => char >= 0x1AB0 && char <= 0x1AFF,\n // 'Balinese': (char) => char >= 0x1B00 && char <= 0x1B7F,\n // 'Sundanese': (char) => char >= 0x1B80 && char <= 0x1BBF,\n // 'Batak': (char) => char >= 0x1BC0 && char <= 0x1BFF,\n // 'Lepcha': (char) => char >= 0x1C00 && char <= 0x1C4F,\n // 'Ol Chiki': (char) => char >= 0x1C50 && char <= 0x1C7F,\n // 'Cyrillic Extended-C': (char) => char >= 0x1C80 && char <= 0x1C8F,\n // 'Georgian Extended': (char) => char >= 0x1C90 && char <= 0x1CBF,\n // 'Sundanese Supplement': (char) => char >= 0x1CC0 && char <= 0x1CCF,\n // 'Vedic Extensions': (char) => char >= 0x1CD0 && char <= 0x1CFF,\n // 'Phonetic Extensions': (char) => char >= 0x1D00 && char <= 0x1D7F,\n // 'Phonetic Extensions Supplement': (char) => char >= 0x1D80 && char <= 0x1DBF,\n // 'Combining Diacritical Marks Supplement': (char) => char >= 0x1DC0 && char <= 0x1DFF,\n // 'Latin Extended Additional': (char) => char >= 0x1E00 && char <= 0x1EFF,\n // 'Greek Extended': (char) => char >= 0x1F00 && char <= 0x1FFF,\n 'General Punctuation': (char) => char >= 0x2000 && char <= 0x206F,\n // 'Superscripts and Subscripts': (char) => char >= 0x2070 && char <= 0x209F,\n // 'Currency Symbols': (char) => char >= 0x20A0 && char <= 0x20CF,\n // 'Combining Diacritical Marks for Symbols': (char) => char >= 0x20D0 && char <= 0x20FF,\n 'Letterlike Symbols': (char) => char >= 0x2100 && char <= 0x214F,\n 'Number Forms': (char) => char >= 0x2150 && char <= 0x218F,\n // 'Arrows': (char) => char >= 0x2190 && char <= 0x21FF,\n // 'Mathematical Operators': (char) => char >= 0x2200 && char <= 0x22FF,\n 'Miscellaneous Technical': (char) => char >= 0x2300 && char <= 0x23FF,\n 'Control Pictures': (char) => char >= 0x2400 && char <= 0x243F,\n 'Optical Character Recognition': (char) => char >= 0x2440 && char <= 0x245F,\n 'Enclosed Alphanumerics': (char) => char >= 0x2460 && char <= 0x24FF,\n // 'Box Drawing': (char) => char >= 0x2500 && char <= 0x257F,\n // 'Block Elements': (char) => char >= 0x2580 && char <= 0x259F,\n 'Geometric Shapes': (char) => char >= 0x25A0 && char <= 0x25FF,\n 'Miscellaneous Symbols': (char) => char >= 0x2600 && char <= 0x26FF,\n // 'Dingbats': (char) => char >= 0x2700 && char <= 0x27BF,\n // 'Miscellaneous Mathematical Symbols-A': (char) => char >= 0x27C0 && char <= 0x27EF,\n // 'Supplemental Arrows-A': (char) => char >= 0x27F0 && char <= 0x27FF,\n // 'Braille Patterns': (char) => char >= 0x2800 && char <= 0x28FF,\n // 'Supplemental Arrows-B': (char) => char >= 0x2900 && char <= 0x297F,\n // 'Miscellaneous Mathematical Symbols-B': (char) => char >= 0x2980 && char <= 0x29FF,\n // 'Supplemental Mathematical Operators': (char) => char >= 0x2A00 && char <= 0x2AFF,\n 'Miscellaneous Symbols and Arrows': (char) => char >= 0x2B00 && char <= 0x2BFF,\n // 'Glagolitic': (char) => char >= 0x2C00 && char <= 0x2C5F,\n // 'Latin Extended-C': (char) => char >= 0x2C60 && char <= 0x2C7F,\n // 'Coptic': (char) => char >= 0x2C80 && char <= 0x2CFF,\n // 'Georgian Supplement': (char) => char >= 0x2D00 && char <= 0x2D2F,\n // 'Tifinagh': (char) => char >= 0x2D30 && char <= 0x2D7F,\n // 'Ethiopic Extended': (char) => char >= 0x2D80 && char <= 0x2DDF,\n // 'Cyrillic Extended-A': (char) => char >= 0x2DE0 && char <= 0x2DFF,\n // 'Supplemental Punctuation': (char) => char >= 0x2E00 && char <= 0x2E7F,\n 'CJK Radicals Supplement': (char) => char >= 0x2E80 && char <= 0x2EFF,\n 'Kangxi Radicals': (char) => char >= 0x2F00 && char <= 0x2FDF,\n 'Ideographic Description Characters': (char) => char >= 0x2FF0 && char <= 0x2FFF,\n 'CJK Symbols and Punctuation': (char) => char >= 0x3000 && char <= 0x303F,\n 'Hiragana': (char) => char >= 0x3040 && char <= 0x309F,\n 'Katakana': (char) => char >= 0x30A0 && char <= 0x30FF,\n 'Bopomofo': (char) => char >= 0x3100 && char <= 0x312F,\n 'Hangul Compatibility Jamo': (char) => char >= 0x3130 && char <= 0x318F,\n 'Kanbun': (char) => char >= 0x3190 && char <= 0x319F,\n 'Bopomofo Extended': (char) => char >= 0x31A0 && char <= 0x31BF,\n 'CJK Strokes': (char) => char >= 0x31C0 && char <= 0x31EF,\n 'Katakana Phonetic Extensions': (char) => char >= 0x31F0 && char <= 0x31FF,\n 'Enclosed CJK Letters and Months': (char) => char >= 0x3200 && char <= 0x32FF,\n 'CJK Compatibility': (char) => char >= 0x3300 && char <= 0x33FF,\n 'CJK Unified Ideographs Extension A': (char) => char >= 0x3400 && char <= 0x4DBF,\n 'Yijing Hexagram Symbols': (char) => char >= 0x4DC0 && char <= 0x4DFF,\n 'CJK Unified Ideographs': (char) => char >= 0x4E00 && char <= 0x9FFF,\n 'Yi Syllables': (char) => char >= 0xA000 && char <= 0xA48F,\n 'Yi Radicals': (char) => char >= 0xA490 && char <= 0xA4CF,\n // 'Lisu': (char) => char >= 0xA4D0 && char <= 0xA4FF,\n // 'Vai': (char) => char >= 0xA500 && char <= 0xA63F,\n // 'Cyrillic Extended-B': (char) => char >= 0xA640 && char <= 0xA69F,\n // 'Bamum': (char) => char >= 0xA6A0 && char <= 0xA6FF,\n // 'Modifier Tone Letters': (char) => char >= 0xA700 && char <= 0xA71F,\n // 'Latin Extended-D': (char) => char >= 0xA720 && char <= 0xA7FF,\n // 'Syloti Nagri': (char) => char >= 0xA800 && char <= 0xA82F,\n // 'Common Indic Number Forms': (char) => char >= 0xA830 && char <= 0xA83F,\n // 'Phags-pa': (char) => char >= 0xA840 && char <= 0xA87F,\n // 'Saurashtra': (char) => char >= 0xA880 && char <= 0xA8DF,\n // 'Devanagari Extended': (char) => char >= 0xA8E0 && char <= 0xA8FF,\n // 'Kayah Li': (char) => char >= 0xA900 && char <= 0xA92F,\n // 'Rejang': (char) => char >= 0xA930 && char <= 0xA95F,\n 'Hangul Jamo Extended-A': (char) => char >= 0xA960 && char <= 0xA97F,\n // 'Javanese': (char) => char >= 0xA980 && char <= 0xA9DF,\n // 'Myanmar Extended-B': (char) => char >= 0xA9E0 && char <= 0xA9FF,\n // 'Cham': (char) => char >= 0xAA00 && char <= 0xAA5F,\n // 'Myanmar Extended-A': (char) => char >= 0xAA60 && char <= 0xAA7F,\n // 'Tai Viet': (char) => char >= 0xAA80 && char <= 0xAADF,\n // 'Meetei Mayek Extensions': (char) => char >= 0xAAE0 && char <= 0xAAFF,\n // 'Ethiopic Extended-A': (char) => char >= 0xAB00 && char <= 0xAB2F,\n // 'Latin Extended-E': (char) => char >= 0xAB30 && char <= 0xAB6F,\n // 'Cherokee Supplement': (char) => char >= 0xAB70 && char <= 0xABBF,\n // 'Meetei Mayek': (char) => char >= 0xABC0 && char <= 0xABFF,\n 'Hangul Syllables': (char) => char >= 0xAC00 && char <= 0xD7AF,\n 'Hangul Jamo Extended-B': (char) => char >= 0xD7B0 && char <= 0xD7FF,\n // 'High Surrogates': (char) => char >= 0xD800 && char <= 0xDB7F,\n // 'High Private Use Surrogates': (char) => char >= 0xDB80 && char <= 0xDBFF,\n // 'Low Surrogates': (char) => char >= 0xDC00 && char <= 0xDFFF,\n 'Private Use Area': (char) => char >= 0xE000 && char <= 0xF8FF,\n 'CJK Compatibility Ideographs': (char) => char >= 0xF900 && char <= 0xFAFF,\n // 'Alphabetic Presentation Forms': (char) => char >= 0xFB00 && char <= 0xFB4F,\n 'Arabic Presentation Forms-A': (char) => char >= 0xFB50 && char <= 0xFDFF,\n // 'Variation Selectors': (char) => char >= 0xFE00 && char <= 0xFE0F,\n 'Vertical Forms': (char) => char >= 0xFE10 && char <= 0xFE1F,\n // 'Combining Half Marks': (char) => char >= 0xFE20 && char <= 0xFE2F,\n 'CJK Compatibility Forms': (char) => char >= 0xFE30 && char <= 0xFE4F,\n 'Small Form Variants': (char) => char >= 0xFE50 && char <= 0xFE6F,\n 'Arabic Presentation Forms-B': (char) => char >= 0xFE70 && char <= 0xFEFF,\n 'Halfwidth and Fullwidth Forms': (char) => char >= 0xFF00 && char <= 0xFFEF\n // 'Specials': (char) => char >= 0xFFF0 && char <= 0xFFFF,\n // 'Linear B Syllabary': (char) => char >= 0x10000 && char <= 0x1007F,\n // 'Linear B Ideograms': (char) => char >= 0x10080 && char <= 0x100FF,\n // 'Aegean Numbers': (char) => char >= 0x10100 && char <= 0x1013F,\n // 'Ancient Greek Numbers': (char) => char >= 0x10140 && char <= 0x1018F,\n // 'Ancient Symbols': (char) => char >= 0x10190 && char <= 0x101CF,\n // 'Phaistos Disc': (char) => char >= 0x101D0 && char <= 0x101FF,\n // 'Lycian': (char) => char >= 0x10280 && char <= 0x1029F,\n // 'Carian': (char) => char >= 0x102A0 && char <= 0x102DF,\n // 'Coptic Epact Numbers': (char) => char >= 0x102E0 && char <= 0x102FF,\n // 'Old Italic': (char) => char >= 0x10300 && char <= 0x1032F,\n // 'Gothic': (char) => char >= 0x10330 && char <= 0x1034F,\n // 'Old Permic': (char) => char >= 0x10350 && char <= 0x1037F,\n // 'Ugaritic': (char) => char >= 0x10380 && char <= 0x1039F,\n // 'Old Persian': (char) => char >= 0x103A0 && char <= 0x103DF,\n // 'Deseret': (char) => char >= 0x10400 && char <= 0x1044F,\n // 'Shavian': (char) => char >= 0x10450 && char <= 0x1047F,\n // 'Osmanya': (char) => char >= 0x10480 && char <= 0x104AF,\n // 'Osage': (char) => char >= 0x104B0 && char <= 0x104FF,\n // 'Elbasan': (char) => char >= 0x10500 && char <= 0x1052F,\n // 'Caucasian Albanian': (char) => char >= 0x10530 && char <= 0x1056F,\n // 'Linear A': (char) => char >= 0x10600 && char <= 0x1077F,\n // 'Cypriot Syllabary': (char) => char >= 0x10800 && char <= 0x1083F,\n // 'Imperial Aramaic': (char) => char >= 0x10840 && char <= 0x1085F,\n // 'Palmyrene': (char) => char >= 0x10860 && char <= 0x1087F,\n // 'Nabataean': (char) => char >= 0x10880 && char <= 0x108AF,\n // 'Hatran': (char) => char >= 0x108E0 && char <= 0x108FF,\n // 'Phoenician': (char) => char >= 0x10900 && char <= 0x1091F,\n // 'Lydian': (char) => char >= 0x10920 && char <= 0x1093F,\n // 'Meroitic Hieroglyphs': (char) => char >= 0x10980 && char <= 0x1099F,\n // 'Meroitic Cursive': (char) => char >= 0x109A0 && char <= 0x109FF,\n // 'Kharoshthi': (char) => char >= 0x10A00 && char <= 0x10A5F,\n // 'Old South Arabian': (char) => char >= 0x10A60 && char <= 0x10A7F,\n // 'Old North Arabian': (char) => char >= 0x10A80 && char <= 0x10A9F,\n // 'Manichaean': (char) => char >= 0x10AC0 && char <= 0x10AFF,\n // 'Avestan': (char) => char >= 0x10B00 && char <= 0x10B3F,\n // 'Inscriptional Parthian': (char) => char >= 0x10B40 && char <= 0x10B5F,\n // 'Inscriptional Pahlavi': (char) => char >= 0x10B60 && char <= 0x10B7F,\n // 'Psalter Pahlavi': (char) => char >= 0x10B80 && char <= 0x10BAF,\n // 'Old Turkic': (char) => char >= 0x10C00 && char <= 0x10C4F,\n // 'Old Hungarian': (char) => char >= 0x10C80 && char <= 0x10CFF,\n // 'Hanifi Rohingya': (char) => char >= 0x10D00 && char <= 0x10D3F,\n // 'Rumi Numeral Symbols': (char) => char >= 0x10E60 && char <= 0x10E7F,\n // 'Old Sogdian': (char) => char >= 0x10F00 && char <= 0x10F2F,\n // 'Sogdian': (char) => char >= 0x10F30 && char <= 0x10F6F,\n // 'Elymaic': (char) => char >= 0x10FE0 && char <= 0x10FFF,\n // 'Brahmi': (char) => char >= 0x11000 && char <= 0x1107F,\n // 'Kaithi': (char) => char >= 0x11080 && char <= 0x110CF,\n // 'Sora Sompeng': (char) => char >= 0x110D0 && char <= 0x110FF,\n // 'Chakma': (char) => char >= 0x11100 && char <= 0x1114F,\n // 'Mahajani': (char) => char >= 0x11150 && char <= 0x1117F,\n // 'Sharada': (char) => char >= 0x11180 && char <= 0x111DF,\n // 'Sinhala Archaic Numbers': (char) => char >= 0x111E0 && char <= 0x111FF,\n // 'Khojki': (char) => char >= 0x11200 && char <= 0x1124F,\n // 'Multani': (char) => char >= 0x11280 && char <= 0x112AF,\n // 'Khudawadi': (char) => char >= 0x112B0 && char <= 0x112FF,\n // 'Grantha': (char) => char >= 0x11300 && char <= 0x1137F,\n // 'Newa': (char) => char >= 0x11400 && char <= 0x1147F,\n // 'Tirhuta': (char) => char >= 0x11480 && char <= 0x114DF,\n // 'Siddham': (char) => char >= 0x11580 && char <= 0x115FF,\n // 'Modi': (char) => char >= 0x11600 && char <= 0x1165F,\n // 'Mongolian Supplement': (char) => char >= 0x11660 && char <= 0x1167F,\n // 'Takri': (char) => char >= 0x11680 && char <= 0x116CF,\n // 'Ahom': (char) => char >= 0x11700 && char <= 0x1173F,\n // 'Dogra': (char) => char >= 0x11800 && char <= 0x1184F,\n // 'Warang Citi': (char) => char >= 0x118A0 && char <= 0x118FF,\n // 'Nandinagari': (char) => char >= 0x119A0 && char <= 0x119FF,\n // 'Zanabazar Square': (char) => char >= 0x11A00 && char <= 0x11A4F,\n // 'Soyombo': (char) => char >= 0x11A50 && char <= 0x11AAF,\n // 'Pau Cin Hau': (char) => char >= 0x11AC0 && char <= 0x11AFF,\n // 'Bhaiksuki': (char) => char >= 0x11C00 && char <= 0x11C6F,\n // 'Marchen': (char) => char >= 0x11C70 && char <= 0x11CBF,\n // 'Masaram Gondi': (char) => char >= 0x11D00 && char <= 0x11D5F,\n // 'Gunjala Gondi': (char) => char >= 0x11D60 && char <= 0x11DAF,\n // 'Makasar': (char) => char >= 0x11EE0 && char <= 0x11EFF,\n // 'Tamil Supplement': (char) => char >= 0x11FC0 && char <= 0x11FFF,\n // 'Cuneiform': (char) => char >= 0x12000 && char <= 0x123FF,\n // 'Cuneiform Numbers and Punctuation': (char) => char >= 0x12400 && char <= 0x1247F,\n // 'Early Dynastic Cuneiform': (char) => char >= 0x12480 && char <= 0x1254F,\n // 'Egyptian Hieroglyphs': (char) => char >= 0x13000 && char <= 0x1342F,\n // 'Egyptian Hieroglyph Format Controls': (char) => char >= 0x13430 && char <= 0x1343F,\n // 'Anatolian Hieroglyphs': (char) => char >= 0x14400 && char <= 0x1467F,\n // 'Bamum Supplement': (char) => char >= 0x16800 && char <= 0x16A3F,\n // 'Mro': (char) => char >= 0x16A40 && char <= 0x16A6F,\n // 'Bassa Vah': (char) => char >= 0x16AD0 && char <= 0x16AFF,\n // 'Pahawh Hmong': (char) => char >= 0x16B00 && char <= 0x16B8F,\n // 'Medefaidrin': (char) => char >= 0x16E40 && char <= 0x16E9F,\n // 'Miao': (char) => char >= 0x16F00 && char <= 0x16F9F,\n // 'Ideographic Symbols and Punctuation': (char) => char >= 0x16FE0 && char <= 0x16FFF,\n // 'Tangut': (char) => char >= 0x17000 && char <= 0x187FF,\n // 'Tangut Components': (char) => char >= 0x18800 && char <= 0x18AFF,\n // 'Kana Supplement': (char) => char >= 0x1B000 && char <= 0x1B0FF,\n // 'Kana Extended-A': (char) => char >= 0x1B100 && char <= 0x1B12F,\n // 'Small Kana Extension': (char) => char >= 0x1B130 && char <= 0x1B16F,\n // 'Nushu': (char) => char >= 0x1B170 && char <= 0x1B2FF,\n // 'Duployan': (char) => char >= 0x1BC00 && char <= 0x1BC9F,\n // 'Shorthand Format Controls': (char) => char >= 0x1BCA0 && char <= 0x1BCAF,\n // 'Byzantine Musical Symbols': (char) => char >= 0x1D000 && char <= 0x1D0FF,\n // 'Musical Symbols': (char) => char >= 0x1D100 && char <= 0x1D1FF,\n // 'Ancient Greek Musical Notation': (char) => char >= 0x1D200 && char <= 0x1D24F,\n // 'Mayan Numerals': (char) => char >= 0x1D2E0 && char <= 0x1D2FF,\n // 'Tai Xuan Jing Symbols': (char) => char >= 0x1D300 && char <= 0x1D35F,\n // 'Counting Rod Numerals': (char) => char >= 0x1D360 && char <= 0x1D37F,\n // 'Mathematical Alphanumeric Symbols': (char) => char >= 0x1D400 && char <= 0x1D7FF,\n // 'Sutton SignWriting': (char) => char >= 0x1D800 && char <= 0x1DAAF,\n // 'Glagolitic Supplement': (char) => char >= 0x1E000 && char <= 0x1E02F,\n // 'Nyiakeng Puachue Hmong': (char) => char >= 0x1E100 && char <= 0x1E14F,\n // 'Wancho': (char) => char >= 0x1E2C0 && char <= 0x1E2FF,\n // 'Mende Kikakui': (char) => char >= 0x1E800 && char <= 0x1E8DF,\n // 'Adlam': (char) => char >= 0x1E900 && char <= 0x1E95F,\n // 'Indic Siyaq Numbers': (char) => char >= 0x1EC70 && char <= 0x1ECBF,\n // 'Ottoman Siyaq Numbers': (char) => char >= 0x1ED00 && char <= 0x1ED4F,\n // 'Arabic Mathematical Alphabetic Symbols': (char) => char >= 0x1EE00 && char <= 0x1EEFF,\n // 'Mahjong Tiles': (char) => char >= 0x1F000 && char <= 0x1F02F,\n // 'Domino Tiles': (char) => char >= 0x1F030 && char <= 0x1F09F,\n // 'Playing Cards': (char) => char >= 0x1F0A0 && char <= 0x1F0FF,\n // 'Enclosed Alphanumeric Supplement': (char) => char >= 0x1F100 && char <= 0x1F1FF,\n // 'Enclosed Ideographic Supplement': (char) => char >= 0x1F200 && char <= 0x1F2FF,\n // 'Miscellaneous Symbols and Pictographs': (char) => char >= 0x1F300 && char <= 0x1F5FF,\n // 'Emoticons': (char) => char >= 0x1F600 && char <= 0x1F64F,\n // 'Ornamental Dingbats': (char) => char >= 0x1F650 && char <= 0x1F67F,\n // 'Transport and Map Symbols': (char) => char >= 0x1F680 && char <= 0x1F6FF,\n // 'Alchemical Symbols': (char) => char >= 0x1F700 && char <= 0x1F77F,\n // 'Geometric Shapes Extended': (char) => char >= 0x1F780 && char <= 0x1F7FF,\n // 'Supplemental Arrows-C': (char) => char >= 0x1F800 && char <= 0x1F8FF,\n // 'Supplemental Symbols and Pictographs': (char) => char >= 0x1F900 && char <= 0x1F9FF,\n // 'Chess Symbols': (char) => char >= 0x1FA00 && char <= 0x1FA6F,\n // 'Symbols and Pictographs Extended-A': (char) => char >= 0x1FA70 && char <= 0x1FAFF,\n // 'CJK Unified Ideographs Extension B': (char) => char >= 0x20000 && char <= 0x2A6DF,\n // 'CJK Unified Ideographs Extension C': (char) => char >= 0x2A700 && char <= 0x2B73F,\n // 'CJK Unified Ideographs Extension D': (char) => char >= 0x2B740 && char <= 0x2B81F,\n // 'CJK Unified Ideographs Extension E': (char) => char >= 0x2B820 && char <= 0x2CEAF,\n // 'CJK Unified Ideographs Extension F': (char) => char >= 0x2CEB0 && char <= 0x2EBEF,\n // 'CJK Compatibility Ideographs Supplement': (char) => char >= 0x2F800 && char <= 0x2FA1F,\n // 'Tags': (char) => char >= 0xE0000 && char <= 0xE007F,\n // 'Variation Selectors Supplement': (char) => char >= 0xE0100 && char <= 0xE01EF,\n // 'Supplementary Private Use Area-A': (char) => char >= 0xF0000 && char <= 0xFFFFF,\n // 'Supplementary Private Use Area-B': (char) => char >= 0x100000 && char <= 0x10FFFF,\n};\n\nexport default unicodeBlockLookup;\n","// @flow\n\n/* eslint-disable new-cap */\n\nimport isChar from './is_char_in_unicode_block';\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// <http://www.unicode.org/Public/12.0.0/ucd/VerticalOrientation.txt>.\n// Keep it synchronized with\n// <http://www.unicode.org/Public/UCD/latest/ucd/VerticalOrientation.txt>.\n// The data file denotes with “U” or “Tu” any codepoint that may be drawn\n// upright in vertical text but does not distinguish between upright and\n// “neutral” characters.\n\n// Blocks in the Unicode supplementary planes are excluded from this module due\n// to <https://github.com/mapbox/mapbox-gl/issues/29>.\n\n/**\n * Returns true if the given Unicode codepoint identifies a character with\n * upright orientation.\n *\n * A character has upright orientation if it is drawn upright (unrotated)\n * whether the line is oriented horizontally or vertically, even if both\n * adjacent characters can be rotated. For example, a Chinese character is\n * always drawn upright. An uprightly oriented character causes an adjacent\n * “neutral” character to be drawn upright as well.\n * @private\n */\nexport function charHasUprightVerticalOrientation(char: number) {\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<typeof status>;\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<number>) => Array<string>,\n processStyledBidirectionalText: ?(string, Array<number>, Array<number>) => Array<[string, Array<number>]>,\n isLoaded: () => boolean,\n isLoading: () => boolean,\n setState: (state: PluginState) => void,\n isParsed: () => boolean,\n getPluginURL: () => ?string\n} = {\n applyArabicShaping: null,\n processBidirectionalText: null,\n processStyledBidirectionalText: null,\n isLoaded() {\n return pluginStatus === status.loaded || // Main Thread: loaded if the completion callback returned successfully\n plugin.applyArabicShaping != null; // Web-worker: loaded if the plugin functions have been compiled\n },\n isLoading() { // Main Thread Only: query the loading status, this function does not return the correct value in the worker context.\n return pluginStatus === status.loading;\n },\n setState(state: PluginState) { // Worker thread only: this tells the worker threads that the plugin is available on the Main thread\n assert(isWorker(), 'Cannot set the state of the rtl-text-plugin when not in the web-worker context');\n\n pluginStatus = state.pluginStatus;\n pluginURL = state.pluginURL;\n },\n isParsed(): boolean {\n assert(isWorker(), 'rtl-text-plugin is only parsed on the worker-threads');\n\n return plugin.applyArabicShaping != null &&\n plugin.processBidirectionalText != null &&\n plugin.processStyledBidirectionalText != null;\n },\n getPluginURL(): ?string {\n assert(isWorker(), 'rtl-text-plugin url can only be queried from the worker threads');\n return pluginURL;\n }\n};\n\nexport const lazyLoadRTLTextPlugin = function() {\n if (!plugin.isLoading() &&\n !plugin.isLoaded() &&\n getRTLTextPluginStatus() === 'deferred'\n ) {\n downloadRTLTextPlugin();\n }\n};\n","// @flow\n\nimport 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<T> = {\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<T, R> {\n specification: StylePropertySpecification;\n possiblyEvaluate(value: PropertyValue<T, R>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array<string>): R;\n interpolate(a: R, b: R, t: number): R;\n}\n\n/**\n * `PropertyValue` represents the value part of a property key-value unit. It's used to represent both\n * paint and layout property values, and regardless of whether or not their property supports data-driven\n * expressions.\n *\n * `PropertyValue` stores the raw input value as seen in a style or a runtime styling API call, i.e. one of the\n * following:\n *\n * * A constant value of the type appropriate for the property\n * * A function which produces a value of that type (but functions are quasi-deprecated in favor of expressions)\n * * An expression which produces a value of that type\n * * \"undefined\"/\"not present\", in which case the property is assumed to take on its default value.\n *\n * In addition to storing the original input value, `PropertyValue` also stores a normalized representation,\n * effectively treating functions as if they are expressions, and constant or default values as if they are\n * (constant) expressions.\n *\n * @private\n */\nexport class PropertyValue<T, R> {\n property: Property<T, R>;\n value: PropertyValueSpecification<T> | void;\n expression: StylePropertyExpression;\n\n constructor(property: Property<T, R>, value: PropertyValueSpecification<T> | void) {\n this.property = property;\n this.value = value;\n this.expression = normalizePropertyExpression(value === undefined ? property.specification.default : value, property.specification);\n }\n\n isDataDriven(): boolean {\n return this.expression.kind === 'source' || this.expression.kind === 'composite';\n }\n\n possiblyEvaluate(parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array<string>): R {\n return this.property.possiblyEvaluate(this, parameters, canonical, availableImages);\n }\n}\n\n// ------- Transitionable -------\n\nexport type TransitionParameters = {\n now: TimePoint,\n transition: TransitionSpecification\n};\n\n/**\n * Paint properties are _transitionable_: they can change in a fluid manner, interpolating or cross-fading between\n * old and new value. The duration of the transition, and the delay before it begins, is configurable.\n *\n * `TransitionablePropertyValue` is a compositional class that stores both the property value and that transition\n * configuration.\n *\n * A `TransitionablePropertyValue` can calculate the next step in the evaluation chain for paint property values:\n * `TransitioningPropertyValue`.\n *\n * @private\n */\nclass TransitionablePropertyValue<T, R> {\n property: Property<T, R>;\n value: PropertyValue<T, R>;\n transition: TransitionSpecification | void;\n\n constructor(property: Property<T, R>) {\n this.property = property;\n this.value = new PropertyValue(property, undefined);\n }\n\n transitioned(parameters: TransitionParameters,\n prior: TransitioningPropertyValue<T, R>): TransitioningPropertyValue<T, R> {\n return new TransitioningPropertyValue(this.property, this.value, prior, // eslint-disable-line no-use-before-define\n extend({}, parameters.transition, this.transition), parameters.now);\n }\n\n untransitioned(): TransitioningPropertyValue<T, R> {\n return new TransitioningPropertyValue(this.property, this.value, null, {}, 0); // eslint-disable-line no-use-before-define\n }\n}\n\n/**\n * A helper type: given an object type `Properties` whose values are each of type `Property<T, R>`, it calculates\n * an object type with the same keys and values of type `TransitionablePropertyValue<T, R>`.\n *\n * @private\n */\ntype TransitionablePropertyValues<Props: Object>\n = $Exact<$ObjMap<Props, <T, R>(p: Property<T, R>) => TransitionablePropertyValue<T, R>>>\n\n/**\n * `Transitionable` stores a map of all (property name, `TransitionablePropertyValue`) pairs for paint properties of a\n * given layer type. It can calculate the `TransitioningPropertyValue`s for all of them at once, producing a\n * `Transitioning` instance for the same set of properties.\n *\n * @private\n */\nexport class Transitionable<Props: Object> {\n _properties: Properties<Props>;\n _values: TransitionablePropertyValues<Props>;\n\n constructor(properties: Properties<Props>) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultTransitionablePropertyValues): any);\n }\n\n getValue<S: string, T>(name: S): PropertyValueSpecification<T> | void {\n return clone(this._values[name].value.value);\n }\n\n setValue<S: string, T>(name: S, value: PropertyValueSpecification<T> | void) {\n if (!this._values.hasOwnProperty(name)) {\n this._values[name] = new TransitionablePropertyValue(this._values[name].property);\n }\n // Note that we do not _remove_ an own property in the case where a value is being reset\n // to the default: the transition might still be non-default.\n this._values[name].value = new PropertyValue(this._values[name].property, value === null ? undefined : clone(value));\n }\n\n getTransition<S: string>(name: S): TransitionSpecification | void {\n return clone(this._values[name].transition);\n }\n\n setTransition<S: string>(name: S, value: TransitionSpecification | void) {\n if (!this._values.hasOwnProperty(name)) {\n this._values[name] = new TransitionablePropertyValue(this._values[name].property);\n }\n this._values[name].transition = clone(value) || undefined;\n }\n\n serialize() {\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<Props>): Transitioning<Props> {\n const result = new Transitioning(this._properties); // eslint-disable-line no-use-before-define\n for (const property of Object.keys(this._values)) {\n result._values[property] = this._values[property].transitioned(parameters, prior._values[property]);\n }\n return result;\n }\n\n untransitioned(): Transitioning<Props> {\n const result = new Transitioning(this._properties); // eslint-disable-line no-use-before-define\n for (const property of Object.keys(this._values)) {\n result._values[property] = this._values[property].untransitioned();\n }\n return result;\n }\n}\n\n// ------- Transitioning -------\n\n/**\n * `TransitioningPropertyValue` implements the first of two intermediate steps in the evaluation chain of a paint\n * property value. In this step, transitions between old and new values are handled: as long as the transition is in\n * progress, `TransitioningPropertyValue` maintains a reference to the prior value, and interpolates between it and\n * the new value based on the current time and the configured transition duration and delay. The product is the next\n * step in the evaluation chain: the \"possibly evaluated\" result type `R`. See below for more on this concept.\n *\n * @private\n */\nclass TransitioningPropertyValue<T, R> {\n property: Property<T, R>;\n value: PropertyValue<T, R>;\n prior: ?TransitioningPropertyValue<T, R>;\n begin: TimePoint;\n end: TimePoint;\n\n constructor(property: Property<T, R>,\n value: PropertyValue<T, R>,\n prior: ?TransitioningPropertyValue<T, R>,\n transition: TransitionSpecification,\n now: TimePoint) {\n 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<string>): R {\n const now = parameters.now || 0;\n const finalValue = this.value.possiblyEvaluate(parameters, canonical, availableImages);\n const prior = this.prior;\n if (!prior) {\n // No prior value.\n return finalValue;\n } else if (now > this.end) {\n // Transition from prior value is now complete.\n this.prior = null;\n return finalValue;\n } else if (this.value.isDataDriven()) {\n // Transitions to data-driven properties are not supported.\n // We snap immediately to the data-driven value so that, when we perform layout,\n // we see the data-driven function and can use it to populate vertex buffers.\n this.prior = null;\n return finalValue;\n } else if (now < this.begin) {\n // Transition hasn't started yet.\n return prior.possiblyEvaluate(parameters, canonical, availableImages);\n } else {\n // Interpolate between recursively-calculated prior value and final.\n const t = (now - this.begin) / (this.end - this.begin);\n return this.property.interpolate(prior.possiblyEvaluate(parameters, canonical, availableImages), finalValue, easeCubicInOut(t));\n }\n }\n}\n\n/**\n * A helper type: given an object type `Properties` whose values are each of type `Property<T, R>`, it calculates\n * an object type with the same keys and values of type `TransitioningPropertyValue<T, R>`.\n *\n * @private\n */\ntype TransitioningPropertyValues<Props: Object>\n = $Exact<$ObjMap<Props, <T, R>(p: Property<T, R>) => TransitioningPropertyValue<T, R>>>\n\n/**\n * `Transitioning` stores a map of all (property name, `TransitioningPropertyValue`) pairs for paint properties of a\n * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a\n * `PossiblyEvaluated` instance for the same set of properties.\n *\n * @private\n */\nexport class Transitioning<Props: Object> {\n _properties: Properties<Props>;\n _values: TransitioningPropertyValues<Props>;\n\n constructor(properties: Properties<Props>) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultTransitioningPropertyValues): any);\n }\n\n possiblyEvaluate(parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array<string>): PossiblyEvaluated<Props> {\n const result = new PossiblyEvaluated(this._properties); // eslint-disable-line no-use-before-define\n for (const property of Object.keys(this._values)) {\n result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages);\n }\n return result;\n }\n\n hasTransition() {\n for (const property of Object.keys(this._values)) {\n if (this._values[property].prior) {\n return true;\n }\n }\n return false;\n }\n}\n\n// ------- Layout -------\n\n/**\n * A helper type: given an object type `Properties` whose values are each of type `Property<T, R>`, it calculates\n * an object type with the same keys and values of type `PropertyValue<T, R>`.\n *\n * @private\n */\ntype PropertyValues<Props: Object>\n = $Exact<$ObjMap<Props, <T, R>(p: Property<T, R>) => PropertyValue<T, R>>>\n\n/**\n * Because layout properties are not transitionable, they have a simpler representation and evaluation chain than\n * paint properties: `PropertyValue`s are possibly evaluated, producing possibly evaluated values, which are then\n * fully evaluated.\n *\n * `Layout` stores a map of all (property name, `PropertyValue`) pairs for layout properties of a\n * given layer type. It can calculate the possibly-evaluated values for all of them at once, producing a\n * `PossiblyEvaluated` instance for the same set of properties.\n *\n * @private\n */\nexport class Layout<Props: Object> {\n _properties: Properties<Props>;\n _values: PropertyValues<Props>;\n\n constructor(properties: Properties<Props>) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultPropertyValues): any);\n }\n\n getValue<S: string>(name: S) {\n return clone(this._values[name].value);\n }\n\n setValue<S: string>(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<string>): PossiblyEvaluated<Props> {\n const result = new PossiblyEvaluated(this._properties); // eslint-disable-line no-use-before-define\n for (const property of Object.keys(this._values)) {\n result._values[property] = this._values[property].possiblyEvaluate(parameters, canonical, availableImages);\n }\n return result;\n }\n}\n\n// ------- PossiblyEvaluated -------\n\n/**\n * \"Possibly evaluated value\" is an intermediate stage in the evaluation chain for both paint and layout property\n * values. The purpose of this stage is to optimize away unnecessary recalculations for data-driven properties. Code\n * which uses data-driven property values must assume that the value is dependent on feature data, and request that it\n * be evaluated for each feature. But when that property value is in fact a constant or camera function, the calculation\n * will not actually depend on the feature, and we can benefit from returning the prior result of having done the\n * evaluation once, ahead of time, in an intermediate step whose inputs are just the value and \"global\" parameters\n * such as current zoom level.\n *\n * `PossiblyEvaluatedValue` represents the three possible outcomes of this step: if the input value was a constant or\n * camera expression, then the \"possibly evaluated\" result is a constant value. Otherwise, the input value was either\n * a source or composite expression, and we must defer final evaluation until supplied a feature. We separate\n * the source and composite cases because they are handled differently when generating GL attributes, buffers, and\n * uniforms.\n *\n * Note that `PossiblyEvaluatedValue` (and `PossiblyEvaluatedPropertyValue`, below) are _not_ used for properties that\n * do not allow data-driven values. For such properties, we know that the \"possibly evaluated\" result is always a constant\n * scalar value. See below.\n *\n * @private\n */\ntype PossiblyEvaluatedValue<T> =\n | {kind: 'constant', value: T}\n | SourceExpression\n | CompositeExpression;\n\n/**\n * `PossiblyEvaluatedPropertyValue` is used for data-driven paint and layout property values. It holds a\n * `PossiblyEvaluatedValue` and the `GlobalProperties` that were used to generate it. You're not allowed to supply\n * a different set of `GlobalProperties` when performing the final evaluation because they would be ignored in the\n * case where the input value was a constant or camera function.\n *\n * @private\n */\nexport class PossiblyEvaluatedPropertyValue<T> {\n property: DataDrivenProperty<T>;\n value: PossiblyEvaluatedValue<T>;\n parameters: EvaluationParameters;\n\n constructor(property: DataDrivenProperty<T>, value: PossiblyEvaluatedValue<T>, parameters: EvaluationParameters) {\n this.property = property;\n this.value = value;\n this.parameters = parameters;\n }\n\n isConstant(): boolean {\n return this.value.kind === 'constant';\n }\n\n constantOr(value: T): T {\n if (this.value.kind === 'constant') {\n return this.value.value;\n } else {\n return value;\n }\n }\n\n evaluate(feature: Feature, featureState: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>): T {\n return this.property.evaluate(this.value, this.parameters, feature, featureState, canonical, availableImages);\n }\n}\n\n/**\n * A helper type: given an object type `Properties` whose values are each of type `Property<T, R>`, it calculates\n * an object type with the same keys, and values of type `R`.\n *\n * For properties that don't allow data-driven values, `R` is a scalar type such as `number`, `string`, or `Color`.\n * For data-driven properties, it is `PossiblyEvaluatedPropertyValue`. Critically, the type definitions are set up\n * in a way that allows flow to know which of these two cases applies for any given property name, and if you attempt\n * to use a `PossiblyEvaluatedPropertyValue` as if it was a scalar, or vice versa, you will get a type error. (However,\n * there's at least one case in which flow fails to produce a type error that you should be aware of: in a context such\n * as `layer.paint.get('foo-opacity') === 0`, if `foo-opacity` is data-driven, than the left-hand side is of type\n * `PossiblyEvaluatedPropertyValue<number>`, but flow will not complain about comparing this to a number using `===`.\n * See https://github.com/facebook/flow/issues/2359.)\n *\n * There's also a third, special case possiblity for `R`: for cross-faded properties, it's `?CrossFaded<T>`.\n *\n * @private\n */\ntype PossiblyEvaluatedPropertyValues<Props: Object>\n = $Exact<$ObjMap<Props, <T, R>(p: Property<T, R>) => R>>\n\n/**\n * `PossiblyEvaluated` stores a map of all (property name, `R`) pairs for paint or layout properties of a\n * given layer type.\n * @private\n */\nexport class PossiblyEvaluated<Props: Object> {\n _properties: Properties<Props>;\n _values: PossiblyEvaluatedPropertyValues<Props>;\n\n constructor(properties: Properties<Props>) {\n this._properties = properties;\n this._values = (Object.create(properties.defaultPossiblyEvaluatedValues): any);\n }\n\n get<S: string>(name: S): $ElementType<PossiblyEvaluatedPropertyValues<Props>, S> {\n return this._values[name];\n }\n}\n\n/**\n * An implementation of `Property` for properties that do not permit data-driven (source or composite) expressions.\n * This restriction allows us to declare statically that the result of possibly evaluating this kind of property\n * is in fact always the scalar type `T`, and can be used without further evaluating the value on a per-feature basis.\n *\n * @private\n */\nexport class DataConstantProperty<T> implements Property<T, T> {\n specification: StylePropertySpecification;\n\n constructor(specification: StylePropertySpecification) {\n this.specification = specification;\n }\n\n possiblyEvaluate(value: PropertyValue<T, T>, parameters: EvaluationParameters): T {\n assert(!value.isDataDriven());\n return value.expression.evaluate(parameters);\n }\n\n interpolate(a: T, b: T, t: number): T {\n const interp: ?(a: T, b: T, t: number) => T = (interpolate: any)[this.specification.type];\n if (interp) {\n return interp(a, b, t);\n } else {\n return a;\n }\n }\n}\n\n/**\n * An implementation of `Property` for properties that permit data-driven (source or composite) expressions.\n * The result of possibly evaluating this kind of property is `PossiblyEvaluatedPropertyValue<T>`; obtaining\n * a scalar value `T` requires further evaluation on a per-feature basis.\n *\n * @private\n */\nexport class DataDrivenProperty<T> implements Property<T, PossiblyEvaluatedPropertyValue<T>> {\n specification: StylePropertySpecification;\n overrides: ?Object;\n\n constructor(specification: StylePropertySpecification, overrides?: Object) {\n this.specification = specification;\n this.overrides = overrides;\n }\n\n possiblyEvaluate(value: PropertyValue<T, PossiblyEvaluatedPropertyValue<T>>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array<string>): PossiblyEvaluatedPropertyValue<T> {\n if (value.expression.kind === 'constant' || value.expression.kind === 'camera') {\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: value.expression.evaluate(parameters, (null: any), {}, canonical, availableImages)}, parameters);\n } else {\n return new PossiblyEvaluatedPropertyValue(this, value.expression, parameters);\n }\n }\n\n interpolate(a: PossiblyEvaluatedPropertyValue<T>,\n b: PossiblyEvaluatedPropertyValue<T>,\n t: number): PossiblyEvaluatedPropertyValue<T> {\n // If either possibly-evaluated value is non-constant, give up: we aren't able to interpolate data-driven values.\n if (a.value.kind !== 'constant' || b.value.kind !== 'constant') {\n return a;\n }\n\n // Special case hack solely for fill-outline-color. The undefined value is subsequently handled in\n // FillStyleLayer#recalculate, which sets fill-outline-color to the fill-color value if the former\n // is a PossiblyEvaluatedPropertyValue containing a constant undefined value. In addition to the\n // return value here, the other source of a PossiblyEvaluatedPropertyValue containing a constant\n // undefined value is the \"default value\" for fill-outline-color held in\n // `Properties#defaultPossiblyEvaluatedValues`, which serves as the prototype of\n // `PossiblyEvaluated#_values`.\n if (a.value.value === undefined || b.value.value === undefined) {\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: (undefined: any)}, a.parameters);\n }\n\n const interp: ?(a: T, b: T, t: number) => T = (interpolate: any)[this.specification.type];\n if (interp) {\n return new PossiblyEvaluatedPropertyValue(this, {kind: 'constant', value: interp(a.value.value, b.value.value, t)}, a.parameters);\n } else {\n return a;\n }\n }\n\n evaluate(value: PossiblyEvaluatedValue<T>, parameters: EvaluationParameters, feature: Feature, featureState: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>): T {\n if (value.kind === 'constant') {\n return value.value;\n } else {\n 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<T> extends DataDrivenProperty<?CrossFaded<T>> {\n\n possiblyEvaluate(value: PropertyValue<?CrossFaded<T>, PossiblyEvaluatedPropertyValue<?CrossFaded<T>>>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array<string>): PossiblyEvaluatedPropertyValue<?CrossFaded<T>> {\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<?CrossFaded<T>>, globals: EvaluationParameters, feature: Feature, featureState: FeatureState, canonical?: CanonicalTileID, availableImages?: Array<string>): ?CrossFaded<T> {\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<T> {\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<?CrossFaded<T>>): PossiblyEvaluatedPropertyValue<?CrossFaded<T>> {\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<T> implements Property<T, ?CrossFaded<T>> {\n specification: StylePropertySpecification;\n\n constructor(specification: StylePropertySpecification) {\n this.specification = specification;\n }\n\n possiblyEvaluate(value: PropertyValue<T, ?CrossFaded<T>>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array<string>): ?CrossFaded<T> {\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<T> {\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<T>): ?CrossFaded<T> {\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<Color, boolean> {\n specification: StylePropertySpecification;\n\n constructor(specification: StylePropertySpecification) {\n this.specification = specification;\n }\n\n possiblyEvaluate(value: PropertyValue<Color, boolean>, parameters: EvaluationParameters, canonical?: CanonicalTileID, availableImages?: Array<string>): boolean {\n return !!value.expression.evaluate(parameters, (null: any), {}, canonical, availableImages);\n }\n\n interpolate(): boolean { return false; }\n}\n\n/**\n * `Properties` holds objects containing default values for the layout or paint property set of a given\n * layer type. These objects are immutable, and they are used as the prototypes for the `_values` members of\n * `Transitionable`, `Transitioning`, `Layout`, and `PossiblyEvaluated`. This allows these classes to avoid\n * doing work in the common case where a property has no explicit value set and should be considered to take\n * on the default value: using `for (const property of Object.keys(this._values))`, they can iterate over\n * only the _own_ properties of `_values`, skipping repeated calculation of transitions and possible/final\n * evaluations for defaults, the result of which will always be the same.\n *\n * @private\n */\nexport class Properties<Props: Object> {\n properties: Props;\n defaultPropertyValues: PropertyValues<Props>;\n defaultTransitionablePropertyValues: TransitionablePropertyValues<Props>;\n defaultTransitioningPropertyValues: TransitioningPropertyValues<Props>;\n defaultPossiblyEvaluatedValues: PossiblyEvaluatedPropertyValues<Props>;\n overridableProperties: Array<string>;\n\n constructor(properties: Props) {\n this.properties = properties;\n this.defaultPropertyValues = ({}: any);\n this.defaultTransitionablePropertyValues = ({}: any);\n this.defaultTransitioningPropertyValues = ({}: any);\n this.defaultPossiblyEvaluatedValues = ({}: any);\n this.overridableProperties = ([]: any);\n\n 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 {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\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<typeof viewTypes>;\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<StructArrayMember>,\n size: number,\n alignment: ?number\n}\n\nexport type SerializedStructArray = {\n length: number,\n arrayBuffer: ArrayBuffer\n};\n\n/**\n * `StructArray` provides an abstraction over `ArrayBuffer` and `TypedArray`\n * making it behave like an array of typed structs.\n *\n * Conceptually, a StructArray is comprised of elements, i.e., instances of its\n * associated struct type. Each particular struct type, together with an\n * alignment size, determines the memory layout of a StructArray whose elements\n * are of that type. Thus, for each such layout that we need, we have\n * a corrseponding StructArrayLayout class, inheriting from StructArray and\n * implementing `emplaceBack()` and `_refreshViews()`.\n *\n * In some cases, where we need to access particular elements of a StructArray,\n * we implement a more specific subclass that inherits from one of the\n * StructArrayLayouts and adds a `get(i): T` accessor that returns a structured\n * object whose properties are proxies into the underlying memory space for the\n * i-th element. This affords the convience of working with (seemingly) plain\n * Javascript objects without the overhead of serializing/deserializing them\n * into ArrayBuffers for efficient web worker transfer.\n *\n * @private\n */\nclass StructArray {\n capacity: number;\n length: number;\n isTransferred: boolean;\n arrayBuffer: ArrayBuffer;\n uint8: Uint8Array;\n\n // The following properties are defined on the prototype.\n members: Array<StructArrayMember>;\n bytesPerElement: number;\n +emplaceBack: Function;\n +emplace: Function;\n\n constructor() {\n this.isTransferred = false;\n this.capacity = -1;\n this.resize(0);\n }\n\n /**\n * Serialize a StructArray instance. Serializes both the raw data and the\n * metadata needed to reconstruct the StructArray base class during\n * deserialization.\n * @private\n */\n static serialize(array: StructArray, transferables?: Array<Transferable>): SerializedStructArray {\n assert(!array.isTransferred);\n\n array._trim();\n\n if (transferables) {\n array.isTransferred = true;\n transferables.push(array.arrayBuffer);\n }\n\n return {\n length: array.length,\n arrayBuffer: array.arrayBuffer,\n };\n }\n\n static deserialize(input: SerializedStructArray) {\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/* eslint-disable camelcase */\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]: Uint8[4]\n * [8]: Float32[1]\n *\n * @private\n */\nclass StructArrayLayout2i4ub1f12 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n float32: Float32Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number) {\n const i = this.length;\n this.resize(i + 1);\n return this.emplace(i, v0, v1, v2, v3, v4, v5, v6);\n }\n\n emplace(i: number, v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number) {\n const o2 = i * 6;\n const o1 = i * 12;\n const o4 = i * 3;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.uint8[o1 + 4] = v2;\n this.uint8[o1 + 5] = v3;\n this.uint8[o1 + 6] = v4;\n this.uint8[o1 + 7] = v5;\n this.float32[o4 + 2] = v6;\n return i;\n }\n}\n\nStructArrayLayout2i4ub1f12.prototype.bytesPerElement = 12;\nregister('StructArrayLayout2i4ub1f12', StructArrayLayout2i4ub1f12);\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Float32[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[2]\n * [4]: Float32[4]\n * [20]: Int16[1]\n * [24]: Uint32[1]\n * [28]: Uint16[2]\n *\n * @private\n */\nclass StructArrayLayout2i4f1i1ul2ui32 extends StructArray {\n uint8: Uint8Array;\n int16: Int16Array;\n float32: Float32Array;\n uint32: Uint32Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.int16 = new Int16Array(this.arrayBuffer);\n this.float32 = new Float32Array(this.arrayBuffer);\n this.uint32 = new Uint32Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number, v4: number, v5: number, v6: number, v7: number, v8: number, v9: number) {\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 * 16;\n const o4 = i * 8;\n this.int16[o2 + 0] = v0;\n this.int16[o2 + 1] = v1;\n this.float32[o4 + 1] = v2;\n this.float32[o4 + 2] = v3;\n this.float32[o4 + 3] = v4;\n this.float32[o4 + 4] = v5;\n this.int16[o2 + 10] = v6;\n this.uint32[o4 + 6] = v7;\n this.uint16[o2 + 14] = v8;\n this.uint16[o2 + 15] = v9;\n return i;\n }\n}\n\nStructArrayLayout2i4f1i1ul2ui32.prototype.bytesPerElement = 32;\nregister('StructArrayLayout2i4f1i1ul2ui32', StructArrayLayout2i4f1i1ul2ui32);\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[3]\n *\n * @private\n */\nclass StructArrayLayout1ul3ui12 extends StructArray {\n uint8: Uint8Array;\n uint32: Uint32Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint32 = new Uint32Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number, v2: number, v3: number) {\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 * 3;\n const o2 = i * 6;\n this.uint32[o4 + 0] = v0;\n this.uint16[o2 + 2] = v1;\n this.uint16[o2 + 3] = v2;\n this.uint16[o2 + 4] = v3;\n return i;\n }\n}\n\nStructArrayLayout1ul3ui12.prototype.bytesPerElement = 12;\nregister('StructArrayLayout1ul3ui12', StructArrayLayout1ul3ui12);\n\n/**\n * Implementation of the StructArray layout:\n * [0]: Uint16[2]\n *\n * @private\n */\nclass StructArrayLayout2ui4 extends StructArray {\n uint8: Uint8Array;\n uint16: Uint16Array;\n\n _refreshViews() {\n this.uint8 = new Uint8Array(this.arrayBuffer);\n this.uint16 = new Uint16Array(this.arrayBuffer);\n }\n\n emplaceBack(v0: number, v1: number) {\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 padding: 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.float32[this._pos4 + 1]; }\n get y1() { return this._structArray.float32[this._pos4 + 2]; }\n get x2() { return this._structArray.float32[this._pos4 + 3]; }\n get y2() { return this._structArray.float32[this._pos4 + 4]; }\n get padding() { return this._structArray.int16[this._pos2 + 10]; }\n get featureIndex() { return this._structArray.uint32[this._pos4 + 6]; }\n get sourceLayerIndex() { return this._structArray.uint16[this._pos2 + 14]; }\n get bucketIndex() { return this._structArray.uint16[this._pos2 + 15]; }\n get anchorPoint() { return new Point(this.anchorPointX, this.anchorPointY); }\n}\n\nCollisionBoxStruct.prototype.size = 32;\n\nexport type CollisionBox = CollisionBoxStruct;\n\n/**\n * @private\n */\nexport class CollisionBoxArray extends StructArrayLayout2i4f1i1ul2ui32 {\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 layoutVertexArrayOffset: 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 get layoutVertexArrayOffset() { return this._structArray.uint16[this._pos2 + 4]; }\n}\n\nFeatureIndexStruct.prototype.size = 12;\n\nexport type FeatureIndex = FeatureIndexStruct;\n\n/**\n * @private\n */\nexport class FeatureIndexArray extends StructArrayLayout1ul3ui12 {\n /**\n * Return the FeatureIndexStruct at the given location in the array.\n * @param {number} index The index of the element.\n * @private\n */\n get(index: number): FeatureIndexStruct {\n assert(!this.isTransferred);\n return new FeatureIndexStruct(this, index);\n }\n}\n\nregister('FeatureIndexArray', FeatureIndexArray);\n\nclass FillExtrusionCentroidStruct extends Struct {\n _structArray: FillExtrusionCentroidArray;\n a_centroid_pos0: number;\n a_centroid_pos1: number;\n get a_centroid_pos0() { return this._structArray.uint16[this._pos2 + 0]; }\n get a_centroid_pos1() { return this._structArray.uint16[this._pos2 + 1]; }\n}\n\nFillExtrusionCentroidStruct.prototype.size = 4;\n\nexport type FillExtrusionCentroid = FillExtrusionCentroidStruct;\n\n/**\n * @private\n */\nexport class FillExtrusionCentroidArray extends StructArrayLayout2ui4 {\n /**\n * Return the FillExtrusionCentroidStruct at the given location in the array.\n * @param {number} index The index of the element.\n * @private\n */\n get(index: number): FillExtrusionCentroidStruct {\n assert(!this.isTransferred);\n return new FillExtrusionCentroidStruct(this, index);\n }\n}\n\nregister('FillExtrusionCentroidArray', FillExtrusionCentroidArray);\n\nexport {\n StructArrayLayout2i4,\n StructArrayLayout4i8,\n StructArrayLayout2i4ub1f12,\n StructArrayLayout2f8,\n StructArrayLayout10ui20,\n StructArrayLayout4i4ui4i24,\n StructArrayLayout3f12,\n StructArrayLayout1ul4,\n StructArrayLayout2i4f1i1ul2ui32,\n StructArrayLayout2i2i2i12,\n StructArrayLayout2f1f2i16,\n StructArrayLayout2ub2f12,\n StructArrayLayout3ui6,\n StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48,\n StructArrayLayout8i15ui1ul4f68,\n StructArrayLayout1f4,\n StructArrayLayout3i6,\n StructArrayLayout1ul3ui12,\n StructArrayLayout2ui4,\n StructArrayLayout1ui2,\n StructArrayLayout4f16,\n StructArrayLayout2i4 as PosArray,\n StructArrayLayout4i8 as RasterBoundsArray,\n StructArrayLayout2i4 as CircleLayoutArray,\n StructArrayLayout2i4 as FillLayoutArray,\n StructArrayLayout4i8 as FillExtrusionLayoutArray,\n StructArrayLayout2i4 as HeatmapLayoutArray,\n StructArrayLayout2i4ub1f12 as LineLayoutArray,\n 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 StructArrayLayout3f12 as CollisionVertexExtArray,\n StructArrayLayout3ui6 as QuadTriangleArray,\n StructArrayLayout3ui6 as TriangleIndexArray,\n StructArrayLayout2ui4 as LineIndexArray,\n StructArrayLayout1ui2 as LineStripIndexArray,\n StructArrayLayout3f12 as SkyboxVertexArray\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_to', components: 4, type: 'Uint16'},\n {name: 'a_pattern_from', components: 4, type: 'Uint16'},\n {name: 'a_pixel_ratio_to', components: 1, type: 'Uint16'},\n {name: 'a_pixel_ratio_from', components: 1, type: 'Uint16'},\n]);\n\nexport default patternAttributes;\n","/**\n * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)\n * \n * @author <a href=\"mailto:gary.court@gmail.com\">Gary Court</a>\n * @see http://github.com/garycourt/murmurhash-js\n * @author <a href=\"mailto:aappleby@gmail.com\">Austin Appleby</a>\n * @see http://sites.google.com/site/murmurhash/\n * \n * @param {string} key ASCII only\n * @param {number} seed Positive integer only\n * @return {number} 32-bit positive integer hash \n */\n\nfunction murmurhash3_32_gc(key, seed) {\n\tvar remainder, bytes, h1, h1b, c1, c1b, c2, c2b, k1, i;\n\t\n\tremainder = key.length & 3; // key.length % 4\n\tbytes = key.length - remainder;\n\th1 = seed;\n\tc1 = 0xcc9e2d51;\n\tc2 = 0x1b873593;\n\ti = 0;\n\t\n\twhile (i < bytes) {\n\t \tk1 = \n\t \t ((key.charCodeAt(i) & 0xff)) |\n\t \t ((key.charCodeAt(++i) & 0xff) << 8) |\n\t \t ((key.charCodeAt(++i) & 0xff) << 16) |\n\t \t ((key.charCodeAt(++i) & 0xff) << 24);\n\t\t++i;\n\t\t\n\t\tk1 = ((((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16))) & 0xffffffff;\n\t\tk1 = (k1 << 15) | (k1 >>> 17);\n\t\tk1 = ((((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16))) & 0xffffffff;\n\n\t\th1 ^= k1;\n h1 = (h1 << 13) | (h1 >>> 19);\n\t\th1b = ((((h1 & 0xffff) * 5) + ((((h1 >>> 16) * 5) & 0xffff) << 16))) & 0xffffffff;\n\t\th1 = (((h1b & 0xffff) + 0x6b64) + ((((h1b >>> 16) + 0xe654) & 0xffff) << 16));\n\t}\n\t\n\tk1 = 0;\n\t\n\tswitch (remainder) {\n\t\tcase 3: k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;\n\t\tcase 2: k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;\n\t\tcase 1: k1 ^= (key.charCodeAt(i) & 0xff);\n\t\t\n\t\tk1 = (((k1 & 0xffff) * c1) + ((((k1 >>> 16) * c1) & 0xffff) << 16)) & 0xffffffff;\n\t\tk1 = (k1 << 15) | (k1 >>> 17);\n\t\tk1 = (((k1 & 0xffff) * c2) + ((((k1 >>> 16) * c2) & 0xffff) << 16)) & 0xffffffff;\n\t\th1 ^= k1;\n\t}\n\t\n\th1 ^= key.length;\n\n\th1 ^= h1 >>> 16;\n\th1 = (((h1 & 0xffff) * 0x85ebca6b) + ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) & 0xffffffff;\n\th1 ^= h1 >>> 13;\n\th1 = ((((h1 & 0xffff) * 0xc2b2ae35) + ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16))) & 0xffffffff;\n\th1 ^= h1 >>> 16;\n\n\treturn h1 >>> 0;\n}\n\nif(typeof module !== \"undefined\") {\n module.exports = murmurhash3_32_gc\n}","/**\n * JS Implementation of MurmurHash2\n * \n * @author <a href=\"mailto:gary.court@gmail.com\">Gary Court</a>\n * @see http://github.com/garycourt/murmurhash-js\n * @author <a href=\"mailto:aappleby@gmail.com\">Austin Appleby</a>\n * @see http://sites.google.com/site/murmurhash/\n * \n * @param {string} str ASCII only\n * @param {number} seed Positive integer only\n * @return {number} 32-bit positive integer hash\n */\n\nfunction murmurhash2_32_gc(str, seed) {\n var\n l = str.length,\n h = seed ^ l,\n i = 0,\n k;\n \n while (l >= 4) {\n \tk = \n \t ((str.charCodeAt(i) & 0xff)) |\n \t ((str.charCodeAt(++i) & 0xff) << 8) |\n \t ((str.charCodeAt(++i) & 0xff) << 16) |\n \t ((str.charCodeAt(++i) & 0xff) << 24);\n \n k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n k ^= k >>> 24;\n k = (((k & 0xffff) * 0x5bd1e995) + ((((k >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n\n\th = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16)) ^ k;\n\n l -= 4;\n ++i;\n }\n \n switch (l) {\n case 3: h ^= (str.charCodeAt(i + 2) & 0xff) << 16;\n case 2: h ^= (str.charCodeAt(i + 1) & 0xff) << 8;\n case 1: h ^= (str.charCodeAt(i) & 0xff);\n h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n }\n\n h ^= h >>> 13;\n h = (((h & 0xffff) * 0x5bd1e995) + ((((h >>> 16) * 0x5bd1e995) & 0xffff) << 16));\n h ^= h >>> 15;\n\n return h >>> 0;\n}\n\nif(typeof module !== undefined) {\n module.exports = murmurhash2_32_gc\n}\n","var murmur3 = require(\"./murmurhash3_gc.js\")\nvar murmur2 = require(\"./murmurhash2_gc.js\")\n\nmodule.exports = murmur3\nmodule.exports.murmur3 = murmur3\nmodule.exports.murmur2 = murmur2\n","// @flow\n\nimport murmur3 from 'murmurhash-js';\nimport {register} from '../util/web_worker_transfer';\nimport {MAX_SAFE_INTEGER} from '../util/util';\nimport assert from 'assert';\n\ntype SerializedFeaturePositionMap = {\n ids: Float64Array;\n positions: Uint32Array;\n};\n\ntype FeaturePosition = {\n index: number;\n start: number;\n end: number;\n};\n\n// A transferable data structure that maps feature ids to their indices and buffer offsets\nexport default class FeaturePositionMap {\n ids: Array<number>;\n positions: Array<number>;\n indexed: boolean;\n\n constructor() {\n this.ids = [];\n this.positions = [];\n this.indexed = false;\n }\n\n add(id: mixed, index: number, start: number, end: number) {\n this.ids.push(getNumericId(id));\n this.positions.push(index, start, end);\n }\n\n getPositions(id: mixed): Array<FeaturePosition> {\n assert(this.indexed);\n\n const intId = getNumericId(id);\n\n // binary search for the first occurrence of id in this.ids;\n // relies on ids/positions being sorted by id, which happens in serialization\n let i = 0;\n let j = this.ids.length - 1;\n while (i < j) {\n const m = (i + j) >> 1;\n if (this.ids[m] >= intId) {\n j = m;\n } else {\n i = m + 1;\n }\n }\n const positions = [];\n while (this.ids[i] === intId) {\n const index = this.positions[3 * i];\n const start = this.positions[3 * i + 1];\n const end = this.positions[3 * i + 2];\n positions.push({index, start, end});\n i++;\n }\n return positions;\n }\n\n static serialize(map: FeaturePositionMap, transferables: Array<ArrayBuffer>): SerializedFeaturePositionMap {\n const ids = new Float64Array(map.ids);\n const positions = new Uint32Array(map.positions);\n\n sort(ids, positions, 0, ids.length - 1);\n\n if (transferables) {\n transferables.push(ids.buffer, positions.buffer);\n }\n\n return {ids, positions};\n }\n\n static deserialize(obj: SerializedFeaturePositionMap): FeaturePositionMap {\n const map = new FeaturePositionMap();\n // after transferring, we only use these arrays statically (no pushes),\n // so TypedArray vs Array distinction that flow points out doesn't matter\n map.ids = (obj.ids: any);\n map.positions = (obj.positions: any);\n map.indexed = true;\n return map;\n }\n}\n\nfunction getNumericId(value: mixed) {\n const numValue = +value;\n if (!isNaN(numValue) && 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<Us: Object>\n = $Exact<$ObjMap<Us, <V>(u: Uniform<V>) => V>>;\nexport type UniformLocations = {[_: string]: WebGLUniformLocation};\n\nclass Uniform<T> {\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<number> {\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<number> {\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<Color> {\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<Float32Array> {\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\nconst emptyMat3 = new Float32Array(9);\nclass UniformMatrix3f extends Uniform<Float32Array> {\n constructor(context: Context, location: WebGLUniformLocation) {\n super(context, location);\n this.current = emptyMat3;\n }\n\n set(v: Float32Array): void {\n for (let i = 0; i < 9; i++) {\n if (v[i] !== this.current[i]) {\n this.current = v;\n this.gl.uniformMatrix3fv(this.location, false, v);\n break;\n }\n }\n }\n}\n\nexport {\n Uniform,\n Uniform1i,\n Uniform1f,\n Uniform2f,\n Uniform3f,\n Uniform4f,\n UniformColor,\n UniformMatrix3f,\n UniformMatrix4f\n};\n\nexport type UniformBindings = {[_: string]: Uniform<any>};\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';\nimport assert from 'assert';\n\nexport type BinderUniform = {\n name: string,\n property: string,\n binding: Uniform<any>\n};\n\nfunction packColor(color: Color): [number, number] {\n return [\n packUint8ToFloat(255 * color.r, 255 * color.g),\n packUint8ToFloat(255 * color.b, 255 * color.a)\n ];\n}\n\n/**\n * `Binder` is the interface definition for the strategies for constructing,\n * uploading, and binding paint property data as GLSL attributes. Most style-\n * spec properties have a 1:1 relationship to shader attribute/uniforms, but\n * some require 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<string>;\n setUniform(uniform: Uniform<*>, globals: GlobalProperties, currentValue: PossiblyEvaluatedPropertyValue<*>, uniformName: string): void;\n getBinding(context: Context, location: WebGLUniformLocation, name: string): $Shape<Uniform<*>>;\n}\n\nclass ConstantBinder implements UniformBinder {\n value: mixed;\n type: string;\n uniformNames: Array<string>;\n\n constructor(value: mixed, names: Array<string>, type: string) {\n this.value = value;\n this.uniformNames = names.map(name => `u_${name}`);\n this.type = type;\n }\n\n setUniform(uniform: Uniform<*>, globals: GlobalProperties, currentValue: PossiblyEvaluatedPropertyValue<mixed>): void {\n uniform.set(currentValue.constantOr(this.value));\n }\n\n getBinding(context: Context, location: WebGLUniformLocation, _: string): $Shape<Uniform<any>> {\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<string>;\n patternFrom: ?Array<number>;\n patternTo: ?Array<number>;\n pixelRatioFrom: number;\n pixelRatioTo: number;\n\n constructor(value: mixed, names: Array<string>) {\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<mixed>, 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<Uniform<any>> {\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<StructArrayMember>;\n paintVertexBuffer: ?VertexBuffer;\n\n constructor(expression: SourceExpression, names: Array<string>, type: string, PaintVertexArray: Class<StructArray>) {\n this.expression = expression;\n this.type = type;\n this.maxValue = 0;\n this.paintVertexAttributes = names.map((name) => ({\n name: `a_${name}`,\n type: 'Float32',\n components: type === 'color' ? 2 : 1,\n offset: 0\n }));\n this.paintVertexArray = new PaintVertexArray();\n }\n\n populatePaintArray(newLength: number, feature: Feature, imagePositions: {[_: 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<string>;\n type: string;\n useIntegerZoom: boolean;\n zoom: number;\n maxValue: number;\n\n paintVertexArray: StructArray;\n paintVertexAttributes: Array<StructArrayMember>;\n paintVertexBuffer: ?VertexBuffer;\n\n constructor(expression: CompositeExpression, names: Array<string>, type: string, useIntegerZoom: boolean, zoom: number, PaintVertexArray: Class<StructArray>) {\n this.expression = expression;\n this.uniformNames = names.map(name => `u_${name}_t`);\n this.type = type;\n this.useIntegerZoom = useIntegerZoom;\n this.zoom = zoom;\n this.maxValue = 0;\n this.paintVertexAttributes = names.map((name) => ({\n name: `a_${name}`,\n type: 'Float32',\n components: type === 'color' ? 4 : 2,\n offset: 0\n }));\n this.paintVertexArray = new PaintVertexArray();\n }\n\n populatePaintArray(newLength: number, feature: Feature, imagePositions: {[_: 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<StructArrayMember>;\n\n constructor(expression: CompositeExpression, names: Array<string>, type: string, useIntegerZoom: boolean, zoom: number, PaintVertexArray: Class<StructArray>, layerId: string) {\n this.expression = expression;\n this.type = type;\n this.useIntegerZoom = useIntegerZoom;\n this.zoom = zoom;\n this.layerId = layerId;\n\n for (let i = 0; i < names.length; ++i) {\n assert(`a_${names[i]}` === patternAttributes.members[i].name);\n }\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<VertexBuffer>;\n\n constructor(layer: TypedStyleLayer, zoom: number, filterProperties: (_: string) => boolean = () => true) {\n this.binders = {};\n this._buffers = [];\n\n const keys = [];\n\n for (const property in layer.paint._values) {\n if (!filterProperties(property)) continue;\n const value = layer.paint.get(property);\n if (!(value instanceof PossiblyEvaluatedPropertyValue) || !supportsPropertyExpression(value.property.specification)) {\n continue;\n }\n const names = paintAttributeNames(property, layer.type);\n const expression = value.value;\n const type = value.property.specification.type;\n const useIntegerZoom = value.property.useIntegerZoom;\n const 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, names, 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<string> {\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<string> {\n const result = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof SourceExpressionBinder || binder instanceof CompositeExpressionBinder) {\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<string> {\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<VertexBuffer> {\n return this._buffers;\n }\n\n getUniforms(context: Context, locations: UniformLocations): Array<BinderUniform> {\n const uniforms = [];\n for (const property in this.binders) {\n const binder = this.binders[property];\n if (binder instanceof ConstantBinder || binder instanceof 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<Properties: Object>(context: Context, binderUniforms: Array<BinderUniform>, properties: PossiblyEvaluated<Properties>, globals: GlobalProperties) {\n // Uniform state bindings are owned by the Program, but we set them\n // from within the 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<Layer: TypedStyleLayer> {\n programConfigurations: {[_: string]: ProgramConfiguration};\n needsUpload: boolean;\n _featureMap: FeaturePositionMap;\n _bufferOffset: number;\n\n constructor(layers: $ReadOnlyArray<Layer>, zoom: number, filterProperties: (_: string) => boolean = () => true) {\n this.programConfigurations = {};\n for (const layer of layers) {\n this.programConfigurations[layer.id] = new ProgramConfiguration(layer, zoom, filterProperties);\n }\n this.needsUpload = false;\n this._featureMap = new FeaturePositionMap();\n this._bufferOffset = 0;\n }\n\n populatePaintArrays(length: number, feature: Feature, index: number, imagePositions: {[_: 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<TypedStyleLayer>, 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\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';\nimport ProgramConfiguration from '../data/program_configuration';\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';\nimport type {TilespaceQueryGeometry} from './query_geometry';\nimport type {DEMSampler} from '../terrain/elevation';\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<any>;\n +layout: mixed;\n\n _transitionablePaint: Transitionable<any>;\n _transitioningPaint: Transitioning<any>;\n +paint: mixed;\n\n _featureFilter: FeatureFilter;\n\n +queryRadius: (bucket: Bucket) => number;\n +queryIntersectsFeature: (queryGeometry: TilespaceQueryGeometry,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array<Array<Point>>,\n zoom: number,\n transform: Transform,\n pixelPosMatrix: Float32Array,\n elevationHelper: ?DEMSampler,\n layoutVertexArrayOffset: number) => boolean | number;\n\n +onAdd: ?(map: Map) => void;\n +onRemove: ?(map: Map) => void;\n\n constructor(layer: LayerSpecification | CustomLayerInterface, properties: $ReadOnly<{layout?: Properties<*>, paint?: Properties<*>}>) {\n super();\n\n this.id = layer.id;\n this.type = layer.type;\n this._featureFilter = {filter: () => true, needGeometry: false};\n\n if (layer.type === 'custom') return;\n\n layer = ((layer: any): LayerSpecification);\n\n this.metadata = layer.metadata;\n this.minzoom = layer.minzoom;\n this.maxzoom = layer.maxzoom;\n\n if (layer.type !== 'background' && layer.type !== 'sky') {\n this.source = layer.source;\n this.sourceLayer = layer['source-layer'];\n this.filter = layer.filter;\n }\n\n if (properties.layout) {\n this._unevaluatedLayout = new Layout(properties.layout);\n }\n\n if (properties.paint) {\n this._transitionablePaint = new Transitionable(properties.paint);\n\n for (const property in layer.paint) {\n this.setPaintProperty(property, layer.paint[property], {validate: false});\n }\n for (const property in layer.layout) {\n this.setLayoutProperty(property, layer.layout[property], {validate: false});\n }\n\n this._transitioningPaint = this._transitionablePaint.untransitioned();\n //$FlowFixMe\n this.paint = new PossiblyEvaluated(properties.paint);\n }\n }\n\n 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 getProgramIds(): string[] | null {\n // No-op; can be overridden by derived classes.\n return null;\n }\n\n getProgramConfiguration(_: number): ProgramConfiguration | null {\n // No-op; can be overridden by derived classes.\n return null;\n }\n\n // eslint-disable-next-line no-unused-vars\n _handleOverridablePaintPropertyUpdate<T, R>(name: string, oldValue: PropertyValue<T, R>, newValue: PropertyValue<T, R>): boolean {\n // No-op; can be overridden by derived classes.\n return false;\n }\n\n isHidden(zoom: number) {\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<string>) {\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 isSky() {\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\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<Segment>;\n\n constructor(segments?: Array<Segment> = []) {\n this.segments = segments;\n }\n\n prepareSegment(numVertices: number, layoutVertexArray: StructArray, indexArray: StructArray, sortKey?: number): Segment {\n let segment: Segment = this.segments[this.segments.length - 1];\n if (numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH) warnOnce(`Max vertices per segment is ${SegmentVector.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${numVertices}`);\n if (!segment || segment.vertexLength + numVertices > SegmentVector.MAX_VERTEX_ARRAY_LENGTH || segment.sortKey !== sortKey) {\n segment = ({\n vertexOffset: layoutVertexArray.length,\n primitiveOffset: indexArray.length,\n vertexLength: 0,\n primitiveLength: 0\n }: any);\n if (sortKey !== undefined) segment.sortKey = sortKey;\n this.segments.push(segment);\n }\n return segment;\n }\n\n get() {\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 {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<Array<Point>> {\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<Array<Point>>\n};\n\n/**\n * Construct a new feature based on a VectorTileFeature for expression evaluation, the geometry of which\n * will be loaded based on necessity.\n * @param {VectorTileFeature} feature\n * @param {boolean} needGeometry\n * @private\n */\nexport default function toEvaluationFeature(feature: 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<Layer: CircleStyleLayer | HeatmapStyleLayer> implements Bucket {\n index: number;\n zoom: number;\n overscaling: number;\n layerIds: Array<string>;\n layers: Array<Layer>;\n stateDependentLayers: Array<Layer>;\n stateDependentLayerIds: Array<string>;\n\n layoutVertexArray: CircleLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n hasPattern: boolean;\n programConfigurations: ProgramConfigurationSet<Layer>;\n segments: SegmentVector;\n uploaded: boolean;\n\n constructor(options: BucketParameters<Layer>) {\n this.zoom = options.zoom;\n this.overscaling = options.overscaling;\n this.layers = options.layers;\n this.layerIds = this.layers.map(layer => layer.id);\n this.index = options.index;\n this.hasPattern = false;\n\n this.layoutVertexArray = new CircleLayoutArray();\n this.indexArray = new TriangleIndexArray();\n this.segments = new SegmentVector();\n this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n }\n\n populate(features: Array<IndexedFeature>, options: PopulateParameters, canonical: CanonicalTileID) {\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<Array<Point>>, 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<Point>;\ntype MultiLine = Array<Line>;\ntype Ring = Array<Point>;\ntype Polygon = Array<Point>;\ntype MultiPolygon = Array<Polygon>;\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<Ring>, 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<Point>) {\n const tl = corners[0];\n const br = corners[2];\n // the edge and box do not intersect in either the x or y dimensions\n if (((e1.x < tl.x) && (e2.x < tl.x)) ||\n ((e1.x > br.x) && (e2.x > br.x)) ||\n ((e1.y < tl.y) && (e2.y < tl.y)) ||\n ((e1.y > br.y) && (e2.y > br.y))) return false;\n\n // check if all corners of the box are on the same side of the edge\n const dir = isCounterClockwise(e1, e2, corners[0]);\n return dir !== isCounterClockwise(e1, e2, corners[1]) ||\n dir !== isCounterClockwise(e1, e2, corners[2]) ||\n dir !== isCounterClockwise(e1, e2, corners[3]);\n}\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport type {PossiblyEvaluatedPropertyValue} from \"./properties\";\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<any>).value;\n if (value.kind === 'constant') {\n return value.value;\n } else {\n return bucket.programConfigurations.get(layer.id).getMaxValue(property);\n }\n}\n\nexport function translateDistance(translate: [number, number]) {\n return Math.sqrt(translate[0] * translate[0] + translate[1] * translate[1]);\n}\n\nexport function translate(queryGeometry: Array<Point>,\n translate: [number, number],\n translateAnchor: 'viewport' | 'map',\n bearing: number,\n pixelsToTileUnits: number) {\n if (!translate[0] && !translate[1]) {\n return queryGeometry;\n }\n const pt = Point.convert(translate)._mult(pixelsToTileUnits);\n\n if (translateAnchor === \"viewport\") {\n pt._rotate(-bearing);\n }\n\n const translated = [];\n for (let i = 0; i < queryGeometry.length; i++) {\n const point = queryGeometry[i];\n translated.push(point.sub(pt));\n }\n return translated;\n}\n\nexport function tilespaceTranslate(translate: [number, number],\n translateAnchor: 'viewport' | 'map',\n bearing: number,\n pixelsToTileUnits: number): Point {\n const pt = Point.convert(translate)._mult(pixelsToTileUnits);\n\n if (translateAnchor === \"viewport\") {\n pt._rotate(-bearing);\n }\n\n return pt;\n}\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest';\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<number>,\n|};\n\nconst layout: Properties<LayoutProps> = new Properties({\n \"circle-sort-key\": new DataDrivenProperty(styleSpec[\"layout_circle\"][\"circle-sort-key\"]),\n});\n\nexport type PaintProps = {|\n \"circle-radius\": DataDrivenProperty<number>,\n \"circle-color\": DataDrivenProperty<Color>,\n \"circle-blur\": DataDrivenProperty<number>,\n \"circle-opacity\": DataDrivenProperty<number>,\n \"circle-translate\": DataConstantProperty<[number, number]>,\n \"circle-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"circle-pitch-scale\": DataConstantProperty<\"map\" | \"viewport\">,\n \"circle-pitch-alignment\": DataConstantProperty<\"map\" | \"viewport\">,\n \"circle-stroke-width\": DataDrivenProperty<number>,\n \"circle-stroke-color\": DataDrivenProperty<Color>,\n \"circle-stroke-opacity\": DataDrivenProperty<number>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"circle-radius\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-radius\"]),\n \"circle-color\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-color\"]),\n \"circle-blur\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-blur\"]),\n \"circle-opacity\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-opacity\"]),\n \"circle-translate\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-translate\"]),\n \"circle-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-translate-anchor\"]),\n \"circle-pitch-scale\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-pitch-scale\"]),\n \"circle-pitch-alignment\": new DataConstantProperty(styleSpec[\"paint_circle\"][\"circle-pitch-alignment\"]),\n \"circle-stroke-width\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-width\"]),\n \"circle-stroke-color\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-color\"]),\n \"circle-stroke-opacity\": new DataDrivenProperty(styleSpec[\"paint_circle\"][\"circle-stroke-opacity\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint, layout }: $Exact<{\n paint: Properties<PaintProps>, layout: Properties<LayoutProps>\n}>);\n","/**\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 * 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;","import * as glMatrix from \"./common.js\";\n/**\r\n * 4x4 Matrix<br>Format: column-major, when typed out it looks like row-major<br>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\";\nimport * as mat3 from \"./mat3.js\";\nimport * as vec3 from \"./vec3.js\";\nimport * as vec4 from \"./vec4.js\";\n/**\r\n * Quaternion\r\n * @module quat\r\n */\n\n/**\r\n * Creates a new identity quat\r\n *\r\n * @returns {quat} a new quaternion\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 }\n\n out[3] = 1;\n return out;\n}\n/**\r\n * Set a quat to the identity quaternion\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @returns {quat} out\r\n */\n\nexport function identity(out) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 1;\n return out;\n}\n/**\r\n * Sets a quat from the given angle and rotation axis,\r\n * then returns it.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {vec3} axis the axis around which to rotate\r\n * @param {Number} rad the angle in radians\r\n * @returns {quat} out\r\n **/\n\nexport function setAxisAngle(out, axis, rad) {\n rad = rad * 0.5;\n var s = Math.sin(rad);\n out[0] = s * axis[0];\n out[1] = s * axis[1];\n out[2] = s * axis[2];\n out[3] = Math.cos(rad);\n return out;\n}\n/**\r\n * Gets the rotation axis and angle for a given\r\n * quaternion. If a quaternion is created with\r\n * setAxisAngle, this method will return the same\r\n * values as providied in the original parameter list\r\n * OR functionally equivalent values.\r\n * Example: The quaternion formed by axis [0, 0, 1] and\r\n * angle -90 is the same as the quaternion formed by\r\n * [0, 0, 1] and 270. This method favors the latter.\r\n * @param {vec3} out_axis Vector receiving the axis of rotation\r\n * @param {quat} q Quaternion to be decomposed\r\n * @return {Number} Angle, in radians, of the rotation\r\n */\n\nexport function getAxisAngle(out_axis, q) {\n var rad = Math.acos(q[3]) * 2.0;\n var s = Math.sin(rad / 2.0);\n\n if (s > glMatrix.EPSILON) {\n out_axis[0] = q[0] / s;\n out_axis[1] = q[1] / s;\n out_axis[2] = q[2] / s;\n } else {\n // If s is zero, return any axis (no rotation - axis does not matter)\n out_axis[0] = 1;\n out_axis[1] = 0;\n out_axis[2] = 0;\n }\n\n return rad;\n}\n/**\r\n * Gets the angular distance between two unit quaternions\r\n *\r\n * @param {quat} a Origin unit quaternion\r\n * @param {quat} b Destination unit quaternion\r\n * @return {Number} Angle, in radians, between the two quaternions\r\n */\n\nexport function getAngle(a, b) {\n var dotproduct = dot(a, b);\n return Math.acos(2 * dotproduct * dotproduct - 1);\n}\n/**\r\n * Multiplies two quat's\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {quat} a the first operand\r\n * @param {quat} b the second operand\r\n * @returns {quat} out\r\n */\n\nexport function multiply(out, a, b) {\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = b[0],\n by = b[1],\n bz = b[2],\n bw = b[3];\n out[0] = ax * bw + aw * bx + ay * bz - az * by;\n out[1] = ay * bw + aw * by + az * bx - ax * bz;\n out[2] = az * bw + aw * bz + ax * by - ay * bx;\n out[3] = aw * bw - ax * bx - ay * by - az * bz;\n return out;\n}\n/**\r\n * Rotates a quaternion by the given angle about the X axis\r\n *\r\n * @param {quat} out quat receiving operation result\r\n * @param {quat} a quat to rotate\r\n * @param {number} rad angle (in radians) to rotate\r\n * @returns {quat} out\r\n */\n\nexport function rotateX(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw + aw * bx;\n out[1] = ay * bw + az * bx;\n out[2] = az * bw - ay * bx;\n out[3] = aw * bw - ax * bx;\n return out;\n}\n/**\r\n * Rotates a quaternion by the given angle about the Y axis\r\n *\r\n * @param {quat} out quat receiving operation result\r\n * @param {quat} a quat to rotate\r\n * @param {number} rad angle (in radians) to rotate\r\n * @returns {quat} out\r\n */\n\nexport function rotateY(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var by = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw - az * by;\n out[1] = ay * bw + aw * by;\n out[2] = az * bw + ax * by;\n out[3] = aw * bw - ay * by;\n return out;\n}\n/**\r\n * Rotates a quaternion by the given angle about the Z axis\r\n *\r\n * @param {quat} out quat receiving operation result\r\n * @param {quat} a quat to rotate\r\n * @param {number} rad angle (in radians) to rotate\r\n * @returns {quat} out\r\n */\n\nexport function rotateZ(out, a, rad) {\n rad *= 0.5;\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bz = Math.sin(rad),\n bw = Math.cos(rad);\n out[0] = ax * bw + ay * bz;\n out[1] = ay * bw - ax * bz;\n out[2] = az * bw + aw * bz;\n out[3] = aw * bw - az * bz;\n return out;\n}\n/**\r\n * Calculates the W component of a quat from the X, Y, and Z components.\r\n * Assumes that quaternion is 1 unit in length.\r\n * Any existing W component will be ignored.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {quat} a quat to calculate W component of\r\n * @returns {quat} out\r\n */\n\nexport function calculateW(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2];\n out[0] = x;\n out[1] = y;\n out[2] = z;\n out[3] = Math.sqrt(Math.abs(1.0 - x * x - y * y - z * z));\n return out;\n}\n/**\r\n * Calculate the exponential of a unit quaternion.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {quat} a quat to calculate the exponential of\r\n * @returns {quat} out\r\n */\n\nexport function exp(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n var r = Math.sqrt(x * x + y * y + z * z);\n var et = Math.exp(w);\n var s = r > 0 ? et * Math.sin(r) / r : 0;\n out[0] = x * s;\n out[1] = y * s;\n out[2] = z * s;\n out[3] = et * Math.cos(r);\n return out;\n}\n/**\r\n * Calculate the natural logarithm of a unit quaternion.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {quat} a quat to calculate the exponential of\r\n * @returns {quat} out\r\n */\n\nexport function ln(out, a) {\n var x = a[0],\n y = a[1],\n z = a[2],\n w = a[3];\n var r = Math.sqrt(x * x + y * y + z * z);\n var t = r > 0 ? Math.atan2(r, w) / r : 0;\n out[0] = x * t;\n out[1] = y * t;\n out[2] = z * t;\n out[3] = 0.5 * Math.log(x * x + y * y + z * z + w * w);\n return out;\n}\n/**\r\n * Calculate the scalar power of a unit quaternion.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {quat} a quat to calculate the exponential of\r\n * @param {Number} b amount to scale the quaternion by\r\n * @returns {quat} out\r\n */\n\nexport function pow(out, a, b) {\n ln(out, a);\n scale(out, out, b);\n exp(out, out);\n return out;\n}\n/**\r\n * Performs a spherical linear interpolation between two quat\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {quat} a the first operand\r\n * @param {quat} b the second operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {quat} out\r\n */\n\nexport function slerp(out, a, b, t) {\n // benchmarks:\n // http://jsperf.com/quaternion-slerp-implementations\n var ax = a[0],\n ay = a[1],\n az = a[2],\n aw = a[3];\n var bx = b[0],\n by = b[1],\n bz = b[2],\n bw = b[3];\n var omega, cosom, sinom, scale0, scale1; // calc cosine\n\n cosom = ax * bx + ay * by + az * bz + aw * bw; // adjust signs (if necessary)\n\n if (cosom < 0.0) {\n cosom = -cosom;\n bx = -bx;\n by = -by;\n bz = -bz;\n bw = -bw;\n } // calculate coefficients\n\n\n if (1.0 - cosom > glMatrix.EPSILON) {\n // standard case (slerp)\n omega = Math.acos(cosom);\n sinom = Math.sin(omega);\n scale0 = Math.sin((1.0 - t) * omega) / sinom;\n scale1 = Math.sin(t * omega) / sinom;\n } else {\n // \"from\" and \"to\" quaternions are very close\n // ... so we can do a linear interpolation\n scale0 = 1.0 - t;\n scale1 = t;\n } // calculate final values\n\n\n out[0] = scale0 * ax + scale1 * bx;\n out[1] = scale0 * ay + scale1 * by;\n out[2] = scale0 * az + scale1 * bz;\n out[3] = scale0 * aw + scale1 * bw;\n return out;\n}\n/**\r\n * Generates a random unit quaternion\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @returns {quat} out\r\n */\n\nexport function random(out) {\n // Implementation of http://planning.cs.uiuc.edu/node198.html\n // TODO: Calling random 3 times is probably not the fastest solution\n var u1 = glMatrix.RANDOM();\n var u2 = glMatrix.RANDOM();\n var u3 = glMatrix.RANDOM();\n var sqrt1MinusU1 = Math.sqrt(1 - u1);\n var sqrtU1 = Math.sqrt(u1);\n out[0] = sqrt1MinusU1 * Math.sin(2.0 * Math.PI * u2);\n out[1] = sqrt1MinusU1 * Math.cos(2.0 * Math.PI * u2);\n out[2] = sqrtU1 * Math.sin(2.0 * Math.PI * u3);\n out[3] = sqrtU1 * Math.cos(2.0 * Math.PI * u3);\n return out;\n}\n/**\r\n * Calculates the inverse of a quat\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {quat} a quat to calculate inverse of\r\n * @returns {quat} 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];\n var dot = a0 * a0 + a1 * a1 + a2 * a2 + a3 * a3;\n var invDot = dot ? 1.0 / dot : 0; // TODO: Would be faster to return [0,0,0,0] immediately if dot == 0\n\n out[0] = -a0 * invDot;\n out[1] = -a1 * invDot;\n out[2] = -a2 * invDot;\n out[3] = a3 * invDot;\n return out;\n}\n/**\r\n * Calculates the conjugate of a quat\r\n * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {quat} a quat to calculate conjugate of\r\n * @returns {quat} out\r\n */\n\nexport function conjugate(out, a) {\n out[0] = -a[0];\n out[1] = -a[1];\n out[2] = -a[2];\n out[3] = a[3];\n return out;\n}\n/**\r\n * Creates a quaternion from the given 3x3 rotation matrix.\r\n *\r\n * NOTE: The resultant quaternion is not normalized, so you should be sure\r\n * to renormalize the quaternion yourself where necessary.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {mat3} m rotation matrix\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport function fromMat3(out, m) {\n // Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes\n // article \"Quaternion Calculus and Fast Animation\".\n var fTrace = m[0] + m[4] + m[8];\n var fRoot;\n\n if (fTrace > 0.0) {\n // |w| > 1/2, may as well choose w > 1/2\n fRoot = Math.sqrt(fTrace + 1.0); // 2w\n\n out[3] = 0.5 * fRoot;\n fRoot = 0.5 / fRoot; // 1/(4w)\n\n out[0] = (m[5] - m[7]) * fRoot;\n out[1] = (m[6] - m[2]) * fRoot;\n out[2] = (m[1] - m[3]) * fRoot;\n } else {\n // |w| <= 1/2\n var i = 0;\n if (m[4] > m[0]) i = 1;\n if (m[8] > m[i * 3 + i]) i = 2;\n var j = (i + 1) % 3;\n var k = (i + 2) % 3;\n fRoot = Math.sqrt(m[i * 3 + i] - m[j * 3 + j] - m[k * 3 + k] + 1.0);\n out[i] = 0.5 * fRoot;\n fRoot = 0.5 / fRoot;\n out[3] = (m[j * 3 + k] - m[k * 3 + j]) * fRoot;\n out[j] = (m[j * 3 + i] + m[i * 3 + j]) * fRoot;\n out[k] = (m[k * 3 + i] + m[i * 3 + k]) * fRoot;\n }\n\n return out;\n}\n/**\r\n * Creates a quaternion from the given euler angle x, y, z.\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {x} Angle to rotate around X axis in degrees.\r\n * @param {y} Angle to rotate around Y axis in degrees.\r\n * @param {z} Angle to rotate around Z axis in degrees.\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport function fromEuler(out, x, y, z) {\n var halfToRad = 0.5 * Math.PI / 180.0;\n x *= halfToRad;\n y *= halfToRad;\n z *= halfToRad;\n var sx = Math.sin(x);\n var cx = Math.cos(x);\n var sy = Math.sin(y);\n var cy = Math.cos(y);\n var sz = Math.sin(z);\n var cz = Math.cos(z);\n out[0] = sx * cy * cz - cx * sy * sz;\n out[1] = cx * sy * cz + sx * cy * sz;\n out[2] = cx * cy * sz - sx * sy * cz;\n out[3] = cx * cy * cz + sx * sy * sz;\n return out;\n}\n/**\r\n * Returns a string representation of a quatenion\r\n *\r\n * @param {quat} 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 \"quat(\" + a[0] + \", \" + a[1] + \", \" + a[2] + \", \" + a[3] + \")\";\n}\n/**\r\n * Creates a new quat initialized with values from an existing quaternion\r\n *\r\n * @param {quat} a quaternion to clone\r\n * @returns {quat} a new quaternion\r\n * @function\r\n */\n\nexport var clone = vec4.clone;\n/**\r\n * Creates a new quat 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 {quat} a new quaternion\r\n * @function\r\n */\n\nexport var fromValues = vec4.fromValues;\n/**\r\n * Copy the values from one quat to another\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {quat} a the source quaternion\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport var copy = vec4.copy;\n/**\r\n * Set the components of a quat to the given values\r\n *\r\n * @param {quat} out the receiving quaternion\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 {quat} out\r\n * @function\r\n */\n\nexport var set = vec4.set;\n/**\r\n * Adds two quat's\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {quat} a the first operand\r\n * @param {quat} b the second operand\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport var add = vec4.add;\n/**\r\n * Alias for {@link quat.multiply}\r\n * @function\r\n */\n\nexport var mul = multiply;\n/**\r\n * Scales a quat by a scalar number\r\n *\r\n * @param {quat} out the receiving vector\r\n * @param {quat} a the vector to scale\r\n * @param {Number} b amount to scale the vector by\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport var scale = vec4.scale;\n/**\r\n * Calculates the dot product of two quat's\r\n *\r\n * @param {quat} a the first operand\r\n * @param {quat} b the second operand\r\n * @returns {Number} dot product of a and b\r\n * @function\r\n */\n\nexport var dot = vec4.dot;\n/**\r\n * Performs a linear interpolation between two quat's\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {quat} a the first operand\r\n * @param {quat} b the second operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport var lerp = vec4.lerp;\n/**\r\n * Calculates the length of a quat\r\n *\r\n * @param {quat} a vector to calculate length of\r\n * @returns {Number} length of a\r\n */\n\nexport var length = vec4.length;\n/**\r\n * Alias for {@link quat.length}\r\n * @function\r\n */\n\nexport var len = length;\n/**\r\n * Calculates the squared length of a quat\r\n *\r\n * @param {quat} a vector to calculate squared length of\r\n * @returns {Number} squared length of a\r\n * @function\r\n */\n\nexport var squaredLength = vec4.squaredLength;\n/**\r\n * Alias for {@link quat.squaredLength}\r\n * @function\r\n */\n\nexport var sqrLen = squaredLength;\n/**\r\n * Normalize a quat\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {quat} a quaternion to normalize\r\n * @returns {quat} out\r\n * @function\r\n */\n\nexport var normalize = vec4.normalize;\n/**\r\n * Returns whether or not the quaternions have exactly the same elements in the same position (when compared with ===)\r\n *\r\n * @param {quat} a The first quaternion.\r\n * @param {quat} b The second quaternion.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport var exactEquals = vec4.exactEquals;\n/**\r\n * Returns whether or not the quaternions have approximately the same elements in the same position.\r\n *\r\n * @param {quat} a The first vector.\r\n * @param {quat} b The second vector.\r\n * @returns {Boolean} True if the vectors are equal, false otherwise.\r\n */\n\nexport var equals = vec4.equals;\n/**\r\n * Sets a quaternion to represent the shortest rotation from one\r\n * vector to another.\r\n *\r\n * Both vectors are assumed to be unit length.\r\n *\r\n * @param {quat} out the receiving quaternion.\r\n * @param {vec3} a the initial vector\r\n * @param {vec3} b the destination vector\r\n * @returns {quat} out\r\n */\n\nexport var rotationTo = function () {\n var tmpvec3 = vec3.create();\n var xUnitVec3 = vec3.fromValues(1, 0, 0);\n var yUnitVec3 = vec3.fromValues(0, 1, 0);\n return function (out, a, b) {\n var dot = vec3.dot(a, b);\n\n if (dot < -0.999999) {\n vec3.cross(tmpvec3, xUnitVec3, a);\n if (vec3.len(tmpvec3) < 0.000001) vec3.cross(tmpvec3, yUnitVec3, a);\n vec3.normalize(tmpvec3, tmpvec3);\n setAxisAngle(out, tmpvec3, Math.PI);\n return out;\n } else if (dot > 0.999999) {\n out[0] = 0;\n out[1] = 0;\n out[2] = 0;\n out[3] = 1;\n return out;\n } else {\n vec3.cross(tmpvec3, a, b);\n out[0] = tmpvec3[0];\n out[1] = tmpvec3[1];\n out[2] = tmpvec3[2];\n out[3] = 1 + dot;\n return normalize(out, out);\n }\n };\n}();\n/**\r\n * Performs a spherical linear interpolation with two control points\r\n *\r\n * @param {quat} out the receiving quaternion\r\n * @param {quat} a the first operand\r\n * @param {quat} b the second operand\r\n * @param {quat} c the third operand\r\n * @param {quat} d the fourth operand\r\n * @param {Number} t interpolation amount, in the range [0-1], between the two inputs\r\n * @returns {quat} out\r\n */\n\nexport var sqlerp = function () {\n var temp1 = create();\n var temp2 = create();\n return function (out, a, b, c, d, t) {\n slerp(temp1, a, d, t);\n slerp(temp2, b, c, t);\n slerp(out, temp1, temp2, 2 * t * (1 - t));\n return out;\n };\n}();\n/**\r\n * Sets the specified quaternion with values corresponding to the given\r\n * axes. Each axis is a vec3 and is expected to be unit length and\r\n * perpendicular to all other specified axes.\r\n *\r\n * @param {vec3} view the vector representing the viewing direction\r\n * @param {vec3} right the vector representing the local \"right\" direction\r\n * @param {vec3} up the vector representing the local \"up\" direction\r\n * @returns {quat} out\r\n */\n\nexport var setAxes = function () {\n var matr = mat3.create();\n return function (out, view, right, up) {\n matr[0] = right[0];\n matr[3] = right[1];\n matr[6] = right[2];\n matr[1] = up[0];\n matr[4] = up[1];\n matr[7] = up[2];\n matr[2] = -view[0];\n matr[5] = -view[1];\n matr[8] = -view[2];\n return normalize(out, fromMat3(out, matr));\n };\n}();","// @flow\n\nimport {vec3, vec4} from 'gl-matrix';\n\nclass Ray {\n pos: vec3;\n dir: vec3;\n\n constructor(pos_: vec3, dir_: vec3) {\n this.pos = pos_;\n this.dir = dir_;\n }\n\n intersectsPlane(pt: vec3, normal: vec3, out: vec3): boolean {\n const D = vec3.dot(normal, this.dir);\n\n // ray is parallel to plane, so it misses\n if (Math.abs(D) < 1e-6) { return false; }\n\n const t = vec3.dot(vec3.sub(vec3.create(), pt, this.pos), normal) / D;\n const intersection = vec3.scaleAndAdd(vec3.create(), this.pos, this.dir, t);\n vec3.copy(out, intersection);\n return true;\n }\n}\n\nclass Frustum {\n points: Array<Array<number>>;\n planes: Array<Array<number>>;\n\n constructor(points_: Array<Array<number>>, planes_: Array<Array<number>>) {\n this.points = points_;\n this.planes = planes_;\n }\n\n static fromInvProjectionMatrix(invProj: Float64Array, worldSize: number, zoom: number): Frustum {\n const clipSpaceCorners = [\n [-1, 1, -1, 1],\n [ 1, 1, -1, 1],\n [ 1, -1, -1, 1],\n [-1, -1, -1, 1],\n [-1, 1, 1, 1],\n [ 1, 1, 1, 1],\n [ 1, -1, 1, 1],\n [-1, -1, 1, 1]\n ];\n\n const scale = Math.pow(2, zoom);\n\n // Transform frustum corner points from clip space to tile space\n const frustumCoords = clipSpaceCorners\n .map(v => {\n const s = vec4.transformMat4([], v, invProj);\n const k = 1.0 / s[3] / worldSize * scale;\n // Z scale in meters.\n return vec4.mul(s, s, [k, k, 1.0 / s[3], k]);\n });\n\n const frustumPlanePointIndices = [\n [0, 1, 2], // near\n [6, 5, 4], // far\n [0, 3, 7], // left\n [2, 1, 5], // right\n [3, 2, 6], // bottom\n [0, 4, 5] // top\n ];\n\n const frustumPlanes = frustumPlanePointIndices.map((p: Array<number>) => {\n const a = vec3.sub([], frustumCoords[p[0]], frustumCoords[p[1]]);\n const b = vec3.sub([], frustumCoords[p[2]], frustumCoords[p[1]]);\n const n = vec3.normalize([], vec3.cross([], a, b));\n const d = -vec3.dot(n, frustumCoords[p[1]]);\n return n.concat(d);\n });\n\n return new Frustum(frustumCoords, frustumPlanes);\n }\n}\n\nclass Aabb {\n min: vec3;\n max: vec3;\n center: vec3;\n\n constructor(min_: vec3, max_: vec3) {\n this.min = min_;\n this.max = max_;\n this.center = vec3.scale([], vec3.add([], this.min, this.max), 0.5);\n }\n\n quadrant(index: number): Aabb {\n const split = [(index % 2) === 0, index < 2];\n const qMin = vec3.clone(this.min);\n const qMax = vec3.clone(this.max);\n for (let axis = 0; axis < split.length; axis++) {\n qMin[axis] = split[axis] ? this.min[axis] : this.center[axis];\n qMax[axis] = split[axis] ? this.center[axis] : this.max[axis];\n }\n // Temporarily, elevation is constant, hence quadrant.max.z = this.max.z\n qMax[2] = this.max[2];\n return new Aabb(qMin, qMax);\n }\n\n distanceX(point: Array<number>): number {\n const pointOnAabb = Math.max(Math.min(this.max[0], point[0]), this.min[0]);\n return pointOnAabb - point[0];\n }\n\n distanceY(point: Array<number>): number {\n const pointOnAabb = Math.max(Math.min(this.max[1], point[1]), this.min[1]);\n return pointOnAabb - point[1];\n }\n\n distanceZ(point: Array<number>): number {\n const pointOnAabb = Math.max(Math.min(this.max[2], point[2]), this.min[2]);\n return pointOnAabb - point[2];\n }\n\n // Performs a frustum-aabb intersection test. Returns 0 if there's no intersection,\n // 1 if shapes are intersecting and 2 if the aabb if fully inside the frustum.\n intersects(frustum: Frustum): number {\n // Execute separating axis test between two convex objects to find intersections\n // Each frustum plane together with 3 major axes define the separating axes\n\n const aabbPoints = [\n [this.min[0], this.min[1], this.min[2], 1],\n [this.max[0], this.min[1], this.min[2], 1],\n [this.max[0], this.max[1], this.min[2], 1],\n [this.min[0], this.max[1], this.min[2], 1],\n [this.min[0], this.min[1], this.max[2], 1],\n [this.max[0], this.min[1], this.max[2], 1],\n [this.max[0], this.max[1], this.max[2], 1],\n [this.min[0], this.max[1], this.max[2], 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 Ray\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, tilespaceTranslate} from '../query_utils';\nimport properties from './circle_style_layer_properties';\nimport {Transitionable, Transitioning, Layout, PossiblyEvaluated} from '../properties';\nimport {vec4, vec3} from 'gl-matrix';\nimport Point from '@mapbox/point-geometry';\nimport ProgramConfiguration from '../../data/program_configuration';\nimport {Ray} from '../../util/primitives';\nimport assert from 'assert';\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';\nimport type {TilespaceQueryGeometry} from '../query_geometry';\nimport type {DEMSampler} from '../../terrain/elevation';\n\nclass CircleStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout<LayoutProps>;\n layout: PossiblyEvaluated<LayoutProps>;\n\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n createBucket(parameters: BucketParameters<*>) {\n return new CircleBucket(parameters);\n }\n\n queryRadius(bucket: Bucket): number {\n const circleBucket: CircleBucket<CircleStyleLayer> = (bucket: any);\n return getMaximumPaintValue('circle-radius', this, circleBucket) +\n getMaximumPaintValue('circle-stroke-width', this, circleBucket) +\n translateDistance(this.paint.get('circle-translate'));\n }\n\n queryIntersectsFeature(queryGeometry: TilespaceQueryGeometry,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array<Array<Point>>,\n zoom: number,\n transform: Transform,\n pixelPosMatrix: Float32Array,\n elevationHelper: ?DEMSampler): boolean {\n const alignWithMap = this.paint.get('circle-pitch-alignment') === 'map';\n if (alignWithMap && queryGeometry.queryGeometry.isAboveHorizon) return false;\n\n const translation = tilespaceTranslate(this.paint.get('circle-translate'),\n this.paint.get('circle-translate-anchor'),\n transform.angle, queryGeometry.pixelToTileUnitsFactor);\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 transformedSize = alignWithMap ? size * queryGeometry.pixelToTileUnitsFactor : size;\n\n for (const ring of geometry) {\n for (const point of ring) {\n const translatedPoint = point.add(translation);\n const z = (elevationHelper && transform.elevation) ?\n transform.elevation.exaggeration() * elevationHelper.getElevationAt(translatedPoint.x, translatedPoint.y, true) :\n 0;\n\n const transformedPoint = alignWithMap ? translatedPoint : projectPoint(translatedPoint, z, pixelPosMatrix);\n const transformedPolygon = alignWithMap ?\n queryGeometry.tilespaceRays.map((r) => intersectAtHeight(r, z)) :\n queryGeometry.queryGeometry.screenGeometry;\n\n let adjustedSize = transformedSize;\n const projectedCenter = vec4.transformMat4([], [point.x, point.y, z, 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 getProgramIds() {\n return ['circle'];\n }\n\n getProgramConfiguration(zoom: number): ProgramConfiguration {\n return new ProgramConfiguration(this, zoom);\n }\n}\n\nfunction projectPoint(p: Point, z: number, pixelPosMatrix: Float32Array) {\n const point = vec4.transformMat4([], [p.x, p.y, z, 1], pixelPosMatrix);\n return new Point(point[0] / point[3], point[1] / point[3]);\n}\n\nconst origin = vec3.fromValues(0, 0, 0);\nconst up = vec3.fromValues(0, 0, 1);\n\nfunction intersectAtHeight(r: Ray, z: number): Point {\n const intersectionPt = vec3.create();\n origin[2] = z;\n const intersects = r.intersectsPlane(origin, up, intersectionPt);\n assert(intersects, 'tilespacePoint should always be below horizon, and since camera cannot have pitch >90, ray should always intersect');\n\n return new Point(intersectionPt[0], intersectionPt[1]);\n}\n\nexport default CircleStyleLayer;\n","// @flow\n\nimport CircleBucket from './circle_bucket';\n\nimport {register} from '../../util/web_worker_transfer';\n\nimport type HeatmapStyleLayer from '../../style/style_layer/heatmap_style_layer';\n\nclass HeatmapBucket extends CircleBucket<HeatmapStyleLayer> {\n // Needed for flow to accept omit: ['layers'] below, due to\n // https://github.com/facebook/flow/issues/4262\n layers: Array<HeatmapStyleLayer>;\n}\n\nregister('HeatmapBucket', HeatmapBucket, {omit: ['layers']});\n\nexport default HeatmapBucket;\n","// @flow\n\nimport assert from 'assert';\n\nimport {register} from './web_worker_transfer';\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<number>,\n \"heatmap-weight\": DataDrivenProperty<number>,\n \"heatmap-intensity\": DataConstantProperty<number>,\n \"heatmap-color\": ColorRampProperty,\n \"heatmap-opacity\": DataConstantProperty<number>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"heatmap-radius\": new DataDrivenProperty(styleSpec[\"paint_heatmap\"][\"heatmap-radius\"]),\n \"heatmap-weight\": new DataDrivenProperty(styleSpec[\"paint_heatmap\"][\"heatmap-weight\"]),\n \"heatmap-intensity\": new DataConstantProperty(styleSpec[\"paint_heatmap\"][\"heatmap-intensity\"]),\n \"heatmap-color\": new ColorRampProperty(styleSpec[\"paint_heatmap\"][\"heatmap-color\"]),\n \"heatmap-opacity\": new DataConstantProperty(styleSpec[\"paint_heatmap\"][\"heatmap-opacity\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint }: $Exact<{\n paint: Properties<PaintProps>\n}>);\n","// @flow\n\nimport {RGBAImage} from './image';\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<Object>;\n}\n\n/**\n * Given an expression that should evaluate to a color ramp,\n * return a RGBA image representing that ramp expression.\n *\n * @private\n */\nexport function renderColorRamp(params: ColorRampParams): RGBAImage {\n const evaluationGlobals = {};\n const width = params.resolution || 256;\n const height = params.clips ? params.clips.length : 1;\n const image = params.image || new RGBAImage({width, height});\n\n assert(isPowerOfTwo(width));\n\n const renderPixel = (stride, index, progress) => {\n evaluationGlobals[params.evaluationKey] = progress;\n const pxColor = params.expression.evaluate((evaluationGlobals: any));\n // the colors are being unpremultiplied because Color uses\n // premultiplied values, and the Texture class expects unpremultiplied ones\n image.data[stride + index + 0] = Math.floor(pxColor.r * 255 / pxColor.a);\n image.data[stride + index + 1] = Math.floor(pxColor.g * 255 / pxColor.a);\n image.data[stride + index + 2] = Math.floor(pxColor.b * 255 / pxColor.a);\n image.data[stride + index + 3] = Math.floor(pxColor.a * 255);\n };\n\n if (!params.clips) {\n for (let i = 0, j = 0; i < width; i++, j += 4) {\n const progress = i / (width - 1);\n\n renderPixel(0, j, progress);\n }\n } else {\n for (let clip = 0, stride = 0; clip < height; ++clip, stride += width * 4) {\n for (let i = 0, j = 0; i < width; i++, j += 4) {\n // Remap progress between clips\n const progress = i / (width - 1);\n const {start, end} = params.clips[clip];\n const evaluationProgress = start * (1 - progress) + end * progress;\n renderPixel(stride, j, evaluationProgress);\n }\n }\n }\n\n return image;\n}\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest';\n\nimport {\n Properties,\n DataConstantProperty,\n DataDrivenProperty,\n CrossFadedDataDrivenProperty,\n CrossFadedProperty,\n ColorRampProperty\n} from '../properties';\n\nimport type Color from '../../style-spec/util/color';\n\nimport type Formatted from '../../style-spec/expression/types/formatted';\n\nimport type ResolvedImage from '../../style-spec/expression/types/resolved_image';\n\n\nexport type PaintProps = {|\n \"hillshade-illumination-direction\": DataConstantProperty<number>,\n \"hillshade-illumination-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"hillshade-exaggeration\": DataConstantProperty<number>,\n \"hillshade-shadow-color\": DataConstantProperty<Color>,\n \"hillshade-highlight-color\": DataConstantProperty<Color>,\n \"hillshade-accent-color\": DataConstantProperty<Color>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"hillshade-illumination-direction\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-illumination-direction\"]),\n \"hillshade-illumination-anchor\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-illumination-anchor\"]),\n \"hillshade-exaggeration\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-exaggeration\"]),\n \"hillshade-shadow-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-shadow-color\"]),\n \"hillshade-highlight-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-highlight-color\"]),\n \"hillshade-accent-color\": new DataConstantProperty(styleSpec[\"paint_hillshade\"][\"hillshade-accent-color\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint }: $Exact<{\n paint: Properties<PaintProps>\n}>);\n","// @flow\nimport {createLayout} from '../../util/struct_array';\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<Array<Point>>, 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<LineStyleLayer> |\n Array<FillStyleLayer> |\n Array<FillExtrusionStyleLayer>;\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<FillStyleLayer>;\n layerIds: Array<string>;\n stateDependentLayers: Array<FillStyleLayer>;\n stateDependentLayerIds: Array<string>;\n patternFeatures: Array<BucketFeature>;\n\n layoutVertexArray: FillLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n indexArray2: LineIndexArray;\n indexBuffer2: IndexBuffer;\n\n hasPattern: boolean;\n programConfigurations: ProgramConfigurationSet<FillStyleLayer>;\n segments: SegmentVector;\n segments2: SegmentVector;\n uploaded: boolean;\n\n constructor(options: BucketParameters<FillStyleLayer>) {\n this.zoom = options.zoom;\n this.overscaling = options.overscaling;\n this.layers = options.layers;\n this.layerIds = this.layers.map(layer => layer.id);\n this.index = options.index;\n this.hasPattern = false;\n this.patternFeatures = [];\n\n this.layoutVertexArray = new FillLayoutArray();\n this.indexArray = new TriangleIndexArray();\n this.indexArray2 = new LineIndexArray();\n this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n this.segments = new SegmentVector();\n this.segments2 = new SegmentVector();\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n }\n\n populate(features: Array<IndexedFeature>, 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<Array<Point>>, 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<number>,\n|};\n\nconst layout: Properties<LayoutProps> = new Properties({\n \"fill-sort-key\": new DataDrivenProperty(styleSpec[\"layout_fill\"][\"fill-sort-key\"]),\n});\n\nexport type PaintProps = {|\n \"fill-antialias\": DataConstantProperty<boolean>,\n \"fill-opacity\": DataDrivenProperty<number>,\n \"fill-color\": DataDrivenProperty<Color>,\n \"fill-outline-color\": DataDrivenProperty<Color>,\n \"fill-translate\": DataConstantProperty<[number, number]>,\n \"fill-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"fill-pattern\": CrossFadedDataDrivenProperty<ResolvedImage>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"fill-antialias\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-antialias\"]),\n \"fill-opacity\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-opacity\"]),\n \"fill-color\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-color\"]),\n \"fill-outline-color\": new DataDrivenProperty(styleSpec[\"paint_fill\"][\"fill-outline-color\"]),\n \"fill-translate\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-translate\"]),\n \"fill-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_fill\"][\"fill-translate-anchor\"]),\n \"fill-pattern\": new 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<PaintProps>, layout: Properties<LayoutProps>\n}>);\n","// @flow\nimport {createLayout} from '../../util/struct_array';\n\nexport const fillExtrusionAttributes = createLayout([\n {name: 'a_pos_normal_ed', components: 4, type: 'Int16'}\n]);\n\nexport const centroidAttributes = createLayout([\n {name: 'a_centroid_pos', components: 2, type: 'Uint16'}\n]);\n\nexport const {members, size, alignment} = fillExtrusionAttributes;\n","'use strict';\n\nvar Point = require('@mapbox/point-geometry');\n\nmodule.exports = VectorTileFeature;\n\nfunction VectorTileFeature(pbf, end, extent, keys, values) {\n // Public\n this.properties = {};\n this.extent = extent;\n this.type = 0;\n\n // Private\n this._pbf = pbf;\n this._geometry = -1;\n this._keys = keys;\n this._values = values;\n\n pbf.readFields(readFeature, this, end);\n}\n\nfunction readFeature(tag, feature, pbf) {\n if (tag == 1) feature.id = pbf.readVarint();\n else if (tag == 2) readTag(pbf, feature);\n else if (tag == 3) feature.type = pbf.readVarint();\n else if (tag == 4) feature._geometry = pbf.pos;\n}\n\nfunction readTag(pbf, feature) {\n var end = pbf.readVarint() + pbf.pos;\n\n while (pbf.pos < end) {\n var key = feature._keys[pbf.readVarint()],\n value = feature._values[pbf.readVarint()];\n feature.properties[key] = value;\n }\n}\n\nVectorTileFeature.types = ['Unknown', 'Point', 'LineString', 'Polygon'];\n\nVectorTileFeature.prototype.loadGeometry = function() {\n var pbf = this._pbf;\n pbf.pos = this._geometry;\n\n var end = pbf.readVarint() + pbf.pos,\n cmd = 1,\n length = 0,\n x = 0,\n y = 0,\n lines = [],\n line;\n\n while (pbf.pos < end) {\n if (length <= 0) {\n var cmdLen = pbf.readVarint();\n cmd = cmdLen & 0x7;\n length = cmdLen >> 3;\n }\n\n length--;\n\n if (cmd === 1 || cmd === 2) {\n x += pbf.readSVarint();\n y += pbf.readSVarint();\n\n if (cmd === 1) { // moveTo\n if (line) lines.push(line);\n line = [];\n }\n\n line.push(new Point(x, y));\n\n } else if (cmd === 7) {\n\n // Workaround for https://github.com/mapbox/mapnik-vector-tile/issues/90\n if (line) {\n line.push(line[0].clone()); // closePolygon\n }\n\n } else {\n throw new Error('unknown command ' + cmd);\n }\n }\n\n if (line) lines.push(line);\n\n return lines;\n};\n\nVectorTileFeature.prototype.bbox = function() {\n var pbf = this._pbf;\n pbf.pos = this._geometry;\n\n var end = pbf.readVarint() + pbf.pos,\n cmd = 1,\n length = 0,\n x = 0,\n y = 0,\n x1 = Infinity,\n x2 = -Infinity,\n y1 = Infinity,\n y2 = -Infinity;\n\n while (pbf.pos < end) {\n if (length <= 0) {\n var cmdLen = pbf.readVarint();\n cmd = cmdLen & 0x7;\n length = cmdLen >> 3;\n }\n\n length--;\n\n if (cmd === 1 || cmd === 2) {\n x += pbf.readSVarint();\n y += pbf.readSVarint();\n if (x < x1) x1 = x;\n if (x > x2) x2 = x;\n if (y < y1) y1 = y;\n if (y > y2) y2 = y;\n\n } else if (cmd !== 7) {\n throw new Error('unknown command ' + cmd);\n }\n }\n\n return [x1, y1, x2, y2];\n};\n\nVectorTileFeature.prototype.toGeoJSON = function(x, y, z) {\n var size = this.extent * Math.pow(2, z),\n x0 = this.extent * x,\n y0 = this.extent * y,\n coords = this.loadGeometry(),\n type = VectorTileFeature.types[this.type],\n i, j;\n\n function project(line) {\n for (var j = 0; j < line.length; j++) {\n var p = line[j], y2 = 180 - (p.y + y0) * 360 / size;\n line[j] = [\n (p.x + x0) * 360 / size - 180,\n 360 / Math.PI * Math.atan(Math.exp(y2 * Math.PI / 180)) - 90\n ];\n }\n }\n\n switch (this.type) {\n case 1:\n var points = [];\n for (i = 0; i < coords.length; i++) {\n points[i] = coords[i][0];\n }\n coords = points;\n project(coords);\n break;\n\n case 2:\n for (i = 0; i < coords.length; i++) {\n project(coords[i]);\n }\n break;\n\n case 3:\n coords = classifyRings(coords);\n for (i = 0; i < coords.length; i++) {\n for (j = 0; j < coords[i].length; j++) {\n project(coords[i][j]);\n }\n }\n break;\n }\n\n if (coords.length === 1) {\n coords = coords[0];\n } else {\n type = 'Multi' + type;\n }\n\n var result = {\n type: \"Feature\",\n geometry: {\n type: type,\n coordinates: coords\n },\n properties: this.properties\n };\n\n if ('id' in this) {\n result.id = this.id;\n }\n\n return result;\n};\n\n// classifies an array of rings into polygons with outer rings and holes\n\nfunction classifyRings(rings) {\n var len = rings.length;\n\n if (len <= 1) return [rings];\n\n var polygons = [],\n polygon,\n ccw;\n\n for (var i = 0; i < len; i++) {\n var area = signedArea(rings[i]);\n if (area === 0) continue;\n\n if (ccw === undefined) ccw = area < 0;\n\n if (ccw === area < 0) {\n if (polygon) polygons.push(polygon);\n polygon = [rings[i]];\n\n } else {\n polygon.push(rings[i]);\n }\n }\n if (polygon) polygons.push(polygon);\n\n return polygons;\n}\n\nfunction signedArea(ring) {\n var sum = 0;\n for (var i = 0, len = ring.length, j = len - 1, p1, p2; i < len; j = i++) {\n p1 = ring[i];\n p2 = ring[j];\n sum += (p2.x - p1.x) * (p1.y + p2.y);\n }\n return sum;\n}\n","'use strict';\n\nvar VectorTileFeature = require('./vectortilefeature.js');\n\nmodule.exports = VectorTileLayer;\n\nfunction VectorTileLayer(pbf, end) {\n // Public\n this.version = 1;\n this.name = null;\n this.extent = 4096;\n this.length = 0;\n\n // Private\n this._pbf = pbf;\n this._keys = [];\n this._values = [];\n this._features = [];\n\n pbf.readFields(readLayer, this, end);\n\n this.length = this._features.length;\n}\n\nfunction readLayer(tag, layer, pbf) {\n if (tag === 15) layer.version = pbf.readVarint();\n else if (tag === 1) layer.name = pbf.readString();\n else if (tag === 5) layer.extent = pbf.readVarint();\n else if (tag === 2) layer._features.push(pbf.pos);\n else if (tag === 3) layer._keys.push(pbf.readString());\n else if (tag === 4) layer._values.push(readValueMessage(pbf));\n}\n\nfunction readValueMessage(pbf) {\n var value = null,\n end = pbf.readVarint() + pbf.pos;\n\n while (pbf.pos < end) {\n var tag = pbf.readVarint() >> 3;\n\n value = tag === 1 ? pbf.readString() :\n tag === 2 ? pbf.readFloat() :\n tag === 3 ? pbf.readDouble() :\n tag === 4 ? pbf.readVarint64() :\n tag === 5 ? pbf.readVarint() :\n tag === 6 ? pbf.readSVarint() :\n tag === 7 ? pbf.readBoolean() : null;\n }\n\n return value;\n}\n\n// return feature `i` from this layer as a `VectorTileFeature`\nVectorTileLayer.prototype.feature = function(i) {\n if (i < 0 || i >= this._features.length) throw new Error('feature index out of bounds');\n\n this._pbf.pos = this._features[i];\n\n var end = this._pbf.readVarint() + this._pbf.pos;\n return new VectorTileFeature(this._pbf, end, this.extent, this._keys, this._values);\n};\n","'use strict';\n\nvar VectorTileLayer = require('./vectortilelayer');\n\nmodule.exports = VectorTile;\n\nfunction VectorTile(pbf, end) {\n this.layers = pbf.readFields(readTile, {}, end);\n}\n\nfunction readTile(tag, layers, pbf) {\n if (tag === 3) {\n var layer = new VectorTileLayer(pbf, pbf.readVarint() + pbf.pos);\n if (layer.length) layers[layer.name] = layer;\n }\n}\n\n","module.exports.VectorTile = require('./lib/vectortile.js');\nmodule.exports.VectorTileFeature = require('./lib/vectortilefeature.js');\nmodule.exports.VectorTileLayer = require('./lib/vectortilelayer.js');\n","// @flow\n\nimport {FillExtrusionLayoutArray, FillExtrusionCentroidArray} from '../array_types';\n\nimport {members as layoutAttributes, centroidAttributes} 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';\nimport Point from '@mapbox/point-geometry';\nimport {number as interpolate} from '../../style-spec/util/interpolate';\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 {FeatureStates} from '../../source/source_state';\nimport type {ImagePosition} from '../../render/image_atlas';\n\nconst FACTOR = Math.pow(2, 13);\n\n// Also declared in _prelude_terrain.vertex.glsl\n// Used to scale most likely elevation values to fit well in an uint16\n// Height of mt everest * 7.3 is roughly 64k\nexport const ELEVATION_SCALE = 7.3;\n\nfunction addVertex(vertexArray, x, y, nxRatio, nySign, normalUp, top, e) {\n vertexArray.emplaceBack(\n // a_pos_normal_ed:\n // Encode top and side/up normal using the least significant bits\n (x << 1) + top,\n (y << 1) + normalUp,\n // dxdy is signed, encode quadrant info using the least significant bit\n (Math.floor(nxRatio * FACTOR) << 1) + nySign,\n // edgedistance (used for wrapping patterns around extrusion sides)\n Math.round(e)\n );\n}\n\nclass PartMetadata {\n acc: Point;\n min: Point;\n max: Point;\n polyCount: Array<{edges: number, top: number}>;\n currentPolyCount: {edges: number, top: number};\n borders: Array<[number, number]>; // Array<[min, max]>\n vertexArrayOffset: number;\n\n constructor() {\n this.acc = new Point(0, 0);\n this.polyCount = [];\n }\n\n startRing(p: Point) {\n this.currentPolyCount = {edges: 0, top: 0};\n this.polyCount.push(this.currentPolyCount);\n if (this.min) return;\n this.min = new Point(p.x, p.y);\n this.max = new Point(p.x, p.y);\n }\n\n append(p: Point, prev: Point) {\n this.currentPolyCount.edges++;\n\n this.acc._add(p);\n let checkBorders = !!this.borders;\n\n const min = this.min, max = this.max;\n if (p.x < min.x) {\n min.x = p.x;\n checkBorders = true;\n } else if (p.x > max.x) {\n max.x = p.x;\n checkBorders = true;\n }\n if (p.y < min.y) {\n min.y = p.y;\n checkBorders = true;\n } else if (p.y > max.y) {\n max.y = p.y;\n checkBorders = true;\n }\n if (((p.x === 0 || p.x === EXTENT) && p.x === prev.x) !== ((p.y === 0 || p.y === EXTENT) && p.y === prev.y)) {\n // Custom defined geojson buildings are cut on borders. Points are\n // repeated when edge cuts tile corner (reason for using xor).\n this.processBorderOverlap(p, prev);\n }\n if (checkBorders) this.checkBorderIntersection(p, prev);\n }\n\n checkBorderIntersection(p: Point, prev: Point) {\n if ((prev.x < 0) !== (p.x < 0)) {\n this.addBorderIntersection(0, interpolate(prev.y, p.y, (0 - prev.x) / (p.x - prev.x)));\n }\n if ((prev.x > EXTENT) !== (p.x > EXTENT)) {\n this.addBorderIntersection(1, interpolate(prev.y, p.y, (EXTENT - prev.x) / (p.x - prev.x)));\n }\n if ((prev.y < 0) !== (p.y < 0)) {\n this.addBorderIntersection(2, interpolate(prev.x, p.x, (0 - prev.y) / (p.y - prev.y)));\n }\n if ((prev.y > EXTENT) !== (p.y > EXTENT)) {\n this.addBorderIntersection(3, interpolate(prev.x, p.x, (EXTENT - prev.y) / (p.y - prev.y)));\n }\n }\n\n addBorderIntersection(index: 0 | 1 | 2 | 3, i: number) {\n if (!this.borders) {\n this.borders = [\n [Number.MAX_VALUE, -Number.MAX_VALUE],\n [Number.MAX_VALUE, -Number.MAX_VALUE],\n [Number.MAX_VALUE, -Number.MAX_VALUE],\n [Number.MAX_VALUE, -Number.MAX_VALUE]\n ];\n }\n const b = this.borders[index];\n if (i < b[0]) b[0] = i;\n if (i > b[1]) b[1] = i;\n }\n\n processBorderOverlap(p: Point, prev: Point) {\n if (p.x === prev.x) {\n if (p.y === prev.y) return; // custom defined geojson could have points repeated.\n const index = p.x === 0 ? 0 : 1;\n this.addBorderIntersection(index, prev.y);\n this.addBorderIntersection(index, p.y);\n } else {\n assert(p.y === prev.y);\n const index = p.y === 0 ? 2 : 3;\n this.addBorderIntersection(index, prev.x);\n this.addBorderIntersection(index, p.x);\n }\n }\n\n centroid(): Point {\n const count = this.polyCount.reduce((acc, p) => acc + p.edges, 0);\n return count !== 0 ? this.acc.div(count)._round() : new Point(0, 0);\n }\n\n span(): Point {\n return new Point(this.max.x - this.min.x, this.max.y - this.min.y);\n }\n\n intersectsCount(): number {\n return this.borders.reduce((acc, p) => acc + +(p[0] !== Number.MAX_VALUE), 0);\n }\n}\n\nclass FillExtrusionBucket implements Bucket {\n index: number;\n zoom: number;\n overscaling: number;\n enableTerrain: boolean;\n layers: Array<FillExtrusionStyleLayer>;\n layerIds: Array<string>;\n stateDependentLayers: Array<FillExtrusionStyleLayer>;\n stateDependentLayerIds: Array<string>;\n\n layoutVertexArray: FillExtrusionLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n\n centroidVertexArray: FillExtrusionCentroidArray;\n centroidVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n hasPattern: boolean;\n programConfigurations: ProgramConfigurationSet<FillExtrusionStyleLayer>;\n segments: SegmentVector;\n uploaded: boolean;\n features: Array<BucketFeature>;\n\n featuresOnBorder: Array<PartMetadata>;\n // borders / borderDone: 0 - left, 1, right, 2 - top, 3 - bottom\n borders: Array<Array<number>>; // For each side, indices into featuresOnBorder array.\n borderDone: Array<boolean>;\n needsCentroidUpdate: boolean;\n tileToMeter: number; // cache conversion.\n\n constructor(options: BucketParameters<FillExtrusionStyleLayer>) {\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.centroidVertexArray = new FillExtrusionCentroidArray();\n this.indexArray = new TriangleIndexArray();\n this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n this.segments = new SegmentVector();\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n this.enableTerrain = options.enableTerrain;\n }\n\n populate(features: Array<IndexedFeature>, options: PopulateParameters, canonical: CanonicalTileID) {\n this.features = [];\n this.hasPattern = hasPattern('fill-extrusion', this.layers, options);\n this.featuresOnBorder = [];\n this.borders = [[], [], [], []];\n this.borderDone = [false, false, false, false];\n this.tileToMeter = tileToMeter(canonical);\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 const vertexArrayOffset = this.layoutVertexArray.length;\n if (this.hasPattern) {\n this.features.push(addPatternDependencies('fill-extrusion', this.layers, bucketFeature, this.zoom, options));\n } else {\n this.addFeature(bucketFeature, bucketFeature.geometry, index, canonical, {});\n }\n\n options.featureIndex.insert(feature, bucketFeature.geometry, index, sourceLayerIndex, this.index, vertexArrayOffset);\n }\n this.sortBorders();\n }\n\n addFeatures(options: PopulateParameters, canonical: CanonicalTileID, imagePositions: {[_: string]: ImagePosition}) {\n for (const feature of this.features) {\n const {geometry} = feature;\n this.addFeature(feature, geometry, feature.index, canonical, imagePositions);\n }\n this.sortBorders();\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 uploadCentroid(context: Context) {\n if (this.centroidVertexArray.length === 0) return;\n if (!this.centroidVertexBuffer) {\n this.centroidVertexBuffer = context.createVertexBuffer(this.centroidVertexArray, centroidAttributes.members, true);\n } else if (this.needsCentroidUpdate) {\n this.centroidVertexBuffer.updateData(this.centroidVertexArray);\n }\n this.needsCentroidUpdate = false;\n }\n\n destroy() {\n if (!this.layoutVertexBuffer) return;\n this.layoutVertexBuffer.destroy();\n if (this.centroidVertexBuffer) this.centroidVertexBuffer.destroy();\n this.indexBuffer.destroy();\n this.programConfigurations.destroy();\n this.segments.destroy();\n }\n\n addFeature(feature: BucketFeature, geometry: Array<Array<Point>>, index: number, canonical: CanonicalTileID, imagePositions: {[_: string]: ImagePosition}) {\n const flatRoof = this.enableTerrain && feature.properties && feature.properties.hasOwnProperty('type') &&\n feature.properties.hasOwnProperty('height') && vectorTileFeatureTypes[feature.type] === 'Polygon';\n\n const metadata = flatRoof ? new PartMetadata() : null;\n\n for (const polygon of classifyRings(geometry, EARCUT_MAX_RINGS)) {\n let numVertices = 0;\n let segment = this.segments.prepareSegment(4, this.layoutVertexArray, this.indexArray);\n\n if (polygon.length === 0 || isEntirelyOutside(polygon[0])) {\n continue;\n }\n\n for (let i = 0; i < polygon.length; i++) {\n const ring = polygon[i];\n if (ring.length === 0) {\n continue;\n }\n numVertices += ring.length;\n\n let edgeDistance = 0;\n if (metadata) metadata.startRing(ring[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 (metadata) metadata.append(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 d = p1.sub(p2)._perp();\n // Given that nz === 0, encode nx / (abs(nx) + abs(ny)) and signs.\n // This information is sufficient to reconstruct normal vector in vertex shader.\n const nxRatio = d.x / (Math.abs(d.x) + Math.abs(d.y));\n const nySign = d.y > 0 ? 1 : 0;\n const dist = p2.dist(p1);\n if (edgeDistance + dist > 32768) edgeDistance = 0;\n\n addVertex(this.layoutVertexArray, p1.x, p1.y, nxRatio, nySign, 0, 0, edgeDistance);\n addVertex(this.layoutVertexArray, p1.x, p1.y, nxRatio, nySign, 0, 1, edgeDistance);\n\n edgeDistance += dist;\n\n addVertex(this.layoutVertexArray, p2.x, p2.y, nxRatio, nySign, 0, 0, edgeDistance);\n addVertex(this.layoutVertexArray, p2.x, p2.y, nxRatio, nySign, 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 (let i = 0; i < polygon.length; i++) {\n const ring = polygon[i];\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 if (metadata) metadata.currentPolyCount.top++;\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 if (metadata && metadata.polyCount.length > 0) {\n // When building is split between tiles, don't handle flat roofs here.\n if (metadata.borders) {\n // Store to the bucket. Flat roofs are handled in flatRoofsUpdate,\n // after joining parts that lay in different buckets.\n metadata.vertexArrayOffset = this.centroidVertexArray.length;\n const borders = metadata.borders;\n const index = this.featuresOnBorder.push(metadata) - 1;\n for (let i = 0; i < 4; i++) {\n if (borders[i][0] !== Number.MAX_VALUE) { this.borders[i].push(index); }\n }\n }\n this.encodeCentroid(metadata.borders ? undefined : metadata.centroid(), metadata);\n assert(!this.centroidVertexArray.length || this.centroidVertexArray.length === this.layoutVertexArray.length);\n }\n\n this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length, feature, index, imagePositions, canonical);\n }\n\n sortBorders() {\n for (let i = 0; i < 4; i++) {\n // Sort by border intersection area minimums, ascending.\n this.borders[i].sort((a, b) => this.featuresOnBorder[a].borders[i][0] - this.featuresOnBorder[b].borders[i][0]);\n }\n }\n\n encodeCentroid(c: Point, metadata: PartMetadata, append: boolean = true) {\n let x, y;\n // Encoded centroid x and y:\n // x y\n // ---------------------------------------------\n // 0 0 Default, no flat roof.\n // 0 1 Hide, used to hide parts of buildings on border while expecting the other side to get loaded\n // >0 0 Elevation encoded to uint16 word\n // >0 >0 Encoded centroid position and x & y span\n if (c) {\n if (c.y !== 0) {\n const span = metadata.span()._mult(this.tileToMeter);\n x = (Math.max(c.x, 1) << 3) + Math.min(7, Math.round(span.x / 10));\n y = (Math.max(c.y, 1) << 3) + Math.min(7, Math.round(span.y / 10));\n } else { // encode height:\n x = Math.ceil(c.x * ELEVATION_SCALE);\n y = 0;\n }\n } else {\n // Use the impossible situation (building that has width and doesn't cross border cannot have centroid\n // at border) to encode unprocessed border building: it is initially (append === true) hidden until\n // computing centroid for joined building parts in rendering thread (flatRoofsUpdate). If it intersects more than\n // two borders, flat roof approach is not applied.\n x = 0;\n y = +append; // Hide (1) initially when creating - visibility is changed in draw_fill_extrusion as soon as neighbor tile gets loaded.\n }\n\n assert(append || metadata.vertexArrayOffset !== undefined);\n let offset = append ? this.centroidVertexArray.length : metadata.vertexArrayOffset;\n for (const polyInfo of metadata.polyCount) {\n if (append) {\n this.centroidVertexArray.resize(this.centroidVertexArray.length + polyInfo.edges * 4 + polyInfo.top);\n }\n for (let i = 0; i < polyInfo.edges * 2; i++) {\n this.centroidVertexArray.emplace(offset++, 0, y);\n this.centroidVertexArray.emplace(offset++, x, y);\n }\n for (let i = 0; i < polyInfo.top; i++) {\n this.centroidVertexArray.emplace(offset++, x, y);\n }\n }\n }\n}\n\nregister('FillExtrusionBucket', FillExtrusionBucket, {omit: ['layers', 'features']});\nregister('PartMetadata', PartMetadata);\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 // Discard rings with corners on border if all other vertices are outside: they get defined\n // also in the tile across the border. Eventual zero area rings at border are discarded by classifyRings\n // and there is no need to handle that case here.\n return ring.every(p => p.x <= 0) ||\n ring.every(p => p.x >= EXTENT) ||\n ring.every(p => p.y <= 0) ||\n ring.every(p => p.y >= EXTENT);\n}\n\nfunction tileToMeter(canonical: CanonicalTileID) {\n const circumferenceAtEquator = 40075017;\n const mercatorY = canonical.y / (1 << canonical.z);\n const exp = Math.exp(Math.PI * (1 - 2 * mercatorY));\n // simplify cos(2 * atan(e) - PI/2) from mercator_coordinate.js, remove trigonometrics.\n return circumferenceAtEquator * 2 * exp / (exp * exp + 1) / EXTENT / (1 << canonical.z);\n}\n","// 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<number>,\n \"fill-extrusion-color\": DataDrivenProperty<Color>,\n \"fill-extrusion-translate\": DataConstantProperty<[number, number]>,\n \"fill-extrusion-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"fill-extrusion-pattern\": CrossFadedDataDrivenProperty<ResolvedImage>,\n \"fill-extrusion-height\": DataDrivenProperty<number>,\n \"fill-extrusion-base\": DataDrivenProperty<number>,\n \"fill-extrusion-vertical-gradient\": DataConstantProperty<boolean>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"fill-extrusion-opacity\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-opacity\"]),\n \"fill-extrusion-color\": new DataDrivenProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-color\"]),\n \"fill-extrusion-translate\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-translate\"]),\n \"fill-extrusion-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_fill-extrusion\"][\"fill-extrusion-translate-anchor\"]),\n \"fill-extrusion-pattern\": new 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<PaintProps>\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer';\nimport FillExtrusionBucket, {ELEVATION_SCALE} from '../../data/bucket/fill_extrusion_bucket';\nimport {polygonIntersectsPolygon, polygonIntersectsMultiPolygon} from '../../util/intersection_tests';\nimport {translateDistance, tilespaceTranslate} from '../query_utils';\nimport properties from './fill_extrusion_style_layer_properties';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties';\nimport Point from '@mapbox/point-geometry';\nimport ProgramConfiguration from '../../data/program_configuration';\nimport {vec2, vec3} from 'gl-matrix';\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';\nimport type {TilespaceQueryGeometry} from '../query_geometry';\nimport type {DEMSampler} from '../../terrain/elevation';\nimport type {vec4} from 'gl-matrix';\n\nclass FillExtrusionStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n createBucket(parameters: BucketParameters<FillExtrusionStyleLayer>) {\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 getProgramIds(): string[] {\n const patternProperty = this.paint.get('fill-extrusion-pattern');\n const image = patternProperty.constantOr((1: any));\n return [image ? 'fillExtrusionPattern' : 'fillExtrusion'];\n }\n\n getProgramConfiguration(zoom: number): ProgramConfiguration {\n return new ProgramConfiguration(this, zoom);\n }\n\n queryIntersectsFeature(queryGeometry: TilespaceQueryGeometry,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array<Array<Point>>,\n zoom: number,\n transform: Transform,\n pixelPosMatrix: Float32Array,\n elevationHelper: ?DEMSampler,\n layoutVertexArrayOffset: number): boolean | number {\n\n const translation = tilespaceTranslate(this.paint.get('fill-extrusion-translate'),\n this.paint.get('fill-extrusion-translate-anchor'),\n transform.angle,\n queryGeometry.pixelToTileUnitsFactor);\n const height = this.paint.get('fill-extrusion-height').evaluate(feature, featureState);\n const base = this.paint.get('fill-extrusion-base').evaluate(feature, featureState);\n\n const centroid = [0, 0];\n const terrainVisible = elevationHelper && transform.elevation;\n const exaggeration = transform.elevation ? transform.elevation.exaggeration() : 1;\n if (terrainVisible) {\n const centroidVertexArray = queryGeometry.tile.getBucket(this).centroidVertexArray;\n\n // See FillExtrusionBucket#encodeCentroid(), centroid is inserted at vertexOffset + 1\n const centroidOffset = layoutVertexArrayOffset + 1;\n if (centroidOffset < centroidVertexArray.length) {\n const centroidVertexObject = centroidVertexArray.get(centroidOffset);\n centroid[0] = centroidVertexObject.a_centroid_pos0;\n centroid[1] = centroidVertexObject.a_centroid_pos1;\n }\n }\n\n // Early exit if fill extrusion is still hidden while waiting for backfill\n const isHidden = centroid[0] === 0 && centroid[1] === 1;\n if (isHidden) return false;\n\n const demSampler = terrainVisible ? elevationHelper : null;\n const projected = projectExtrusion(geometry, base, height, translation, pixelPosMatrix, demSampler, centroid, exaggeration, transform.center.lat);\n const projectedBase = projected[0];\n const projectedTop = projected[1];\n\n const screenQuery = queryGeometry.queryGeometry;\n const projectedQueryGeometry = screenQuery.isPointQuery() ? screenQuery.screenBounds : screenQuery.screenGeometry;\n return checkIntersection(projectedBase, projectedTop, projectedQueryGeometry);\n }\n}\n\nfunction dot(a, b) {\n return a.x * b.x + a.y * b.y;\n}\n\nexport function getIntersectionDistance(projectedQueryGeometry: Array<Point>, projectedFace: Array<Point>) {\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<Point>, projectedTop: Array<Point>, projectedQueryGeometry: Array<Point>) {\n let closestDistance = Infinity;\n\n if (polygonIntersectsMultiPolygon(projectedQueryGeometry, projectedTop)) {\n closestDistance = getIntersectionDistance(projectedQueryGeometry, projectedTop[0]);\n }\n\n for (let r = 0; r < projectedTop.length; r++) {\n const ringTop = projectedTop[r];\n const ringBase = projectedBase[r];\n for (let p = 0; p < ringTop.length - 1; p++) {\n const topA = ringTop[p];\n const topB = ringTop[p + 1];\n const baseA = ringBase[p];\n const baseB = ringBase[p + 1];\n const face = [topA, topB, baseB, baseA, topA];\n if (polygonIntersectsPolygon(projectedQueryGeometry, face)) {\n closestDistance = Math.min(closestDistance, getIntersectionDistance(projectedQueryGeometry, face));\n }\n }\n }\n\n return closestDistance === Infinity ? false : closestDistance;\n}\n\nfunction projectExtrusion(geometry: Array<Array<Point>>, zBase: number, zTop: number, translation: Point, m: Float32Array, demSampler: ?DEMSampler, centroid: vec2, exaggeration: number, lat: number) {\n if (demSampler) {\n return projectExtrusion3D(geometry, zBase, zTop, translation, m, demSampler, centroid, exaggeration, lat);\n } else {\n return projectExtrusion2D(geometry, zBase, zTop, translation, m);\n }\n}\n\n/*\n * Project the geometry using matrix `m`. This is essentially doing\n * `vec4.transformMat4([], [p.x, p.y, z, 1], m)` but the multiplication\n * is inlined so that parts of the projection that are the same across\n * different points can only be done once. This produced a measurable\n * performance improvement.\n */\nfunction projectExtrusion2D(geometry: Array<Array<Point>>, zBase: number, zTop: number, translation: Point, m: Float32Array) {\n const projectedBase = [];\n const projectedTop = [];\n\n const baseXZ = m[8] * zBase;\n const baseYZ = m[9] * zBase;\n const baseZZ = m[10] * zBase;\n const baseWZ = m[11] * zBase;\n const topXZ = m[8] * zTop;\n const topYZ = m[9] * zTop;\n const topZZ = m[10] * zTop;\n const topWZ = m[11] * zTop;\n\n for (const r of geometry) {\n const ringBase = [];\n const ringTop = [];\n for (const p of r) {\n const x = p.x + translation.x;\n const y = p.y + translation.y;\n\n const sX = m[0] * x + m[4] * y + m[12];\n const sY = m[1] * x + m[5] * y + m[13];\n const sZ = m[2] * x + m[6] * y + m[14];\n const sW = m[3] * x + m[7] * y + m[15];\n\n const baseX = sX + baseXZ;\n const baseY = sY + baseYZ;\n const baseZ = sZ + baseZZ;\n const baseW = 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\n/**\n * Projects a fill extrusion vertices to screen while accounting for terrain.\n * This and its dependent functions are ported directly from `fill_extrusion.vertex.glsl`\n * with a few co-ordinate space differences.\n *\n * - Matrix `m` projects to screen-pixel space instead of to gl-coordinates (NDC)\n * - Texture querying is performed in texture pixel coordinates instead of normalized uv coordinates.\n * - Height offset calculation for fill-extrusion-base is offset with -1 instead of -5 to prevent underground picking.\n */\nfunction projectExtrusion3D(geometry: Array<Array<Point>>, zBase: number, zTop: number, translation: Point, m: Float32Array, demSampler: DEMSampler, centroid: vec2, exaggeration: number, lat: number) {\n const projectedBase = [];\n const projectedTop = [];\n const v = [0, 0, 0];\n\n for (const r of geometry) {\n const ringBase = [];\n const ringTop = [];\n for (const p of r) {\n const x = p.x + translation.x;\n const y = p.y + translation.y;\n const heightOffset = getTerrainHeightOffset(x, y, zBase, zTop, demSampler, centroid, exaggeration, lat);\n\n v[0] = x;\n v[1] = y;\n v[2] = heightOffset.base;\n const base = toPoint(vec3.transformMat4(v, v, m));\n\n v[0] = x;\n v[1] = y;\n v[2] = heightOffset.top;\n const top = toPoint(vec3.transformMat4(v, v, m));\n\n ringBase.push(base);\n ringTop.push(top);\n }\n projectedBase.push(ringBase);\n projectedTop.push(ringTop);\n }\n return [projectedBase, projectedTop];\n}\n\nfunction toPoint(v: vec3): Point {\n const p = new Point(v[0], v[1]);\n p.z = v[2];\n return p;\n}\n\nfunction getTerrainHeightOffset(x: number, y: number, zBase: number, zTop: number, demSampler: DEMSampler, centroid: vec2, exaggeration: number, lat: number): { base: number, top: number} {\n const ele = exaggeration * demSampler.getElevationAt(x, y, true, true);\n const flatRoof = centroid[0] !== 0;\n const centroidElevation = flatRoof ? centroid[1] === 0 ? exaggeration * elevationFromUint16(centroid[0]) : exaggeration * flatElevation(demSampler, centroid, lat) : ele;\n return {\n base: ele + (zBase === 0) ? -1 : zBase, // Use -1 instead of -5 in shader to prevent picking underground\n top: flatRoof ? Math.max(centroidElevation + zTop, ele + zBase + 2) : ele + zTop\n };\n}\n\n// Elevation is encoded into unit16 in fill_extrusion_bucket.js FillExtrusionBucket#encodeCentroid\nfunction elevationFromUint16(n: number): number {\n return n / ELEVATION_SCALE;\n}\n\n// Equivalent GPU side function is in _prelude_terrain.vertex.glsl\nfunction flatElevation(demSampler: DEMSampler, centroid: vec2, lat: number): number {\n // Span and pos are packed two 16 bit uint16 values in fill_extrusion_bucket.js FillExtrusionBucket#encodeCentroid\n // pos is encoded by << by 3 bits thus dividing by 8 performs equivalent of right shifting it back.\n const posX = Math.floor(centroid[0] / 8);\n const posY = Math.floor(centroid[1] / 8);\n\n // Span is stored in the lower three bits in multiples of 10\n const spanX = 10 * (centroid[0] - posX * 8);\n const spanY = 10 * (centroid[1] - posY * 8);\n\n // Get height at centroid\n const z = demSampler.getElevationAt(posX, posY, true, true);\n const meterToDEM = demSampler.getMeterToDEM(lat);\n\n const wX = Math.floor(0.5 * (spanX * meterToDEM - 1));\n const wY = Math.floor(0.5 * (spanY * meterToDEM - 1));\n\n const posPx = demSampler.tileCoordToPixel(posX, posY);\n\n const offsetX = 2 * wX + 1;\n const offsetY = 2 * wY + 1;\n const corners = fourSample(demSampler, posPx.x - wX, posPx.y - wY, offsetX, offsetY);\n\n const diffX = Math.abs(corners[0] - corners[1]);\n const diffY = Math.abs(corners[2] - corners[3]);\n const diffZ = Math.abs(corners[0] - corners[2]);\n const diffW = Math.abs(corners[1] - corners[3]);\n\n const diffSumX = diffX + diffY;\n const diffSumY = diffZ + diffW;\n\n const slopeX = Math.min(0.25, meterToDEM * 0.5 * diffSumX / offsetX);\n const slopeY = Math.min(0.25, meterToDEM * 0.5 * diffSumY / offsetY);\n\n return z + Math.max(slopeX * spanX, slopeY * spanY);\n}\n\nfunction fourSample(demSampler: DEMSampler, posX: number, posY: number, offsetX: number, offsetY: number): vec4 {\n return [\n demSampler.getElevationAtPixel(posX, posY, true),\n demSampler.getElevationAtPixel(posX + offsetY, posY, true),\n demSampler.getElevationAtPixel(posX, posY + offsetY, true),\n demSampler.getElevationAtPixel(posX + offsetX, posY + offsetY, true)\n ];\n}\n\nexport default FillExtrusionStyleLayer;\n","// @flow\nimport {createLayout} from '../../util/struct_array';\n\nconst lineLayoutAttributes = createLayout([\n {name: 'a_pos_normal', components: 2, type: 'Int16'},\n {name: 'a_data', components: 4, type: 'Uint8'},\n {name: 'a_linesofar', components: 1, type: 'Float32'}\n], 4);\n\nexport default lineLayoutAttributes;\nexport const {members, size, alignment} = lineLayoutAttributes;\n","// @flow\nimport {createLayout} from '../../util/struct_array';\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\ntype LineClips = {\n start: number;\n end: number;\n}\n\ntype GradientTexture = {\n texture: Texture;\n gradient: ?RGBAImage;\n version: number;\n}\n\n/**\n * @private\n */\nclass LineBucket implements Bucket {\n distance: number;\n totalDistance: number;\n maxLineLength: number;\n scaledDistance: number;\n lineSoFar: number;\n lineClips: ?LineClips;\n\n e1: number;\n e2: number;\n\n index: number;\n zoom: number;\n overscaling: number;\n layers: Array<LineStyleLayer>;\n layerIds: Array<string>;\n gradients: {[string]: GradientTexture};\n stateDependentLayers: Array<any>;\n stateDependentLayerIds: Array<string>;\n patternFeatures: Array<BucketFeature>;\n lineClipsArray: Array<LineClips>;\n\n layoutVertexArray: LineLayoutArray;\n layoutVertexBuffer: VertexBuffer;\n layoutVertexArray2: LineExtLayoutArray;\n layoutVertexBuffer2: VertexBuffer;\n\n indexArray: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n\n hasPattern: boolean;\n programConfigurations: ProgramConfigurationSet<LineStyleLayer>;\n segments: SegmentVector;\n uploaded: boolean;\n\n constructor(options: BucketParameters<LineStyleLayer>) {\n this.zoom = options.zoom;\n this.overscaling = options.overscaling;\n this.layers = options.layers;\n this.layerIds = this.layers.map(layer => layer.id);\n this.index = options.index;\n this.hasPattern = false;\n this.patternFeatures = [];\n this.lineClipsArray = [];\n this.gradients = {};\n this.layers.forEach(layer => {\n this.gradients[layer.id] = {};\n });\n\n this.layoutVertexArray = new LineLayoutArray();\n this.layoutVertexArray2 = new LineExtLayoutArray();\n this.indexArray = new TriangleIndexArray();\n this.programConfigurations = new ProgramConfigurationSet(options.layers, options.zoom);\n this.segments = new SegmentVector();\n this.maxLineLength = 0;\n\n this.stateDependentLayerIds = this.layers.filter((l) => l.isStateDependent()).map((l) => l.id);\n }\n\n populate(features: Array<IndexedFeature>, options: PopulateParameters, canonical: CanonicalTileID) {\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<Array<Point>>, 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<Point>, feature: BucketFeature, join: string, cap: string, miterLimit: number, roundLimit: number) {\n this.distance = 0;\n this.scaledDistance = 0;\n this.totalDistance = 0;\n this.lineSoFar = 0;\n\n if (this.lineClips) {\n this.lineClipsArray.push(this.lineClips);\n // Calculate the total distance, in tile units, of this tiled line feature\n for (let i = 0; i < vertices.length - 1; i++) {\n this.totalDistance += vertices[i].dist(vertices[i + 1]);\n }\n this.updateScaledDistance();\n this.maxLineLength = Math.max(this.maxLineLength, this.totalDistance);\n }\n\n const isPolygon = vectorTileFeatureTypes[feature.type] === 'Polygon';\n\n // If the line has duplicate vertices at the ends, adjust start/length to remove them.\n let len = vertices.length;\n while (len >= 2 && vertices[len - 1].equals(vertices[len - 2])) {\n len--;\n }\n let first = 0;\n while (first < len - 1 && vertices[first].equals(vertices[first + 1])) {\n first++;\n }\n\n // Ignore invalid geometry.\n if (len < (isPolygon ? 3 : 2)) return;\n\n if (join === 'bevel') miterLimit = 1.05;\n\n const sharpCornerOffset = this.overscaling <= 16 ?\n SHARP_CORNER_OFFSET * EXTENT / (512 * this.overscaling) :\n 0;\n\n // we could be more precise, but it would only save a negligible amount of space\n const segment = this.segments.prepareSegment(len * 10, this.layoutVertexArray, this.indexArray);\n\n let currentVertex;\n let prevVertex = ((undefined: any): Point);\n let nextVertex = ((undefined: any): Point);\n let prevNormal = ((undefined: any): Point);\n let nextNormal = ((undefined: any): Point);\n\n // the last two vertices added\n this.e1 = this.e2 = -1;\n\n if (isPolygon) {\n currentVertex = vertices[len - 2];\n nextNormal = vertices[first].sub(currentVertex)._unit()._perp();\n }\n\n for (let i = first; i < len; i++) {\n\n nextVertex = i === len - 1 ?\n (isPolygon ? vertices[first + 1] : (undefined: any)) : // if it's a polygon, treat the last vertex like the first\n vertices[i + 1]; // just the next vertex\n\n // if two consecutive vertices exist, skip the current one\n if (nextVertex && vertices[i].equals(nextVertex)) continue;\n\n if (nextNormal) prevNormal = nextNormal;\n if (currentVertex) prevVertex = currentVertex;\n\n currentVertex = vertices[i];\n\n // Calculate the normal towards the next vertex in this line. In case\n // there is no next vertex, pretend that the line is continuing straight,\n // meaning that we are just using the previous normal.\n nextNormal = nextVertex ? nextVertex.sub(currentVertex)._unit()._perp() : prevNormal;\n\n // If we still don't have a previous normal, this is the beginning of a\n // non-closed line, so we're doing a straight \"join\".\n prevNormal = prevNormal || nextNormal;\n\n // Determine the normal of the join extrusion. It is the angle bisector\n // of the segments between the previous line and the next line.\n // In the case of 180° angles, the prev and next normals cancel each other out:\n // prevNormal + nextNormal = (0, 0), its magnitude is 0, so the unit vector would be\n // undefined. In that case, we're keeping the joinNormal at (0, 0), so that the cosHalfAngle\n // below will also become 0 and miterLength will become Infinity.\n let joinNormal = prevNormal.add(nextNormal);\n if (joinNormal.x !== 0 || joinNormal.y !== 0) {\n joinNormal._unit();\n }\n /* joinNormal prevNormal\n * ↖ ↑\n * .________. prevVertex\n * |\n * nextNormal ← | currentVertex\n * |\n * nextVertex !\n *\n */\n\n // calculate cosines of the angle (and its half) using dot product\n const cosAngle = prevNormal.x * nextNormal.x + prevNormal.y * nextNormal.y;\n const cosHalfAngle = joinNormal.x * nextNormal.x + joinNormal.y * nextNormal.y;\n\n // Calculate the length of the miter (the ratio of the miter to the width)\n // as the inverse of cosine of the angle between next and join normals\n const miterLength = cosHalfAngle !== 0 ? 1 / cosHalfAngle : Infinity;\n\n // approximate angle from cosine\n const approxAngle = 2 * Math.sqrt(2 - 2 * cosHalfAngle);\n\n const isSharpCorner = cosHalfAngle < COS_HALF_SHARP_CORNER && prevVertex && nextVertex;\n const lineTurnsLeft = prevNormal.x * nextNormal.y - prevNormal.y * nextNormal.x > 0;\n\n if (isSharpCorner && i > first) {\n const prevSegmentLength = currentVertex.dist(prevVertex);\n if (prevSegmentLength > 2 * sharpCornerOffset) {\n const newPrevVertex = currentVertex.sub(currentVertex.sub(prevVertex)._mult(sharpCornerOffset / prevSegmentLength)._round());\n this.updateDistance(prevVertex, newPrevVertex);\n this.addCurrentVertex(newPrevVertex, prevNormal, 0, 0, segment);\n prevVertex = newPrevVertex;\n }\n }\n\n // The join if a middle vertex, otherwise the cap.\n const middleVertex = prevVertex && nextVertex;\n let currentJoin = middleVertex ? join : isPolygon ? 'butt' : cap;\n\n if (middleVertex && currentJoin === 'round') {\n if (miterLength < roundLimit) {\n currentJoin = 'miter';\n } else if (miterLength <= 2) {\n currentJoin = 'fakeround';\n }\n }\n\n if (currentJoin === 'miter' && miterLength > miterLimit) {\n currentJoin = 'bevel';\n }\n\n if (currentJoin === 'bevel') {\n // The maximum extrude length is 128 / 63 = 2 times the width of the line\n // so if miterLength >= 2 we need to draw a different type of bevel here.\n if (miterLength > 2) currentJoin = 'flipbevel';\n\n // If the miterLength is really small and the line bevel wouldn't be visible,\n // just draw a miter join to save a triangle.\n if (miterLength < miterLimit) currentJoin = 'miter';\n }\n\n // Calculate how far along the line the currentVertex is\n if (prevVertex) this.updateDistance(prevVertex, currentVertex);\n\n if (currentJoin === 'miter') {\n\n joinNormal._mult(miterLength);\n this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment);\n\n } else if (currentJoin === 'flipbevel') {\n // miter is too big, flip the direction to make a beveled join\n\n if (miterLength > 100) {\n // Almost parallel lines\n joinNormal = nextNormal.mult(-1);\n\n } else {\n const bevelLength = miterLength * prevNormal.add(nextNormal).mag() / prevNormal.sub(nextNormal).mag();\n joinNormal._perp()._mult(bevelLength * (lineTurnsLeft ? -1 : 1));\n }\n this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment);\n this.addCurrentVertex(currentVertex, joinNormal.mult(-1), 0, 0, segment);\n\n } else if (currentJoin === 'bevel' || currentJoin === 'fakeround') {\n const offset = -Math.sqrt(miterLength * miterLength - 1);\n const offsetA = lineTurnsLeft ? offset : 0;\n const offsetB = lineTurnsLeft ? 0 : offset;\n\n // Close previous segment with a bevel\n if (prevVertex) {\n this.addCurrentVertex(currentVertex, prevNormal, offsetA, offsetB, segment);\n }\n\n if (currentJoin === 'fakeround') {\n // The join angle is sharp enough that a round join would be visible.\n // Bevel joins fill the gap between segments with a single pie slice triangle.\n // Create a round join by adding multiple pie slices. The join isn't actually round, but\n // it looks like it is at the sizes we render lines at.\n\n // pick the number of triangles for approximating round join by based on the angle between normals\n const n = Math.round((approxAngle * 180 / Math.PI) / DEG_PER_TRIANGLE);\n\n for (let m = 1; m < n; m++) {\n let t = m / n;\n if (t !== 0.5) {\n // approximate spherical interpolation https://observablehq.com/@mourner/approximating-geometric-slerp\n const t2 = t - 0.5;\n const A = 1.0904 + cosAngle * (-3.2452 + cosAngle * (3.55645 - cosAngle * 1.43519));\n const B = 0.848013 + cosAngle * (-1.06021 + cosAngle * 0.215638);\n t = t + t * t2 * (t - 1) * (A * t2 * t2 + B);\n }\n const extrude = nextNormal.sub(prevNormal)._mult(t)._add(prevNormal)._unit()._mult(lineTurnsLeft ? -1 : 1);\n this.addHalfVertex(currentVertex, extrude.x, extrude.y, false, lineTurnsLeft, 0, segment);\n }\n }\n\n if (nextVertex) {\n // Start next segment\n this.addCurrentVertex(currentVertex, nextNormal, -offsetA, -offsetB, segment);\n }\n\n } else if (currentJoin === 'butt') {\n this.addCurrentVertex(currentVertex, joinNormal, 0, 0, segment); // butt cap\n\n } else if (currentJoin === 'square') {\n const offset = prevVertex ? 1 : -1; // closing or starting square cap\n 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\n addHalfVertex({x, y}: Point, extrudeX: number, extrudeY: number, round: boolean, up: boolean, dir: number, segment: Segment) {\n this.layoutVertexArray.emplaceBack(\n // a_pos_normal\n // Encode round/up the least significant bits\n (x << 1) + (round ? 1 : 0),\n (y << 1) + (up ? 1 : 0),\n // a_data\n // add 128 to store a byte in an unsigned byte\n Math.round(EXTRUDE_SCALE * extrudeX) + 128,\n Math.round(EXTRUDE_SCALE * extrudeY) + 128,\n ((dir === 0 ? 0 : (dir < 0 ? -1 : 1)) + 1),\n 0, // unused\n // a_linesofar\n this.lineSoFar);\n\n // Constructs a second vertex buffer with higher precision line progress\n if (this.lineClips) {\n this.layoutVertexArray2.emplaceBack(this.scaledDistance, this.lineClipsArray.length);\n }\n\n const e = segment.vertexLength++;\n if (this.e1 >= 0 && this.e2 >= 0) {\n this.indexArray.emplaceBack(this.e1, this.e2, e);\n segment.primitiveLength++;\n }\n if (up) {\n this.e2 = e;\n } else {\n this.e1 = e;\n }\n }\n\n updateScaledDistance() {\n // Knowing the ratio of the full linestring covered by this tiled feature, as well\n // as the total distance (in tile units) of this tiled feature, and the distance\n // (in tile units) of the current vertex, we can determine the relative distance\n // of this vertex along the full linestring feature.\n if (this.lineClips) {\n const featureShare = this.lineClips.end - this.lineClips.start;\n const totalFeatureLength = this.totalDistance / featureShare;\n this.scaledDistance = this.distance / this.totalDistance;\n this.lineSoFar = totalFeatureLength * this.lineClips.start + this.distance;\n } else {\n this.lineSoFar = this.distance;\n }\n }\n\n updateDistance(prev: Point, next: Point) {\n this.distance += prev.dist(next);\n this.updateScaledDistance();\n }\n}\n\nregister('LineBucket', LineBucket, {omit: ['layers', 'patternFeatures']});\n\nexport default LineBucket;\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest';\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<number>,\n \"line-round-limit\": DataConstantProperty<number>,\n \"line-sort-key\": DataDrivenProperty<number>,\n|};\n\nconst layout: Properties<LayoutProps> = new Properties({\n \"line-cap\": new 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<number>,\n \"line-color\": DataDrivenProperty<Color>,\n \"line-translate\": DataConstantProperty<[number, number]>,\n \"line-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"line-width\": DataDrivenProperty<number>,\n \"line-gap-width\": DataDrivenProperty<number>,\n \"line-offset\": DataDrivenProperty<number>,\n \"line-blur\": DataDrivenProperty<number>,\n \"line-dasharray\": CrossFadedProperty<Array<number>>,\n \"line-pattern\": CrossFadedDataDrivenProperty<ResolvedImage>,\n \"line-gradient\": ColorRampProperty,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"line-opacity\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-opacity\"]),\n \"line-color\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-color\"]),\n \"line-translate\": new DataConstantProperty(styleSpec[\"paint_line\"][\"line-translate\"]),\n \"line-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_line\"][\"line-translate-anchor\"]),\n \"line-width\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-width\"]),\n \"line-gap-width\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-gap-width\"]),\n \"line-offset\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-offset\"]),\n \"line-blur\": new DataDrivenProperty(styleSpec[\"paint_line\"][\"line-blur\"]),\n \"line-dasharray\": new 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<PaintProps>, layout: Properties<LayoutProps>\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';\nimport ProgramConfiguration from '../../data/program_configuration';\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';\nimport type {TilespaceQueryGeometry} from '../query_geometry';\n\nclass LineFloorwidthProperty extends DataDrivenProperty<number> {\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<LayoutProps>;\n layout: PossiblyEvaluated<LayoutProps>;\n\n gradientVersion: number;\n stepInterpolant: boolean;\n\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n this.gradientVersion = 0;\n }\n\n _handleSpecialPaintPropertyUpdate(name: string) {\n if (name === 'line-gradient') {\n const expression: ZoomConstantExpression<'source'> = ((this._transitionablePaint._values['line-gradient'].value.expression): any);\n this.stepInterpolant = expression._styleExpression.expression 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<string>) {\n super.recalculate(parameters, availableImages);\n\n (this.paint._values: any)['line-floorwidth'] =\n lineFloorwidthProperty.possiblyEvaluate(this._transitioningPaint._values['line-width'].value, parameters);\n }\n\n createBucket(parameters: BucketParameters<*>) {\n return new LineBucket(parameters);\n }\n\n getProgramIds(): string[] {\n const dasharray = this.paint.get('line-dasharray');\n const patternProperty = this.paint.get('line-pattern');\n const image = patternProperty.constantOr((1: any));\n const gradient = this.paint.get('line-gradient');\n const programId =\n image ? 'linePattern' :\n dasharray ? 'lineSDF' :\n gradient ? 'lineGradient' : 'line';\n return [programId];\n }\n\n getProgramConfiguration(zoom: number): ProgramConfiguration {\n return new ProgramConfiguration(this, zoom);\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: TilespaceQueryGeometry,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array<Array<Point>>,\n zoom: number,\n transform: Transform): boolean {\n if (queryGeometry.queryGeometry.isAboveHorizon) return false;\n\n const translatedPolygon = translate(queryGeometry.tilespaceGeometry,\n this.paint.get('line-translate'),\n this.paint.get('line-translate-anchor'),\n transform.angle, queryGeometry.pixelToTileUnitsFactor);\n const halfWidth = queryGeometry.pixelToTileUnitsFactor / 2 * getLineWidth(\n this.paint.get('line-width').evaluate(feature, featureState),\n this.paint.get('line-gap-width').evaluate(feature, featureState));\n const lineOffset = this.paint.get('line-offset').evaluate(feature, featureState);\n if (lineOffset) {\n geometry = offsetLine(geometry, lineOffset * queryGeometry.pixelToTileUnitsFactor);\n }\n\n return polygonIntersectsBufferedMultiLine(translatedPolygon, geometry, halfWidth);\n }\n\n isTileClipped() {\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 collisionVertexAttributesExt = createLayout([\n {name: 'a_size_scale', components: 1, type: 'Float32'},\n {name: 'a_padding', 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: 'Float32', name: 'x1'},\n {type: 'Float32', name: 'y1'},\n {type: 'Float32', name: 'x2'},\n {type: 'Float32', name: 'y2'},\n\n {type: 'Int16', name: 'padding'},\n\n // the index of the feature in the original vectortile\n {type: 'Uint32', name: 'featureIndex'},\n // the source layer the feature appears in\n {type: 'Uint16', name: 'sourceLayerIndex'},\n // the bucket the feature appears in\n {type: 'Uint16', name: 'bucketIndex'},\n]);\n\nexport const collisionBoxLayout = 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_2f', components: 2, type: 'Float32'},\n {name: 'a_radius', components: 1, type: 'Float32'},\n {name: 'a_flags', components: 2, type: 'Int16'}\n], 4);\n\nexport const quadTriangle = 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 {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<number, PossiblyEvaluatedPropertyValue<number>>): 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 {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<StyleGlyph>, pbf: Protobuf) {\n if (tag === 1) {\n pbf.readMessage(readFontstack, glyphs);\n }\n}\n\nfunction readFontstack(tag: number, glyphs: Array<StyleGlyph>, 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<StyleGlyph> {\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<number> {\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<string>;\n uploaded: ?boolean;\n\n constructor(icons: {[_: string]: StyleImage}, patterns: {[_: string]: StyleImage}) {\n const iconPositions = {}, patternPositions = {};\n this.haveRenderCallbacks = [];\n\n const bins = [];\n\n this.addImages(icons, iconPositions, bins);\n this.addImages(patterns, patternPositions, bins);\n\n const {w, h} = potpack(bins);\n const image = new RGBAImage({width: w || 1, height: h || 1});\n\n for (const id in icons) {\n const src = icons[id];\n const bin = iconPositions[id].paddedRect;\n RGBAImage.copy(src.data, image, {x: 0, y: 0}, {x: bin.x + IMAGE_PADDING, y: bin.y + IMAGE_PADDING}, src.data);\n }\n\n for (const id in patterns) {\n const src = patterns[id];\n const bin = patternPositions[id].paddedRect;\n const x = bin.x + IMAGE_PADDING,\n y = bin.y + IMAGE_PADDING,\n w = src.data.width,\n h = src.data.height;\n\n RGBAImage.copy(src.data, image, {x: 0, y: 0}, {x, y}, src.data);\n // Add 1 pixel wrapped padding on each side of the image.\n RGBAImage.copy(src.data, image, {x: 0, y: h - 1}, {x, y: y - 1}, {width: w, height: 1}); // T\n RGBAImage.copy(src.data, image, {x: 0, y: 0}, {x, y: y + h}, {width: w, height: 1}); // B\n RGBAImage.copy(src.data, image, {x: w - 1, y: 0}, {x: x - 1, y}, {width: 1, height: h}); // L\n RGBAImage.copy(src.data, image, {x: 0, y: 0}, {x: x + w, y}, {width: 1, height: h}); // R\n }\n\n this.image = image;\n this.iconPositions = iconPositions;\n this.patternPositions = patternPositions;\n }\n\n addImages(images: {[_: string]: StyleImage}, positions: {[_: string]: ImagePosition}, bins: Array<Rect>) {\n for (const id in images) {\n const src = images[id];\n const bin = {\n x: 0,\n y: 0,\n w: src.data.width + 2 * IMAGE_PADDING,\n h: src.data.height + 2 * IMAGE_PADDING,\n };\n bins.push(bin);\n positions[id] = new ImagePosition(bin, src);\n\n if (src.hasRenderCallback) {\n this.haveRenderCallbacks.push(id);\n }\n }\n }\n\n patchUpdatedImages(imageManager: ImageManager, texture: Texture) {\n 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 localGlyph?: boolean\n};\n\nexport type PositionedLine = {\n positionedGlyphs: Array<PositionedGlyph>,\n lineOffset: number\n};\n\n// A collection of positioned glyphs and some metadata\nexport type Shaping = {\n positionedLines: Array<PositionedLine>,\n top: number,\n bottom: number,\n left: number,\n right: number,\n writingMode: 1 | 2,\n text: string,\n iconsInText: boolean,\n verticalizable: boolean\n};\n\nfunction isEmpty(positionedLines: Array<PositionedLine>) {\n for (const line of positionedLines) {\n if (line.positionedGlyphs.length !== 0) {\n return false;\n }\n }\n return true;\n}\n\nexport type SymbolAnchor = 'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\nexport type TextJustify = 'left' | 'center' | 'right';\n\n// Max number of images in label is 6401 U+E000–U+F8FF that covers\n// Basic Multilingual Plane Unicode Private Use Area (PUA).\nconst PUAbegin = 0xE000;\nconst PUAend = 0xF8FF;\n\nclass SectionOptions {\n // Text options\n scale: number;\n fontStack: string;\n // Image options\n imageName: string | null;\n\n constructor() {\n this.scale = 1.0;\n this.fontStack = \"\";\n this.imageName = null;\n }\n\n static forText(scale: number | 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<number> // maps each character in 'text' to its corresponding entry in 'sections'\n sections: Array<SectionOptions>\n imageSectionID: number | null;\n\n constructor() {\n this.text = \"\";\n this.sectionIndex = [];\n this.sections = [];\n this.imageSectionID = null;\n }\n\n static fromFeature(text: Formatted, defaultFontStack: string) {\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<number>): Array<TaggedString> {\n const lines = [];\n const text = input.text;\n let start = 0;\n for (const lineBreak of lineBreakPoints) {\n lines.push(input.substring(start, lineBreak));\n start = lineBreak;\n }\n\n if (start < text.length) {\n lines.push(input.substring(start, text.length));\n }\n return lines;\n}\n\nfunction shapeText(text: Formatted,\n glyphMap: {[_: string]: {[_: 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<TaggedString>;\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<Break>,\n penalty: number,\n isLastBreak: boolean): Break {\n // We could skip evaluating breaks where the line length (breakX - priorBreak.x) > maxWidth\n // ...but in fact we allow lines longer than maxWidth (if there's no break points)\n // ...and when targetWidth and maxWidth are close, strictly enforcing maxWidth can give\n // more lopsided results.\n\n let bestPriorBreak: ?Break = null;\n let bestBreakBadness = calculateBadness(breakX, targetWidth, penalty, isLastBreak);\n\n for (const potentialBreak of potentialBreaks) {\n const lineWidth = breakX - potentialBreak.x;\n const breakBadness =\n calculateBadness(lineWidth, targetWidth, penalty, isLastBreak) + potentialBreak.badness;\n if (breakBadness <= bestBreakBadness) {\n bestPriorBreak = potentialBreak;\n bestBreakBadness = breakBadness;\n }\n }\n\n return {\n index: breakIndex,\n x: breakX,\n priorBreak: bestPriorBreak,\n badness: bestBreakBadness\n };\n}\n\nfunction leastBadBreaks(lastLineBreak: ?Break): Array<number> {\n if (!lastLineBreak) {\n return [];\n }\n return leastBadBreaks(lastLineBreak.priorBreak).concat(lastLineBreak.index);\n}\n\nfunction determineLineBreaks(logicalInput: TaggedString,\n spacing: number,\n maxWidth: number,\n glyphMap: {[_: string]: {[_: number]: ?StyleGlyph}},\n imagePositions: {[_: string]: ImagePosition},\n symbolPlacement: string,\n layoutTextSize: number): Array<number> {\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<TaggedString>,\n lineHeight: number,\n textAnchor: SymbolAnchor,\n textJustify: TextJustify,\n writingMode: 1 | 2,\n spacing: number,\n allowVerticalPlacement: boolean,\n layoutTextSizeThisZoom: number) {\n\n let x = 0;\n let y = 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 localGlyph: false};\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, localGlyph: metrics.localGlyph, 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, localGlyph: metrics.localGlyph, 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<PositionedGlyph>,\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<PositionedLine>,\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 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\nexport default checkMaxAngle;\n\nimport type Point from '@mapbox/point-geometry';\nimport type Anchor from './anchor';\n\n/**\n * Labels placed around really sharp angles aren't readable. Check if any\n * part of the potential label has a combined angle that is too big.\n *\n * @param line\n * @param anchor The point on the line around which the label is anchored.\n * @param labelLength The length of the label in geometry units.\n * @param windowSize The check fails if the combined angles within a part of the line that is `windowSize` long is too big.\n * @param maxAngle The maximum combined angle that any window along the label is allowed to have.\n *\n * @returns {boolean} whether the label should be placed\n * @private\n */\nfunction checkMaxAngle(line: Array<Point>, anchor: Anchor, labelLength: number, windowSize: number, maxAngle: number) {\n\n // horizontal labels always pass\n if (anchor.segment === undefined) return true;\n\n let p = anchor;\n let index = anchor.segment + 1;\n let anchorDistance = 0;\n\n // move backwards along the line to the first segment the label appears on\n while (anchorDistance > -labelLength / 2) {\n index--;\n\n // there isn't enough room for the label after the beginning of the line\n if (index < 0) return false;\n\n anchorDistance -= line[index].dist(p);\n p = line[index];\n }\n\n anchorDistance += line[index].dist(line[index + 1]);\n index++;\n\n // store recent corners and their total angle difference\n const recentCorners = [];\n let recentAngleDelta = 0;\n\n // move forwards by the length of the label and check angles along the way\n while (anchorDistance < labelLength / 2) {\n const prev = line[index - 1];\n const current = line[index];\n const next = line[index + 1];\n\n // there isn't enough room for the label before the end of the line\n if (!next) return false;\n\n let angleDelta = prev.angleTo(current) - current.angleTo(next);\n // restrict angle to -pi..pi range\n angleDelta = Math.abs(((angleDelta + 3 * Math.PI) % (Math.PI * 2)) - Math.PI);\n\n recentCorners.push({\n distance: anchorDistance,\n angleDelta\n });\n recentAngleDelta += angleDelta;\n\n // remove corners that are far enough away from the list of recent anchors\n while (anchorDistance - recentCorners[0].distance > windowSize) {\n recentAngleDelta -= recentCorners.shift().angleDelta;\n }\n\n // the sum of angles within the window area exceeds the maximum allowed value. check fails.\n if (recentAngleDelta > maxAngle) return false;\n\n index++;\n anchorDistance += current.dist(next);\n }\n\n // no part of the line had an angle greater than the maximum allowed. check passes.\n return true;\n}\n","// @flow\n\nimport {number as interpolate} from '../style-spec/util/interpolate';\n\nimport Anchor from '../symbol/anchor';\nimport checkMaxAngle from './check_max_angle';\n\nimport type Point from '@mapbox/point-geometry';\nimport type {Shaping, PositionedIcon} from './shaping';\n\nexport {getAnchors, getCenterAnchor};\n\nfunction getLineLength(line: Array<Point>): number {\n let lineLength = 0;\n for (let k = 0; k < line.length - 1; k++) {\n lineLength += line[k].dist(line[k + 1]);\n }\n return lineLength;\n}\n\nfunction getAngleWindowSize(shapedText: ?Shaping,\n glyphSize: number,\n boxScale: number): number {\n return shapedText ?\n 3 / 5 * glyphSize * boxScale :\n 0;\n}\n\nfunction getShapedLabelLength(shapedText: ?Shaping, shapedIcon: ?PositionedIcon): number {\n return Math.max(\n shapedText ? shapedText.right - shapedText.left : 0,\n shapedIcon ? shapedIcon.right - shapedIcon.left : 0);\n}\n\nfunction getCenterAnchor(line: Array<Point>,\n maxAngle: number,\n shapedText: ?Shaping,\n shapedIcon: ?PositionedIcon,\n glyphSize: number,\n boxScale: number) {\n const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale);\n const labelLength = getShapedLabelLength(shapedText, shapedIcon) * boxScale;\n\n let prevDistance = 0;\n const centerDistance = getLineLength(line) / 2;\n\n for (let i = 0; i < line.length - 1; i++) {\n\n const a = line[i],\n b = line[i + 1];\n\n const segmentDistance = a.dist(b);\n\n if (prevDistance + segmentDistance > centerDistance) {\n // The center is on this segment\n const t = (centerDistance - prevDistance) / segmentDistance,\n x = interpolate(a.x, b.x, t),\n y = interpolate(a.y, b.y, t);\n\n const anchor = new Anchor(x, y, b.angleTo(a), i);\n anchor._round();\n if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) {\n return anchor;\n } else {\n return;\n }\n }\n\n prevDistance += segmentDistance;\n }\n}\n\nfunction getAnchors(line: Array<Point>,\n spacing: number,\n maxAngle: number,\n shapedText: ?Shaping,\n shapedIcon: ?PositionedIcon,\n glyphSize: number,\n boxScale: number,\n overscaling: number,\n tileExtent: number) {\n\n // Resample a line to get anchor points for labels and check that each\n // potential label passes text-max-angle check and has enough froom to fit\n // on the line.\n\n const angleWindowSize = getAngleWindowSize(shapedText, glyphSize, boxScale);\n const shapedLabelLength = getShapedLabelLength(shapedText, shapedIcon);\n const labelLength = shapedLabelLength * boxScale;\n\n // Is the line continued from outside the tile boundary?\n const isLineContinued = line[0].x === 0 || line[0].x === tileExtent || line[0].y === 0 || line[0].y === tileExtent;\n\n // Is the label long, relative to the spacing?\n // If so, adjust the spacing so there is always a minimum space of `spacing / 4` between label edges.\n if (spacing - labelLength < spacing / 4) {\n spacing = labelLength + spacing / 4;\n }\n\n // Offset the first anchor by:\n // Either half the label length plus a fixed extra offset if the line is not continued\n // Or half the spacing if the line is continued.\n\n // For non-continued lines, add a bit of fixed extra offset to avoid collisions at T intersections.\n const fixedExtraOffset = glyphSize * 2;\n\n const offset = !isLineContinued ?\n ((shapedLabelLength / 2 + fixedExtraOffset) * boxScale * overscaling) % spacing :\n (spacing / 2 * overscaling) % spacing;\n\n return resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, false, tileExtent);\n}\n\nfunction resample(line, offset, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, placeAtMiddle, tileExtent) {\n\n const halfLabelLength = labelLength / 2;\n const lineLength = getLineLength(line);\n\n let distance = 0,\n markedDistance = offset - spacing;\n\n let anchors = [];\n\n for (let i = 0; i < line.length - 1; i++) {\n\n const a = line[i],\n b = line[i + 1];\n\n const segmentDist = a.dist(b),\n angle = b.angleTo(a);\n\n while (markedDistance + spacing < distance + segmentDist) {\n markedDistance += spacing;\n\n const t = (markedDistance - distance) / segmentDist,\n x = interpolate(a.x, b.x, t),\n y = interpolate(a.y, b.y, t);\n\n // Check that the point is within the tile boundaries and that\n // the label would fit before the beginning and end of the line\n // if placed at this point.\n if (x >= 0 && x < tileExtent && y >= 0 && y < tileExtent &&\n markedDistance - halfLabelLength >= 0 &&\n markedDistance + halfLabelLength <= lineLength) {\n const anchor = new Anchor(x, y, angle, i);\n anchor._round();\n\n if (!angleWindowSize || checkMaxAngle(line, anchor, labelLength, angleWindowSize, maxAngle)) {\n anchors.push(anchor);\n }\n }\n }\n\n distance += segmentDist;\n }\n\n if (!placeAtMiddle && !anchors.length && !isLineContinued) {\n // The first attempt at finding anchors at which labels can be placed failed.\n // Try again, but this time just try placing one anchor at the middle of the line.\n // This has the most effect for short lines in overscaled tiles, since the\n // initial offset used in overscaled tiles is calculated to align labels with positions in\n // parent tiles instead of placing the label as close to the beginning as possible.\n anchors = resample(line, distance / 2, spacing, angleWindowSize, maxAngle, labelLength, isLineContinued, true, tileExtent);\n }\n\n return anchors;\n}\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nexport default clipLine;\n\n/**\n * Returns the part of a multiline that intersects with the provided rectangular box.\n *\n * @param lines\n * @param x1 the left edge of the box\n * @param y1 the top edge of the box\n * @param x2 the right edge of the box\n * @param y2 the bottom edge of the box\n * @returns lines\n * @private\n */\nfunction clipLine(lines: Array<Array<Point>>, x1: number, y1: number, x2: number, y2: number): Array<Array<Point>> {\n const clippedLines = [];\n\n for (let l = 0; l < lines.length; l++) {\n const line = lines[l];\n let clippedLine;\n\n for (let i = 0; i < line.length - 1; i++) {\n let p0 = line[i];\n let p1 = line[i + 1];\n\n if (p0.x < x1 && p1.x < x1) {\n continue;\n } else if (p0.x < x1) {\n p0 = new Point(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round();\n } else if (p1.x < x1) {\n p1 = new Point(x1, p0.y + (p1.y - p0.y) * ((x1 - p0.x) / (p1.x - p0.x)))._round();\n }\n\n if (p0.y < y1 && p1.y < y1) {\n continue;\n } else if (p0.y < y1) {\n p0 = new Point(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round();\n } else if (p1.y < y1) {\n p1 = new Point(p0.x + (p1.x - p0.x) * ((y1 - p0.y) / (p1.y - p0.y)), y1)._round();\n }\n\n if (p0.x >= x2 && p1.x >= x2) {\n continue;\n } else if (p0.x >= x2) {\n p0 = new Point(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round();\n } else if (p1.x >= x2) {\n p1 = new Point(x2, p0.y + (p1.y - p0.y) * ((x2 - p0.x) / (p1.x - p0.x)))._round();\n }\n\n if (p0.y >= y2 && p1.y >= y2) {\n continue;\n } else if (p0.y >= y2) {\n p0 = new Point(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round();\n } else if (p1.y >= y2) {\n p1 = new Point(p0.x + (p1.x - p0.x) * ((y2 - p0.y) / (p1.y - p0.y)), y2)._round();\n }\n\n if (!clippedLine || !p0.equals(clippedLine[clippedLine.length - 1])) {\n clippedLine = [p0];\n clippedLines.push(clippedLine);\n }\n\n clippedLine.push(p1);\n }\n }\n\n return clippedLines;\n}\n","'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\n // For backwards compatibility, we honor the implicit contract that the\n // size of the returned bitmap will be fontSize + buffer * 2\n var size = this.size = this.fontSize + this.buffer * 2;\n // Glyphs may be slightly larger than their fontSize. The canvas already\n // has buffer space, but create extra buffer space in the output grid for the\n // \"halo\" to extend into (if metric extraction is enabled)\n var gridSize = size + 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.textAlign = 'left'; // Necessary so that RTL text doesn't have different alignment\n this.ctx.fillStyle = 'black';\n\n // temporary arrays for the distance transform\n this.gridOuter = new Float64Array(gridSize * gridSize);\n this.gridInner = new Float64Array(gridSize * gridSize);\n this.f = new Float64Array(gridSize);\n this.z = new Float64Array(gridSize + 1);\n this.v = new Uint16Array(gridSize);\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\nfunction prepareGrids(imgData, width, height, glyphWidth, glyphHeight, gridOuter, gridInner) {\n // Initialize grids outside the glyph range to alpha 0\n gridOuter.fill(INF, 0, width * height);\n gridInner.fill(0, 0, width * height);\n\n var offset = (width - glyphWidth) / 2; // This is zero if we're not extracting metrics\n\n for (var y = 0; y < glyphHeight; y++) {\n for (var x = 0; x < glyphWidth; x++) {\n var j = (y + offset) * width + x + offset;\n var a = imgData.data[4 * (y * glyphWidth + x) + 3] / 255; // alpha value\n if (a === 1) {\n gridOuter[j] = 0;\n gridInner[j] = INF;\n } else if (a === 0) {\n gridOuter[j] = INF;\n gridInner[j] = 0;\n } else {\n var b = Math.max(0, 0.5 - a);\n var c = Math.max(0, a - 0.5);\n gridOuter[j] = b * b;\n gridInner[j] = c * c;\n }\n }\n }\n}\n\nfunction extractAlpha(alphaChannel, width, height, gridOuter, gridInner, radius, cutoff) {\n for (var i = 0; i < width * height; i++) {\n var d = Math.sqrt(gridOuter[i]) - Math.sqrt(gridInner[i]);\n alphaChannel[i] = Math.round(255 - 255 * (d / radius + cutoff));\n }\n}\n\nTinySDF.prototype._draw = function (char, getMetrics) {\n var textMetrics = this.ctx.measureText(char);\n // Older browsers only expose the glyph width\n // This is enough for basic layout with all glyphs using the same fixed size\n var advance = textMetrics.width;\n\n var doubleBuffer = 2 * this.buffer;\n var width, glyphWidth, height, glyphHeight, top;\n\n var imgTop, imgLeft;\n // If the browser supports bounding box metrics, we can generate a smaller\n // SDF. This is a significant performance win.\n if (getMetrics && textMetrics.actualBoundingBoxLeft !== undefined) {\n // The integer/pixel part of the top alignment is encoded in metrics.top\n // The remainder is implicitly encoded in the rasterization\n top = Math.floor(textMetrics.actualBoundingBoxAscent) - this.middle;\n imgTop = Math.max(0, this.middle - Math.ceil(textMetrics.actualBoundingBoxAscent));\n imgLeft = this.buffer;\n\n // If the glyph overflows the canvas size, it will be clipped at the\n // bottom/right\n glyphWidth = Math.min(this.size,\n Math.ceil(textMetrics.actualBoundingBoxRight - textMetrics.actualBoundingBoxLeft));\n glyphHeight = Math.min(this.size - imgTop,\n Math.ceil(textMetrics.actualBoundingBoxAscent + textMetrics.actualBoundingBoxDescent));\n\n width = glyphWidth + doubleBuffer;\n height = glyphHeight + doubleBuffer;\n } else {\n width = glyphWidth = this.size;\n height = glyphHeight = this.size\n top = 0;\n imgTop = imgLeft = 0;\n }\n\n var imgData;\n if (glyphWidth && glyphHeight) {\n this.ctx.clearRect(imgLeft, imgTop, glyphWidth, glyphHeight);\n this.ctx.fillText(char, this.buffer, this.middle);\n imgData = this.ctx.getImageData(imgLeft, imgTop, glyphWidth, glyphHeight);\n }\n\n var alphaChannel = new Uint8ClampedArray(width * height);\n\n prepareGrids(imgData, width, height, glyphWidth, glyphHeight, this.gridOuter, this.gridInner);\n\n edt(this.gridOuter, width, height, this.f, this.v, this.z);\n edt(this.gridInner, width, height, this.f, this.v, this.z);\n\n extractAlpha(alphaChannel, width, height, this.gridOuter, this.gridInner, this.radius, this.cutoff);\n\n return {\n data: alphaChannel,\n metrics: {\n width: glyphWidth,\n height: glyphHeight,\n sdfWidth: width,\n sdfHeight: height,\n top: top,\n left: 0,\n advance: advance,\n fontAscent: textMetrics.fontBoundingBoxAscent\n }\n };\n};\n\nTinySDF.prototype.draw = function (char) {\n return this._draw(char, false).data;\n};\n\nTinySDF.prototype.drawWithMetrics = function (char) {\n return this._draw(char, true);\n};\n\n// 2D Euclidean squared distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf\nfunction edt(data, width, height, f, v, z) {\n for (var x = 0; x < width; x++) edt1d(data, x, width, height, f, v, z);\n for (var y = 0; y < height; y++) edt1d(data, y * width, 1, width, f, v, z);\n}\n\n// 1D squared distance transform\nfunction edt1d(grid, offset, stride, length, f, v, z) {\n var q, k, s, r;\n v[0] = 0;\n z[0] = -INF;\n z[1] = INF;\n\n for (q = 0; q < length; q++) f[q] = grid[offset + q * stride];\n\n for (q = 1, k = 0, s = 0; q < length; q++) {\n do {\n r = v[k];\n s = (f[q] - f[r] + q * q - r * r) / (q - r) / 2;\n } while (s <= z[k] && --k > -1);\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 < length; q++) {\n while (z[k + 1] < q) k++;\n r = v[k];\n grid[offset + q * stride] = f[r] + (q - r) * (q - r);\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\n/*\n SDF_SCALE controls the pixel density of locally generated glyphs relative\n to \"normal\" SDFs which are generated at 24pt font and a \"pixel ratio\" of 1.\n The GlyphManager will generate glyphs SDF_SCALE times as large,\n but with the same glyph metrics, and the quad generation code will scale them\n back down so they display at the same size.\n\n The choice of SDF_SCALE is a trade-off between performance and quality.\n Glyph generation time grows quadratically with the the scale, while quality\n improvements drop off rapidly when the scale is higher than the pixel ratio\n of the device. The scale of 2 buys noticeable improvements on HDPI screens\n at acceptable cost.\n\n The scale can be any value, but in order to avoid small distortions, these\n pixel-based values must come out to integers:\n - \"localGlyphPadding\" in GlyphAtlas\n - Font/Canvas/Buffer size for TinySDF\n localGlyphPadding + buffer should equal 4 * SDF_SCALE. So if you wanted to\n use an SDF_SCALE of 1.75, you could manually set localGlyphAdding to 2 and\n buffer to 5.\n*/\nexport const SDF_SCALE = 2;\n\ntype Entry = {\n // null means we've requested the range, but the glyph wasn't included in the result.\n glyphs: {[id: number]: StyleGlyph | null},\n requests: {[range: number]: Array<Callback<{[_: number]: StyleGlyph | null}>>},\n ranges: {[range: number]: boolean | null},\n tinySDF?: TinySDF\n};\n\nexport const LocalGlyphMode = {\n none: 0,\n ideographs: 1,\n all: 2\n};\n\nclass GlyphManager {\n requestManager: RequestManager;\n localFontFamily: ?string;\n localGlyphMode: number;\n entries: {[_: string]: Entry};\n // Multiple fontstacks may share the same local glyphs, so keep an index\n // into the glyphs based soley on font weight\n localGlyphs: {[_: string]: {[id: number]: StyleGlyph | null}};\n url: ?string;\n\n // exposed as statics to enable stubbing in unit tests\n static loadGlyphRange: typeof loadGlyphRange;\n static TinySDF: Class<TinySDF>;\n\n constructor(requestManager: RequestManager, localGlyphMode: number, localFontFamily: ?string) {\n this.requestManager = requestManager;\n this.localGlyphMode = localGlyphMode;\n this.localFontFamily = localFontFamily;\n this.entries = {};\n this.localGlyphs = {\n // Only these four font weights are supported\n '200': {},\n '400': {},\n '500': {},\n '900': {}\n };\n }\n\n setURL(url: ?string) {\n this.url = url;\n }\n\n getGlyphs(glyphs: {[stack: string]: Array<number>}, callback: Callback<{[stack: string]: {[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 if (this.localGlyphMode === LocalGlyphMode.none) {\n return false;\n } else if (this.localGlyphMode === LocalGlyphMode.all) {\n return !!this.localFontFamily;\n } else {\n /* eslint-disable new-cap */\n return !!this.localFontFamily &&\n (isChar['CJK Unified Ideographs'](id) ||\n isChar['Hangul Syllables'](id) ||\n isChar['Hiragana'](id) ||\n isChar['Katakana'](id));\n /* eslint-enable new-cap */\n }\n }\n\n _tinySDF(entry: Entry, stack: string, id: number): ?StyleGlyph {\n const family = this.localFontFamily;\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 * SDF_SCALE, 3 * SDF_SCALE, 8 * SDF_SCALE, .25, family, fontWeight);\n }\n\n if (this.localGlyphs[tinySDF.fontWeight][id]) {\n return this.localGlyphs[tinySDF.fontWeight][id];\n }\n\n const {data, metrics} = tinySDF.drawWithMetrics(String.fromCharCode(id));\n const {fontAscent, sdfWidth, sdfHeight, width, height, left, top, advance} = metrics;\n // TinySDF's \"top\" is the distance from the top of the canvas to the top of the glyph,\n // but drawn with `CanvasRenderingContext2D.textBaseline` = \"middle\", as opposed to\n // the lower alphabetic baseline.\n // Although we don't currently know the actual baseline of server supplied fonts\n // (we might in the future, see: https://github.com/mapbox/node-fontnik/pull/160),\n // we can guess the approximate difference between server-font baselines and this\n // baseline using the \"top\" metric for DIN Office Pro's \"A\", which is -8.\n // Modifying the adjustment based on the measured local font ascent ensures\n // that local glyphs from different fonts will share the same baseline\n const ascent = fontAscent ? (fontAscent / SDF_SCALE) : 17; // From SHAPING_DEFAULT_OFFSET\n const baselineAdjustment = ascent - 9;\n\n const glyph = this.localGlyphs[tinySDF.fontWeight][id] = {\n id,\n bitmap: new AlphaImage({\n width: sdfWidth,\n height: sdfHeight\n }, data),\n metrics: {\n width: width / SDF_SCALE,\n height: height / SDF_SCALE,\n left: left / SDF_SCALE,\n top: top / SDF_SCALE - baselineAdjustment,\n advance: advance / SDF_SCALE,\n localGlyph: true\n }\n };\n return glyph;\n }\n}\n\nGlyphManager.loadGlyphRange = loadGlyphRange;\nGlyphManager.TinySDF = TinySDF;\n\nexport default GlyphManager;\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport {GLYPH_PBF_BORDER} from '../style/parse_glyph_pbf';\n\nimport type Anchor from './anchor';\nimport type {PositionedIcon, Shaping} from './shaping';\nimport {SHAPING_DEFAULT_OFFSET} from './shaping';\nimport {IMAGE_PADDING} from '../render/image_atlas';\nimport {SDF_SCALE} from '../render/glyph_manager';\nimport type SymbolStyleLayer from '../style/style_layer/symbol_style_layer';\nimport type {Feature} from '../style-spec/expression';\nimport type {StyleImage} from '../style/style_image';\nimport ONE_EM from './one_em';\n\n/**\n * A textured quad for rendering a single icon or glyph.\n *\n * The zoom range the glyph can be shown is defined by minScale and maxScale.\n *\n * @param tl The offset of the top left corner from the anchor.\n * @param tr The offset of the top right corner from the anchor.\n * @param bl The offset of the bottom left corner from the anchor.\n * @param br The offset of the bottom right corner from the anchor.\n * @param tex The texture coordinates.\n *\n * @private\n */\nexport type SymbolQuad = {\n tl: Point,\n tr: Point,\n bl: Point,\n br: Point,\n tex: {\n x: number,\n y: number,\n w: number,\n h: number\n },\n pixelOffsetTL: Point,\n pixelOffsetBR: Point,\n writingMode: any | void,\n glyphOffset: [number, number],\n sectionIndex: number,\n isSDF: boolean,\n minFontScaleX: number,\n minFontScaleY: number\n};\n\n// If you have a 10px icon that isn't perfectly aligned to the pixel grid it will cover 11 actual\n// pixels. The quad needs to be padded to account for this, otherwise they'll look slightly clipped\n// on one edge in some cases.\nconst border = IMAGE_PADDING;\n\n/**\n * Create the quads used for rendering an icon.\n * @private\n */\nexport function getIconQuads(\n shapedIcon: PositionedIcon,\n iconRotate: number,\n isSDFIcon: boolean,\n hasIconTextFit: boolean): Array<SymbolQuad> {\n const quads = [];\n\n const image = shapedIcon.image;\n const pixelRatio = image.pixelRatio;\n const imageWidth = image.paddedRect.w - 2 * border;\n const imageHeight = image.paddedRect.h - 2 * border;\n\n const iconWidth = shapedIcon.right - shapedIcon.left;\n const iconHeight = shapedIcon.bottom - shapedIcon.top;\n\n const stretchX = image.stretchX || [[0, imageWidth]];\n const stretchY = image.stretchY || [[0, imageHeight]];\n\n const reduceRanges = (sum, range) => sum + range[1] - range[0];\n const stretchWidth = stretchX.reduce(reduceRanges, 0);\n const stretchHeight = stretchY.reduce(reduceRanges, 0);\n const fixedWidth = imageWidth - stretchWidth;\n const fixedHeight = imageHeight - stretchHeight;\n\n let stretchOffsetX = 0;\n let stretchContentWidth = stretchWidth;\n let stretchOffsetY = 0;\n let stretchContentHeight = stretchHeight;\n let fixedOffsetX = 0;\n let fixedContentWidth = fixedWidth;\n let fixedOffsetY = 0;\n let fixedContentHeight = fixedHeight;\n\n if (image.content && hasIconTextFit) {\n const content = image.content;\n stretchOffsetX = sumWithinRange(stretchX, 0, content[0]);\n stretchOffsetY = sumWithinRange(stretchY, 0, content[1]);\n stretchContentWidth = sumWithinRange(stretchX, content[0], content[2]);\n stretchContentHeight = sumWithinRange(stretchY, content[1], content[3]);\n fixedOffsetX = content[0] - stretchOffsetX;\n fixedOffsetY = content[1] - stretchOffsetY;\n fixedContentWidth = content[2] - content[0] - stretchContentWidth;\n fixedContentHeight = content[3] - content[1] - stretchContentHeight;\n }\n\n const makeBox = (left, top, right, bottom) => {\n\n const leftEm = getEmOffset(left.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left);\n const leftPx = getPxOffset(left.fixed - fixedOffsetX, fixedContentWidth, left.stretch, stretchWidth);\n\n const topEm = getEmOffset(top.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top);\n const topPx = getPxOffset(top.fixed - fixedOffsetY, fixedContentHeight, top.stretch, stretchHeight);\n\n const rightEm = getEmOffset(right.stretch - stretchOffsetX, stretchContentWidth, iconWidth, shapedIcon.left);\n const rightPx = getPxOffset(right.fixed - fixedOffsetX, fixedContentWidth, right.stretch, stretchWidth);\n\n const bottomEm = getEmOffset(bottom.stretch - stretchOffsetY, stretchContentHeight, iconHeight, shapedIcon.top);\n const bottomPx = getPxOffset(bottom.fixed - fixedOffsetY, fixedContentHeight, bottom.stretch, stretchHeight);\n\n const tl = new Point(leftEm, topEm);\n const tr = new Point(rightEm, topEm);\n const br = new Point(rightEm, bottomEm);\n const bl = new Point(leftEm, bottomEm);\n const pixelOffsetTL = new Point(leftPx / pixelRatio, topPx / pixelRatio);\n const pixelOffsetBR = new Point(rightPx / pixelRatio, bottomPx / pixelRatio);\n\n const angle = iconRotate * Math.PI / 180;\n\n if (angle) {\n const sin = Math.sin(angle),\n cos = Math.cos(angle),\n matrix = [cos, -sin, sin, cos];\n\n tl._matMult(matrix);\n tr._matMult(matrix);\n bl._matMult(matrix);\n br._matMult(matrix);\n }\n\n const x1 = left.stretch + left.fixed;\n const x2 = right.stretch + right.fixed;\n const y1 = top.stretch + top.fixed;\n const y2 = bottom.stretch + bottom.fixed;\n\n const subRect = {\n x: image.paddedRect.x + border + x1,\n y: image.paddedRect.y + border + y1,\n w: x2 - x1,\n h: y2 - y1\n };\n\n const minFontScaleX = fixedContentWidth / pixelRatio / iconWidth;\n const minFontScaleY = fixedContentHeight / pixelRatio / iconHeight;\n\n // Icon quad is padded, so texture coordinates also need to be padded.\n return {tl, tr, bl, br, tex: subRect, writingMode: undefined, glyphOffset: [0, 0], sectionIndex: 0, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY, isSDF: isSDFIcon};\n };\n\n if (!hasIconTextFit || (!image.stretchX && !image.stretchY)) {\n quads.push(makeBox(\n {fixed: 0, stretch: -1},\n {fixed: 0, stretch: -1},\n {fixed: 0, stretch: imageWidth + 1},\n {fixed: 0, stretch: imageHeight + 1}));\n } else {\n const xCuts = stretchZonesToCuts(stretchX, fixedWidth, stretchWidth);\n const yCuts = stretchZonesToCuts(stretchY, fixedHeight, stretchHeight);\n\n for (let xi = 0; xi < xCuts.length - 1; xi++) {\n const x1 = xCuts[xi];\n const x2 = xCuts[xi + 1];\n for (let yi = 0; yi < yCuts.length - 1; yi++) {\n const y1 = yCuts[yi];\n const y2 = yCuts[yi + 1];\n quads.push(makeBox(x1, y1, x2, y2));\n }\n }\n }\n\n return quads;\n}\n\nfunction sumWithinRange(ranges, min, max) {\n let sum = 0;\n for (const range of ranges) {\n sum += Math.max(min, Math.min(max, range[1])) - Math.max(min, Math.min(max, range[0]));\n }\n return sum;\n}\n\nfunction stretchZonesToCuts(stretchZones, fixedSize, stretchSize) {\n const cuts = [{fixed: -border, stretch: 0}];\n\n for (const [c1, c2] of stretchZones) {\n const last = cuts[cuts.length - 1];\n cuts.push({\n fixed: c1 - last.stretch,\n stretch: last.stretch\n });\n cuts.push({\n fixed: c1 - last.stretch,\n stretch: last.stretch + (c2 - c1)\n });\n }\n cuts.push({\n fixed: fixedSize + border,\n stretch: stretchSize\n });\n return cuts;\n}\n\nfunction getEmOffset(stretchOffset, stretchSize, iconSize, iconOffset) {\n return stretchOffset / stretchSize * iconSize + iconOffset;\n}\n\nfunction getPxOffset(fixedOffset, fixedSize, stretchOffset, stretchSize) {\n return fixedOffset - fixedSize * stretchOffset / stretchSize;\n}\n\n/**\n * Create the quads used for rendering a text label.\n * @private\n */\nexport function getGlyphQuads(anchor: Anchor,\n shaping: Shaping,\n textOffset: [number, number],\n layer: SymbolStyleLayer,\n alongLine: boolean,\n feature: Feature,\n imageMap: {[_: string]: StyleImage},\n allowVerticalPlacement: boolean): Array<SymbolQuad> {\n\n const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}) * Math.PI / 180;\n const quads = [];\n\n for (const line of shaping.positionedLines) {\n for (const positionedGlyph of line.positionedGlyphs) {\n if (!positionedGlyph.rect) continue;\n const textureRect = positionedGlyph.rect || {};\n\n // The rects have an additional buffer that is not included in their size.\n const glyphPadding = 1.0;\n let rectBuffer = GLYPH_PBF_BORDER + glyphPadding;\n let isSDF = true;\n let pixelRatio = 1.0;\n let lineOffset = 0.0;\n\n const rotateVerticalGlyph = (alongLine || allowVerticalPlacement) && positionedGlyph.vertical;\n const halfAdvance = positionedGlyph.metrics.advance * positionedGlyph.scale / 2;\n\n // Align images and scaled glyphs in the middle of a vertical line.\n if (allowVerticalPlacement && shaping.verticalizable) {\n const scaledGlyphOffset = (positionedGlyph.scale - 1) * ONE_EM;\n const imageOffset = (ONE_EM - positionedGlyph.metrics.width * positionedGlyph.scale) / 2;\n lineOffset = line.lineOffset / 2 - (positionedGlyph.imageName ? -imageOffset : scaledGlyphOffset);\n }\n\n if (positionedGlyph.imageName) {\n const image = imageMap[positionedGlyph.imageName];\n isSDF = image.sdf;\n pixelRatio = image.pixelRatio;\n rectBuffer = IMAGE_PADDING / pixelRatio;\n }\n\n const glyphOffset = alongLine ?\n [positionedGlyph.x + halfAdvance, positionedGlyph.y] :\n [0, 0];\n\n let builtInOffset = alongLine ?\n [0, 0] :\n [positionedGlyph.x + halfAdvance + textOffset[0], positionedGlyph.y + textOffset[1] - lineOffset];\n\n let verticalizedLabelOffset = [0, 0];\n if (rotateVerticalGlyph) {\n // Vertical POI labels that are rotated 90deg CW and whose glyphs must preserve upright orientation\n // need to be rotated 90deg CCW. After a quad is rotated, it is translated to the original built-in offset.\n verticalizedLabelOffset = builtInOffset;\n builtInOffset = [0, 0];\n }\n\n const x1 = (positionedGlyph.metrics.left - rectBuffer) * positionedGlyph.scale - halfAdvance + builtInOffset[0];\n const y1 = (-positionedGlyph.metrics.top - rectBuffer) * positionedGlyph.scale + builtInOffset[1];\n const x2 = x1 + textureRect.w * positionedGlyph.scale / (pixelRatio * (positionedGlyph.localGlyph ? SDF_SCALE : 1));\n const y2 = y1 + textureRect.h * positionedGlyph.scale / (pixelRatio * (positionedGlyph.localGlyph ? SDF_SCALE : 1));\n\n const tl = new Point(x1, y1);\n const tr = new Point(x2, y1);\n const bl = new Point(x1, y2);\n const br = new Point(x2, y2);\n\n if (rotateVerticalGlyph) {\n // Vertical-supporting glyphs are laid out in 24x24 point boxes (1 square em)\n // In horizontal orientation, the y values for glyphs are below the midline\n // and we use a \"yOffset\" of -17 to pull them up to the middle.\n // By rotating counter-clockwise around the point at the center of the left\n // edge of a 24x24 layout box centered below the midline, we align the center\n // of the glyphs with the horizontal midline, so the yOffset is no longer\n // necessary, but we also pull the glyph to the left along the x axis.\n // The y coordinate includes baseline yOffset, thus needs to be accounted\n // for when glyph is rotated and translated.\n const center = new Point(-halfAdvance, halfAdvance - SHAPING_DEFAULT_OFFSET);\n const verticalRotation = -Math.PI / 2;\n\n // xHalfWidthOffsetCorrection is a difference between full-width and half-width\n // advance, should be 0 for full-width glyphs and will pull up half-width glyphs.\n const xHalfWidthOffsetCorrection = ONE_EM / 2 - halfAdvance;\n const yImageOffsetCorrection = positionedGlyph.imageName ? xHalfWidthOffsetCorrection : 0.0;\n const halfWidthOffsetCorrection = new Point(5 - SHAPING_DEFAULT_OFFSET - xHalfWidthOffsetCorrection, -yImageOffsetCorrection);\n const verticalOffsetCorrection = new Point(...verticalizedLabelOffset);\n tl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);\n tr._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);\n bl._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);\n br._rotateAround(verticalRotation, center)._add(halfWidthOffsetCorrection)._add(verticalOffsetCorrection);\n }\n\n if (textRotate) {\n const sin = Math.sin(textRotate),\n cos = Math.cos(textRotate),\n matrix = [cos, -sin, sin, cos];\n\n tl._matMult(matrix);\n tr._matMult(matrix);\n bl._matMult(matrix);\n br._matMult(matrix);\n }\n\n const pixelOffsetTL = new Point(0, 0);\n const pixelOffsetBR = new Point(0, 0);\n const minFontScaleX = 0;\n const minFontScaleY = 0;\n quads.push({tl, tr, bl, br, tex: textureRect, writingMode: shaping.writingMode, glyphOffset, sectionIndex: positionedGlyph.sectionIndex, isSDF, pixelOffsetTL, pixelOffsetBR, minFontScaleX, minFontScaleY});\n }\n }\n\n return quads;\n}\n","// @flow\n\nimport {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","\nexport default class TinyQueue {\n constructor(data = [], compare = defaultCompare) {\n this.data = data;\n this.length = this.data.length;\n this.compare = compare;\n\n if (this.length > 0) {\n for (let i = (this.length >> 1) - 1; i >= 0; i--) this._down(i);\n }\n }\n\n push(item) {\n this.data.push(item);\n this.length++;\n this._up(this.length - 1);\n }\n\n pop() {\n if (this.length === 0) return undefined;\n\n const top = this.data[0];\n const bottom = this.data.pop();\n this.length--;\n\n if (this.length > 0) {\n this.data[0] = bottom;\n this._down(0);\n }\n\n return top;\n }\n\n peek() {\n return this.data[0];\n }\n\n _up(pos) {\n const {data, compare} = this;\n const item = data[pos];\n\n while (pos > 0) {\n const parent = (pos - 1) >> 1;\n const current = data[parent];\n if (compare(item, current) >= 0) break;\n data[pos] = current;\n pos = parent;\n }\n\n data[pos] = item;\n }\n\n _down(pos) {\n const {data, compare} = this;\n const halfLength = this.length >> 1;\n const item = data[pos];\n\n while (pos < halfLength) {\n let left = (pos << 1) + 1;\n let best = data[left];\n const right = left + 1;\n\n if (right < this.length && compare(data[right], best) < 0) {\n left = right;\n best = data[right];\n }\n if (compare(best, item) >= 0) break;\n\n data[pos] = best;\n pos = left;\n }\n\n data[pos] = item;\n }\n}\n\nfunction defaultCompare(a, b) {\n return a < b ? -1 : a > b ? 1 : 0;\n}\n","// @flow\n\nimport Queue from 'tinyqueue';\n\nimport Point from '@mapbox/point-geometry';\nimport {distToSegmentSquared} from './intersection_tests';\n\n/**\n * Finds an approximation of a polygon's Pole Of Inaccessibiliy https://en.wikipedia.org/wiki/Pole_of_inaccessibility\n * This is a copy of http://github.com/mapbox/polylabel adapted to use Points\n *\n * @param polygonRings first item in array is the outer ring followed optionally by the list of holes, should be an element of the result of util/classify_rings\n * @param precision Specified in input coordinate units. If 0 returns after first run, if > 0 repeatedly narrows the search space until the radius of the area searched for the best pole is less than precision\n * @param debug Print some statistics to the console during execution\n * @returns Pole of Inaccessibiliy.\n * @private\n */\nexport default function (polygonRings: Array<Array<Point>>, precision?: number = 1, debug?: boolean = false): Point {\n // find the bounding box of the outer ring\n let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;\n const outerRing = polygonRings[0];\n for (let i = 0; i < outerRing.length; i++) {\n const p = outerRing[i];\n if (!i || p.x < minX) minX = p.x;\n if (!i || p.y < minY) minY = p.y;\n if (!i || p.x > maxX) maxX = p.x;\n if (!i || p.y > maxY) maxY = p.y;\n }\n\n const width = maxX - minX;\n const height = maxY - minY;\n const cellSize = Math.min(width, height);\n let h = cellSize / 2;\n\n // a priority queue of cells in order of their \"potential\" (max distance to polygon)\n const cellQueue = new Queue([], compareMax);\n\n if (cellSize === 0) return new Point(minX, minY);\n\n // cover polygon with initial cells\n for (let x = minX; x < maxX; x += cellSize) {\n for (let y = minY; y < maxY; y += cellSize) {\n cellQueue.push(new Cell(x + h, y + h, h, polygonRings));\n }\n }\n\n // take centroid as the first best guess\n let bestCell = getCentroidCell(polygonRings);\n let numProbes = cellQueue.length;\n\n while (cellQueue.length) {\n // pick the most promising cell from the queue\n const cell = cellQueue.pop();\n\n // update the best cell if we found a better one\n if (cell.d > bestCell.d || !bestCell.d) {\n bestCell = cell;\n if (debug) console.log('found best %d after %d probes', Math.round(1e4 * cell.d) / 1e4, numProbes);\n }\n\n // do not drill down further if there's no chance of a better solution\n if (cell.max - bestCell.d <= precision) continue;\n\n // split the cell into four cells\n h = cell.h / 2;\n cellQueue.push(new Cell(cell.p.x - h, cell.p.y - h, h, polygonRings));\n cellQueue.push(new Cell(cell.p.x + h, cell.p.y - h, h, polygonRings));\n cellQueue.push(new Cell(cell.p.x - h, cell.p.y + h, h, polygonRings));\n cellQueue.push(new Cell(cell.p.x + h, cell.p.y + h, h, polygonRings));\n numProbes += 4;\n }\n\n if (debug) {\n console.log(`num probes: ${numProbes}`);\n console.log(`best distance: ${bestCell.d}`);\n }\n\n return bestCell.p;\n}\n\nfunction compareMax(a, b) {\n return b.max - a.max;\n}\n\nfunction Cell(x, y, h, polygon) {\n this.p = new Point(x, y);\n this.h = h; // half the cell size\n this.d = pointToPolygonDist(this.p, polygon); // distance from cell center to polygon\n this.max = this.d + this.h * Math.SQRT2; // max distance to polygon within a cell\n}\n\n// signed distance from point to polygon outline (negative if point is outside)\nfunction pointToPolygonDist(p, polygon) {\n let inside = false;\n let minDistSq = Infinity;\n\n for (let k = 0; k < polygon.length; k++) {\n const ring = polygon[k];\n\n for (let i = 0, len = ring.length, j = len - 1; i < len; j = i++) {\n const a = ring[i];\n const b = ring[j];\n\n if ((a.y > p.y !== b.y > p.y) &&\n (p.x < (b.x - a.x) * (p.y - a.y) / (b.y - a.y) + a.x)) inside = !inside;\n\n minDistSq = Math.min(minDistSq, distToSegmentSquared(p, a, b));\n }\n }\n\n return (inside ? 1 : -1) * Math.sqrt(minDistSq);\n}\n\n// get polygon centroid\nfunction getCentroidCell(polygon) {\n let area = 0;\n let x = 0;\n let y = 0;\n const points = polygon[0];\n for (let i = 0, len = points.length, j = len - 1; i < len; j = i++) {\n const a = points[i];\n const b = points[j];\n const f = a.x * b.y - b.x * a.y;\n x += (a.x + b.x) * f;\n y += (a.y + b.y) * f;\n area += f * 3;\n }\n return new Cell(x / area, y / area, 0, polygon);\n}\n","// @flow\n\nimport Anchor from './anchor';\n\nimport {getAnchors, getCenterAnchor} from './get_anchors';\nimport clipLine from './clip_line';\nimport {shapeText, shapeIcon, WritingMode, fitIconToText} from './shaping';\nimport {getGlyphQuads, getIconQuads} from './quads';\nimport {warnOnce, degToRad} 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<number>, // (3)\n layoutIconSize: PossiblyEvaluatedPropertyValue<number>, // (3)\n textMaxSize: PossiblyEvaluatedPropertyValue<number>, // (4)\n compositeTextSizes: [PossiblyEvaluatedPropertyValue<number>, PossiblyEvaluatedPropertyValue<number>], // (5)\n compositeIconSizes: [PossiblyEvaluatedPropertyValue<number>, PossiblyEvaluatedPropertyValue<number>], // (5)\n};\n\nexport type TextAnchor = 'center' | 'left' | 'right' | 'top' | 'bottom' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right';\n\n// The radial offset is to the edge of the text box\n// In the horizontal direction, the edge of the text box is where glyphs start\n// But in the vertical direction, the glyphs appear to \"start\" at the baseline\n// We don't actually load baseline data, but we assume an offset of ONE_EM - 17\n// (see \"yOffset\" in shaping.js)\nconst baselineOffset = 7;\nconst INVALID_TEXT_OFFSET = Number.POSITIVE_INFINITY;\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 tileZoom: number) {\n bucket.createArrays();\n\n const tileSize = 512 * bucket.overscaling;\n bucket.tilePixelRatio = EXTENT / tileSize;\n bucket.compareText = {};\n bucket.iconsNeedLinear = false;\n\n const layout = bucket.layers[0].layout;\n const unevaluatedLayoutValues = bucket.layers[0]._unevaluatedLayout._values;\n\n const sizes = {};\n\n if (bucket.textSizeData.kind === 'composite') {\n const {minZoom, maxZoom} = bucket.textSizeData;\n sizes.compositeTextSizes = [\n unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(minZoom), canonical),\n unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), canonical)\n ];\n }\n\n if (bucket.iconSizeData.kind === 'composite') {\n const {minZoom, maxZoom} = bucket.iconSizeData;\n sizes.compositeIconSizes = [\n unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(minZoom), canonical),\n unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(maxZoom), canonical)\n ];\n }\n\n sizes.layoutTextSize = unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(tileZoom + 1), canonical);\n sizes.layoutIconSize = unevaluatedLayoutValues['icon-size'].possiblyEvaluate(new EvaluationParameters(tileZoom + 1), canonical);\n sizes.textMaxSize = unevaluatedLayoutValues['text-size'].possiblyEvaluate(new EvaluationParameters(18), canonical);\n\n const 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(tileZoom, bucket.collisionBoxArray);\n }\n}\n\n// Choose the justification that matches the direction of the TextAnchor\nexport function getAnchorJustification(anchor: TextAnchor): TextJustify {\n switch (anchor) {\n case 'right':\n case 'top-right':\n case 'bottom-right':\n return 'right';\n case 'left':\n case 'top-left':\n case 'bottom-left':\n return 'left';\n }\n return 'center';\n}\n\n/**\n * 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, {}, canonical);\n if (textMaxSize === undefined) {\n textMaxSize = layoutTextSize;\n }\n const layout = bucket.layers[0].layout;\n const iconOffset = layout.get('icon-offset').evaluate(feature, {}, canonical);\n const defaultHorizontalShaping = getDefaultHorizontalShaping(shapedTextOrientations.horizontal);\n const glyphSize = ONE_EM,\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 = degToRad(layout.get('text-max-angle')),\n textAlongLine = layout.get('text-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point',\n iconAlongLine = layout.get('icon-rotation-alignment') === 'map' && layout.get('symbol-placement') !== 'point',\n symbolPlacement = layout.get('symbol-placement'),\n textRepeatDistance = symbolMinDistance / 2;\n\n const iconTextFit = layout.get('icon-text-fit');\n let verticallyShapedIcon;\n // 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, {}, canonical)\n ];\n if (textSizeData[0] > MAX_PACKED_SIZE) {\n warnOnce(`${bucket.layerIds[0]}: Value for \"text-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"text-size\".`);\n }\n } else if (sizeData.kind === 'composite') {\n textSizeData = [\n SIZE_PACK_FACTOR * sizes.compositeTextSizes[0].evaluate(feature, {}, canonical),\n SIZE_PACK_FACTOR * sizes.compositeTextSizes[1].evaluate(feature, {}, canonical)\n ];\n if (textSizeData[0] > MAX_PACKED_SIZE || textSizeData[1] > MAX_PACKED_SIZE) {\n warnOnce(`${bucket.layerIds[0]}: Value for \"text-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"text-size\".`);\n }\n }\n\n bucket.addSymbols(\n bucket.text,\n glyphQuads,\n textSizeData,\n textOffset,\n textAlongLine,\n feature,\n writingMode,\n 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\nexport function evaluateBoxCollisionFeature(collisionBoxArray: CollisionBoxArray,\n anchor: Anchor,\n featureIndex: number,\n sourceLayerIndex: number,\n bucketIndex: number,\n shaped: Object,\n boxScale: number,\n padding: number,\n rotate: number): number {\n let y1 = shaped.top;\n let y2 = shaped.bottom;\n let x1 = shaped.left;\n let x2 = shaped.right;\n\n const collisionPadding = shaped.collisionPadding;\n if (collisionPadding) {\n x1 -= collisionPadding[0];\n y1 -= collisionPadding[1];\n x2 += collisionPadding[2];\n y2 += collisionPadding[3];\n }\n\n if (rotate) {\n // Account for *-rotate in point collision boxes\n // See https://github.com/mapbox/mapbox-gl-js/issues/6075\n // Doesn't account for icon-text-fit\n\n const tl = new Point(x1, y1);\n const tr = new Point(x2, y1);\n const bl = new Point(x1, y2);\n const br = new Point(x2, y2);\n\n const rotateRadians = degToRad(rotate);\n\n tl._rotate(rotateRadians);\n tr._rotate(rotateRadians);\n bl._rotate(rotateRadians);\n br._rotate(rotateRadians);\n\n // Collision features require an \"on-axis\" geometry,\n // so take the envelope of the rotated geometry\n // (may be quite large for wide labels rotated 45 degrees)\n x1 = Math.min(tl.x, tr.x, bl.x, br.x);\n x2 = Math.max(tl.x, tr.x, bl.x, br.x);\n y1 = Math.min(tl.y, tr.y, bl.y, br.y);\n y2 = Math.max(tl.y, tr.y, bl.y, br.y);\n }\n\n collisionBoxArray.emplaceBack(anchor.x, anchor.y, x1, y1, x2, y2, padding, featureIndex, sourceLayerIndex, bucketIndex);\n\n return collisionBoxArray.length - 1;\n}\n\nexport function evaluateCircleCollisionFeature(shaped: Object): number | null {\n if (shaped.collisionPadding) {\n // Compute height of the shape in glyph metrics and apply padding.\n // Note that the pixel based 'text-padding' is applied at runtime\n shaped.top -= shaped.collisionPadding[1];\n shaped.bottom += shaped.collisionPadding[3];\n }\n\n // Set minimum box height to avoid very many small labels\n const height = shaped.bottom - shaped.top;\n return height > 0 ? Math.max(10, height) : null;\n}\n\n/**\n * Add a single label & icon placement.\n *\n * @private\n */\nfunction addSymbol(bucket: SymbolBucket,\n anchor: Anchor,\n line: Array<Point>,\n shapedTextOrientations: any,\n shapedIcon: PositionedIcon | void,\n imageMap: {[_: string]: StyleImage},\n verticallyShapedIcon: PositionedIcon | void,\n layer: SymbolStyleLayer,\n collisionBoxArray: CollisionBoxArray,\n featureIndex: number,\n sourceLayerIndex: number,\n bucketIndex: number,\n 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 textBoxIndex, iconBoxIndex, verticalTextBoxIndex, verticalIconBoxIndex;\n let textCircle, verticalTextCircle, verticalIconCircle;\n\n let numIconVertices = 0;\n let numVerticalIconVertices = 0;\n let numHorizontalGlyphVertices = 0;\n let numVerticalGlyphVertices = 0;\n let placedIconSymbolIndex = -1;\n let verticalPlacedIconSymbolIndex = -1;\n const placedTextSymbolIndices = {};\n let key = murmur3('');\n\n let textOffset0 = 0;\n let textOffset1 = 0;\n if (layer._unevaluatedLayout.getValue('text-radial-offset') === undefined) {\n [textOffset0, textOffset1] = (layer.layout.get('text-offset').evaluate(feature, {}, canonical).map(t => t * ONE_EM): any);\n } else {\n textOffset0 = layer.layout.get('text-radial-offset').evaluate(feature, {}, canonical) * ONE_EM;\n textOffset1 = INVALID_TEXT_OFFSET;\n }\n\n if (bucket.allowVerticalPlacement && shapedTextOrientations.vertical) {\n const verticalShaping = shapedTextOrientations.vertical;\n if (textAlongLine) {\n verticalTextCircle = evaluateCircleCollisionFeature(verticalShaping);\n if (verticallyShapedIcon) {\n verticalIconCircle = evaluateCircleCollisionFeature(verticallyShapedIcon);\n }\n } else {\n const textRotation = layer.layout.get('text-rotate').evaluate(feature, {}, canonical);\n const verticalTextRotation = textRotation + 90.0;\n verticalTextBoxIndex = evaluateBoxCollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticalShaping, textBoxScale, textPadding, verticalTextRotation);\n if (verticallyShapedIcon) {\n verticalIconBoxIndex = evaluateBoxCollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, verticallyShapedIcon, iconBoxScale, iconPadding, verticalTextRotation);\n }\n }\n }\n\n //Place icon first, so text can have a reference to its index in the placed symbol array.\n //Text symbols can lazily shift at render-time because of variable anchor placement.\n //If the style specifies an `icon-text-fit` then the icon would have to shift along with it.\n // For more info check `updateVariableAnchors` in `draw_symbol.js` .\n if (shapedIcon) {\n const iconRotate = layer.layout.get('icon-rotate').evaluate(feature, {}, canonical);\n const hasIconTextFit = layer.layout.get('icon-text-fit') !== 'none';\n const iconQuads = getIconQuads(shapedIcon, iconRotate, isSDFIcon, hasIconTextFit);\n const verticalIconQuads = verticallyShapedIcon ? getIconQuads(verticallyShapedIcon, iconRotate, isSDFIcon, hasIconTextFit) : undefined;\n iconBoxIndex = evaluateBoxCollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shapedIcon, iconBoxScale, iconPadding, iconRotate);\n numIconVertices = iconQuads.length * 4;\n\n const sizeData = bucket.iconSizeData;\n let iconSizeData = null;\n\n if (sizeData.kind === 'source') {\n iconSizeData = [\n SIZE_PACK_FACTOR * layer.layout.get('icon-size').evaluate(feature, {}, canonical)\n ];\n if (iconSizeData[0] > MAX_PACKED_SIZE) {\n warnOnce(`${bucket.layerIds[0]}: Value for \"icon-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"icon-size\".`);\n }\n } else if (sizeData.kind === 'composite') {\n iconSizeData = [\n SIZE_PACK_FACTOR * sizes.compositeIconSizes[0].evaluate(feature, {}, canonical),\n SIZE_PACK_FACTOR * sizes.compositeIconSizes[1].evaluate(feature, {}, canonical)\n ];\n if (iconSizeData[0] > MAX_PACKED_SIZE || iconSizeData[1] > MAX_PACKED_SIZE) {\n warnOnce(`${bucket.layerIds[0]}: Value for \"icon-size\" is >= ${MAX_GLYPH_ICON_SIZE}. Reduce your \"icon-size\".`);\n }\n }\n\n bucket.addSymbols(\n bucket.icon,\n iconQuads,\n iconSizeData,\n iconOffset,\n iconAlongLine,\n feature,\n false,\n 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 (!textBoxIndex) {\n key = murmur3(shaping.text);\n // As a collision approximation, we can use either the vertical or any of the horizontal versions of the feature\n // We're counting on all versions having similar dimensions\n if (textAlongLine) {\n textCircle = evaluateCircleCollisionFeature(shaping);\n } else {\n const textRotate = layer.layout.get('text-rotate').evaluate(feature, {}, canonical);\n textBoxIndex = evaluateBoxCollisionFeature(collisionBoxArray, anchor, featureIndex, sourceLayerIndex, bucketIndex, shaping, textBoxScale, textPadding, textRotate);\n }\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 // Check if runtime collision circles should be used for any of the collision features.\n // It is enough to choose the tallest feature shape as circles are always placed on a line.\n // All measurements are in glyph metrics and later converted into pixels using proper font size \"layoutTextSize\"\n let collisionCircleDiameter = -1;\n\n const getCollisionCircleHeight = (diameter: ?number, prevHeight: number): number => {\n return diameter ? Math.max(diameter, prevHeight) : prevHeight;\n };\n\n collisionCircleDiameter = getCollisionCircleHeight(textCircle, collisionCircleDiameter);\n collisionCircleDiameter = getCollisionCircleHeight(verticalTextCircle, collisionCircleDiameter);\n collisionCircleDiameter = getCollisionCircleHeight(verticalIconCircle, collisionCircleDiameter);\n const useRuntimeCollisionCircles = (collisionCircleDiameter > -1) ? 1 : 0;\n\n // 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 textBoxIndex !== undefined ? textBoxIndex : bucket.collisionBoxArray.length,\n textBoxIndex !== undefined ? textBoxIndex + 1 : bucket.collisionBoxArray.length,\n verticalTextBoxIndex !== undefined ? verticalTextBoxIndex : bucket.collisionBoxArray.length,\n verticalTextBoxIndex !== undefined ? verticalTextBoxIndex + 1 : bucket.collisionBoxArray.length,\n iconBoxIndex !== undefined ? iconBoxIndex : bucket.collisionBoxArray.length,\n iconBoxIndex !== undefined ? iconBoxIndex + 1 : bucket.collisionBoxArray.length,\n verticalIconBoxIndex ? verticalIconBoxIndex : bucket.collisionBoxArray.length,\n verticalIconBoxIndex ? verticalIconBoxIndex + 1 : bucket.collisionBoxArray.length,\n featureIndex,\n numHorizontalGlyphVertices,\n numVerticalGlyphVertices,\n numIconVertices,\n numVerticalIconVertices,\n useRuntimeCollisionCircles,\n 0,\n 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 collisionVertexAttributesExt,\n collisionBoxLayout,\n dynamicLayoutAttributes\n} from './symbol_attributes';\n\nimport {SymbolLayoutArray,\n SymbolDynamicLayoutArray,\n SymbolOpacityArray,\n CollisionBoxLayoutArray,\n CollisionVertexExtArray,\n CollisionVertexArray,\n PlacedSymbolArray,\n SymbolInstanceArray,\n GlyphOffsetArray,\n SymbolLineVertexArray\n} from '../array_types';\n\nimport ONE_EM from '../../symbol/one_em';\nimport * as symbolSize from '../../symbol/symbol_size';\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 padding: number;\n anchorPointX: number;\n anchorPointY: number;\n elevation?: 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<Array<Point>>,\n properties: Object,\n type: 'Point' | 'LineString' | 'Polygon',\n id?: any\n|};\n\nexport type SortKeyRange = {\n sortKey: number,\n symbolInstanceStart: number,\n symbolInstanceEnd: number\n};\n\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<SymbolStyleLayer>;\n segments: SegmentVector;\n\n dynamicLayoutVertexArray: SymbolDynamicLayoutArray;\n dynamicLayoutVertexBuffer: VertexBuffer;\n\n opacityVertexArray: SymbolOpacityArray;\n opacityVertexBuffer: VertexBuffer;\n\n placedSymbolArray: PlacedSymbolArray;\n\n constructor(programConfigurations: ProgramConfigurationSet<SymbolStyleLayer>) {\n this.layoutVertexArray = new SymbolLayoutArray();\n this.indexArray = new TriangleIndexArray();\n this.programConfigurations = programConfigurations;\n this.segments = new SegmentVector();\n this.dynamicLayoutVertexArray = new SymbolDynamicLayoutArray();\n this.opacityVertexArray = new SymbolOpacityArray();\n this.placedSymbolArray = new PlacedSymbolArray();\n }\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<StructArrayMember>;\n layoutVertexBuffer: VertexBuffer;\n\n indexArray: TriangleIndexArray | LineIndexArray;\n indexBuffer: IndexBuffer;\n\n segments: SegmentVector;\n\n collisionVertexArray: CollisionVertexArray;\n collisionVertexBuffer: VertexBuffer;\n\n collisionVertexArrayExt: CollisionVertexExtArray;\n collisionVertexBufferExt: VertexBuffer;\n\n constructor(LayoutArray: Class<StructArray>,\n layoutAttributes: Array<StructArrayMember>,\n IndexArray: Class<TriangleIndexArray | LineIndexArray>) {\n this.layoutVertexArray = new LayoutArray();\n this.layoutAttributes = layoutAttributes;\n this.indexArray = new IndexArray();\n this.segments = new SegmentVector();\n this.collisionVertexArray = new CollisionVertexArray();\n this.collisionVertexArrayExt = new CollisionVertexExtArray();\n }\n\n upload(context: Context) {\n this.layoutVertexBuffer = context.createVertexBuffer(this.layoutVertexArray, this.layoutAttributes);\n this.indexBuffer = context.createIndexBuffer(this.indexArray);\n this.collisionVertexBuffer = context.createVertexBuffer(this.collisionVertexArray, collisionVertexAttributes.members, true);\n this.collisionVertexBufferExt = context.createVertexBuffer(this.collisionVertexArrayExt, collisionVertexAttributesExt.members, true);\n }\n\n destroy() {\n if (!this.layoutVertexBuffer) return;\n this.layoutVertexBuffer.destroy();\n this.indexBuffer.destroy();\n this.segments.destroy();\n this.collisionVertexBuffer.destroy();\n this.collisionVertexBufferExt.destroy();\n }\n}\n\nregister('CollisionBuffers', CollisionBuffers);\n\n/**\n * Unlike other buckets, which simply implement #addFeature with type-specific\n * logic for (essentially) triangulating feature geometries, SymbolBucket\n * requires specialized behavior:\n *\n * 1. WorkerTile#parse(), the logical owner of the bucket creation process,\n * calls SymbolBucket#populate(), which resolves text and icon tokens on\n * each feature, adds each glyphs and symbols needed to the passed-in\n * collections options.glyphDependencies and options.iconDependencies, and\n * stores the feature data for use in subsequent step (this.features).\n *\n * 2. WorkerTile asynchronously requests from the main thread all of the glyphs\n * and icons needed (by this bucket and any others). When glyphs and icons\n * have been received, the WorkerTile creates a CollisionIndex and invokes:\n *\n * 3. performSymbolLayout(bucket, stacks, icons) perform texts shaping and\n * layout on a Symbol Bucket. This step populates:\n * `this.symbolInstances`: metadata on generated symbols\n * `collisionBoxArray`: collision data for use by foreground\n * `this.text`: SymbolBuffers for text symbols\n * `this.icons`: SymbolBuffers for icons\n * `this.iconCollisionBox`: Debug SymbolBuffers for icon collision boxes\n * `this.textCollisionBox`: Debug SymbolBuffers for text collision boxes\n * The results are sent to the foreground for rendering\n *\n * 4. 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<SymbolStyleLayer>;\n layerIds: Array<string>;\n stateDependentLayers: Array<SymbolStyleLayer>;\n stateDependentLayerIds: Array<string>;\n\n index: number;\n sdfIcons: boolean;\n iconsInText: boolean;\n iconsNeedLinear: boolean;\n bucketInstanceId: number;\n justReloaded: boolean;\n hasPattern: boolean;\n\n textSizeData: SizeData;\n iconSizeData: SizeData;\n\n glyphOffsetArray: GlyphOffsetArray;\n lineVertexArray: SymbolLineVertexArray;\n features: Array<SymbolFeature>;\n symbolInstances: SymbolInstanceArray;\n collisionArrays: Array<CollisionArrays>;\n sortKeyRanges: Array<SortKeyRange>;\n pixelRatio: number;\n tilePixelRatio: number;\n compareText: {[_: string]: Array<Point>};\n fadeStartTime: number;\n sortFeaturesByKey: boolean;\n sortFeaturesByY: boolean;\n canOverlap: boolean;\n sortedAngle: number;\n featureSortOrder: Array<number>;\n\n collisionCircleArray: Array<number>;\n placementInvProjMatrix: mat4;\n placementViewportMatrix: mat4;\n\n text: SymbolBuffers;\n icon: SymbolBuffers;\n textCollisionBox: CollisionBuffers;\n iconCollisionBox: CollisionBuffers;\n uploaded: boolean;\n sourceLayerIndex: number;\n sourceID: string;\n symbolInstanceIndexes: Array<number>;\n writingModes: Array<number>;\n allowVerticalPlacement: boolean;\n hasRTLText: boolean;\n\n constructor(options: BucketParameters<SymbolStyleLayer>) {\n this.collisionBoxArray = options.collisionBoxArray;\n this.zoom = options.zoom;\n this.overscaling = options.overscaling;\n this.layers = options.layers;\n this.layerIds = this.layers.map(layer => layer.id);\n this.index = options.index;\n this.pixelRatio = options.pixelRatio;\n this.sourceLayerIndex = options.sourceLayerIndex;\n this.hasPattern = false;\n this.hasRTLText = false;\n this.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<IndexedFeature>, 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<SymbolQuad>,\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 _commitLayoutVertex(array: StructArray, point: Point, anchorX: number, anchorY: number, extrude: Point) {\n array.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(box: CollisionBox, scale: number, arrays: CollisionBuffers, boxAnchorPoint: Point, symbolInstance: SymbolInstance) {\n const segment = arrays.segments.prepareSegment(4, arrays.layoutVertexArray, arrays.indexArray);\n const index = segment.vertexLength;\n const anchorX = symbolInstance.anchorX;\n const anchorY = symbolInstance.anchorY;\n\n for (let i = 0; i < 4; i++) {\n arrays.collisionVertexArray.emplaceBack(0, 0, 0, 0);\n }\n\n arrays.collisionVertexArrayExt.emplaceBack(scale, -box.padding, -box.padding);\n arrays.collisionVertexArrayExt.emplaceBack(scale, box.padding, -box.padding);\n arrays.collisionVertexArrayExt.emplaceBack(scale, box.padding, box.padding);\n arrays.collisionVertexArrayExt.emplaceBack(scale, -box.padding, box.padding);\n\n this._commitLayoutVertex(arrays.layoutVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(box.x1, box.y1));\n this._commitLayoutVertex(arrays.layoutVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(box.x2, box.y1));\n this._commitLayoutVertex(arrays.layoutVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(box.x2, box.y2));\n this._commitLayoutVertex(arrays.layoutVertexArray, boxAnchorPoint, anchorX, anchorY, new Point(box.x1, box.y2));\n\n segment.vertexLength += 4;\n\n const indexArray: LineIndexArray = (arrays.indexArray: any);\n indexArray.emplaceBack(index, index + 1);\n indexArray.emplaceBack(index + 1, index + 2);\n indexArray.emplaceBack(index + 2, index + 3);\n indexArray.emplaceBack(index + 3, index);\n\n segment.primitiveLength += 4;\n }\n\n _addTextDebugCollisionBoxes(size: any, zoom: number, collisionBoxArray: CollisionBoxArray, startIndex: number, endIndex: number, instance: SymbolInstance) {\n for (let b = startIndex; b < endIndex; b++) {\n const box: CollisionBox = (collisionBoxArray.get(b): any);\n const scale = this.getSymbolInstanceTextSize(size, instance, zoom, b);\n\n this._addCollisionDebugVertices(box, scale, this.textCollisionBox, box.anchorPoint, instance);\n }\n }\n\n _addIconDebugCollisionBoxes(size: any, zoom: number, collisionBoxArray: CollisionBoxArray, startIndex: number, endIndex: number, instance: SymbolInstance) {\n for (let b = startIndex; b < endIndex; b++) {\n const box: CollisionBox = (collisionBoxArray.get(b): any);\n const scale = this.getSymbolInstanceIconSize(size, zoom, b);\n\n this._addCollisionDebugVertices(box, scale, this.iconCollisionBox, box.anchorPoint, instance);\n }\n }\n\n generateCollisionDebugBuffers(zoom: number, collisionBoxArray: CollisionBoxArray) {\n if (this.hasDebugData()) {\n this.destroyDebugData();\n }\n\n this.textCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray);\n this.iconCollisionBox = new CollisionBuffers(CollisionBoxLayoutArray, collisionBoxLayout.members, LineIndexArray);\n\n const iconSize = symbolSize.evaluateSizeForZoom(this.iconSizeData, zoom);\n const textSize = symbolSize.evaluateSizeForZoom(this.textSizeData, zoom);\n\n for (let i = 0; i < this.symbolInstances.length; i++) {\n const symbolInstance = this.symbolInstances.get(i);\n this._addTextDebugCollisionBoxes(textSize, zoom, collisionBoxArray, symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance);\n this._addTextDebugCollisionBoxes(textSize, zoom, collisionBoxArray, symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance);\n this._addIconDebugCollisionBoxes(iconSize, zoom, collisionBoxArray, symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex, symbolInstance);\n this._addIconDebugCollisionBoxes(iconSize, zoom, collisionBoxArray, symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex, symbolInstance);\n }\n }\n\n getSymbolInstanceTextSize(textSize: any, instance: SymbolInstance, zoom: number, boxIndex: number) {\n const symbolIndex = instance.rightJustifiedTextSymbolIndex >= 0 ?\n instance.rightJustifiedTextSymbolIndex : instance.centerJustifiedTextSymbolIndex >= 0 ?\n instance.centerJustifiedTextSymbolIndex : instance.leftJustifiedTextSymbolIndex >= 0 ?\n instance.leftJustifiedTextSymbolIndex : instance.verticalPlacedTextSymbolIndex >= 0 ?\n instance.verticalPlacedTextSymbolIndex : boxIndex;\n\n const symbol: any = this.text.placedSymbolArray.get(symbolIndex);\n const featureSize = symbolSize.evaluateSizeForFeature(this.textSizeData, textSize, symbol) / ONE_EM;\n\n return this.tilePixelRatio * featureSize;\n }\n\n getSymbolInstanceIconSize(iconSize: any, zoom: number, index: number) {\n const symbol: any = this.icon.placedSymbolArray.get(index);\n const featureSize = symbolSize.evaluateSizeForFeature(this.iconSizeData, iconSize, symbol);\n\n return this.tilePixelRatio * featureSize;\n }\n\n _commitDebugCollisionVertexUpdate(array: StructArray, scale: number, padding: number) {\n array.emplaceBack(scale, -padding, -padding);\n array.emplaceBack(scale, padding, -padding);\n array.emplaceBack(scale, padding, padding);\n array.emplaceBack(scale, -padding, padding);\n }\n\n _updateTextDebugCollisionBoxes(size: any, zoom: number, collisionBoxArray: CollisionBoxArray, startIndex: number, endIndex: number, instance: SymbolInstance) {\n for (let b = startIndex; b < endIndex; b++) {\n const box: CollisionBox = (collisionBoxArray.get(b): any);\n const scale = this.getSymbolInstanceTextSize(size, instance, zoom, b);\n const array = this.textCollisionBox.collisionVertexArrayExt;\n this._commitDebugCollisionVertexUpdate(array, scale, box.padding);\n }\n }\n\n _updateIconDebugCollisionBoxes(size: any, zoom: number, collisionBoxArray: CollisionBoxArray, startIndex: number, endIndex: number) {\n for (let b = startIndex; b < endIndex; b++) {\n const box: CollisionBox = (collisionBoxArray.get(b): any);\n const scale = this.getSymbolInstanceIconSize(size, zoom, b);\n const array = this.iconCollisionBox.collisionVertexArrayExt;\n this._commitDebugCollisionVertexUpdate(array, scale, box.padding);\n }\n }\n\n updateCollisionDebugBuffers(zoom: number, collisionBoxArray: CollisionBoxArray) {\n if (!this.hasDebugData()) {\n return;\n }\n\n if (this.hasTextCollisionBoxData()) this.textCollisionBox.collisionVertexArrayExt.clear();\n if (this.hasIconCollisionBoxData()) this.iconCollisionBox.collisionVertexArrayExt.clear();\n\n const iconSize = symbolSize.evaluateSizeForZoom(this.iconSizeData, zoom);\n const textSize = symbolSize.evaluateSizeForZoom(this.textSizeData, zoom);\n\n for (let i = 0; i < this.symbolInstances.length; i++) {\n const symbolInstance = this.symbolInstances.get(i);\n this._updateTextDebugCollisionBoxes(textSize, zoom, collisionBoxArray, symbolInstance.textBoxStartIndex, symbolInstance.textBoxEndIndex, symbolInstance);\n this._updateTextDebugCollisionBoxes(textSize, zoom, collisionBoxArray, symbolInstance.verticalTextBoxStartIndex, symbolInstance.verticalTextBoxEndIndex, symbolInstance);\n this._updateIconDebugCollisionBoxes(iconSize, zoom, collisionBoxArray, symbolInstance.iconBoxStartIndex, symbolInstance.iconBoxEndIndex);\n this._updateIconDebugCollisionBoxes(iconSize, zoom, collisionBoxArray, symbolInstance.verticalIconBoxStartIndex, symbolInstance.verticalIconBoxEndIndex);\n }\n\n if (this.hasTextCollisionBoxData() && this.textCollisionBox.collisionVertexBufferExt) {\n this.textCollisionBox.collisionVertexBufferExt.updateData(this.textCollisionBox.collisionVertexArrayExt);\n }\n if (this.hasIconCollisionBoxData() && this.iconCollisionBox.collisionVertexBufferExt) {\n this.iconCollisionBox.collisionVertexBufferExt.updateData(this.iconCollisionBox.collisionVertexArrayExt);\n }\n }\n\n // These flat arrays are meant to be quicker to iterate over than the source\n // CollisionBoxArray\n _deserializeCollisionBoxesForSymbol(collisionBoxArray: CollisionBoxArray,\n textStartIndex: number, textEndIndex: number,\n verticalTextStartIndex: number, verticalTextEndIndex: number,\n iconStartIndex: number, iconEndIndex: number,\n verticalIconStartIndex: number, verticalIconEndIndex: number): CollisionArrays {\n\n 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, padding: box.padding, 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, padding: box.padding, 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, padding: box.padding, 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, padding: box.padding, 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<SymbolFeature>): Array<SymbolFeature> {\n const leftIndex: {[_: string]: number} = {};\n const rightIndex: {[_: string]: number} = {};\n const mergedFeatures = [];\n let mergedIndex = 0;\n\n function add(k) {\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<number>,\n \"symbol-avoid-edges\": DataConstantProperty<boolean>,\n \"symbol-sort-key\": DataDrivenProperty<number>,\n \"symbol-z-order\": DataConstantProperty<\"auto\" | \"viewport-y\" | \"source\">,\n \"icon-allow-overlap\": DataConstantProperty<boolean>,\n \"icon-ignore-placement\": DataConstantProperty<boolean>,\n \"icon-optional\": DataConstantProperty<boolean>,\n \"icon-rotation-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"auto\">,\n \"icon-size\": DataDrivenProperty<number>,\n \"icon-text-fit\": DataConstantProperty<\"none\" | \"width\" | \"height\" | \"both\">,\n \"icon-text-fit-padding\": DataConstantProperty<[number, number, number, number]>,\n \"icon-image\": DataDrivenProperty<ResolvedImage>,\n \"icon-rotate\": DataDrivenProperty<number>,\n \"icon-padding\": DataConstantProperty<number>,\n \"icon-keep-upright\": DataConstantProperty<boolean>,\n \"icon-offset\": DataDrivenProperty<[number, number]>,\n \"icon-anchor\": DataDrivenProperty<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n \"icon-pitch-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"auto\">,\n \"text-pitch-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"auto\">,\n \"text-rotation-alignment\": DataConstantProperty<\"map\" | \"viewport\" | \"auto\">,\n \"text-field\": DataDrivenProperty<Formatted>,\n \"text-font\": DataDrivenProperty<Array<string>>,\n \"text-size\": DataDrivenProperty<number>,\n \"text-max-width\": DataDrivenProperty<number>,\n \"text-line-height\": DataConstantProperty<number>,\n \"text-letter-spacing\": DataDrivenProperty<number>,\n \"text-justify\": DataDrivenProperty<\"auto\" | \"left\" | \"center\" | \"right\">,\n \"text-radial-offset\": DataDrivenProperty<number>,\n \"text-variable-anchor\": DataConstantProperty<Array<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">>,\n \"text-anchor\": DataDrivenProperty<\"center\" | \"left\" | \"right\" | \"top\" | \"bottom\" | \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\">,\n \"text-max-angle\": DataConstantProperty<number>,\n \"text-writing-mode\": DataConstantProperty<Array<\"horizontal\" | \"vertical\">>,\n \"text-rotate\": DataDrivenProperty<number>,\n \"text-padding\": DataConstantProperty<number>,\n \"text-keep-upright\": DataConstantProperty<boolean>,\n \"text-transform\": DataDrivenProperty<\"none\" | \"uppercase\" | \"lowercase\">,\n \"text-offset\": DataDrivenProperty<[number, number]>,\n \"text-allow-overlap\": DataConstantProperty<boolean>,\n \"text-ignore-placement\": DataConstantProperty<boolean>,\n \"text-optional\": DataConstantProperty<boolean>,\n|};\n\nconst layout: Properties<LayoutProps> = new Properties({\n \"symbol-placement\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-placement\"]),\n \"symbol-spacing\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-spacing\"]),\n \"symbol-avoid-edges\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-avoid-edges\"]),\n \"symbol-sort-key\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"symbol-sort-key\"]),\n \"symbol-z-order\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"symbol-z-order\"]),\n \"icon-allow-overlap\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-allow-overlap\"]),\n \"icon-ignore-placement\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-ignore-placement\"]),\n \"icon-optional\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-optional\"]),\n \"icon-rotation-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-rotation-alignment\"]),\n \"icon-size\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-size\"]),\n \"icon-text-fit\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-text-fit\"]),\n \"icon-text-fit-padding\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-text-fit-padding\"]),\n \"icon-image\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-image\"]),\n \"icon-rotate\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-rotate\"]),\n \"icon-padding\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-padding\"]),\n \"icon-keep-upright\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-keep-upright\"]),\n \"icon-offset\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-offset\"]),\n \"icon-anchor\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"icon-anchor\"]),\n \"icon-pitch-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"icon-pitch-alignment\"]),\n \"text-pitch-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-pitch-alignment\"]),\n \"text-rotation-alignment\": new DataConstantProperty(styleSpec[\"layout_symbol\"][\"text-rotation-alignment\"]),\n \"text-field\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-field\"]),\n \"text-font\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-font\"]),\n \"text-size\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-size\"]),\n \"text-max-width\": new DataDrivenProperty(styleSpec[\"layout_symbol\"][\"text-max-width\"]),\n \"text-line-height\": new 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<number>,\n \"icon-color\": DataDrivenProperty<Color>,\n \"icon-halo-color\": DataDrivenProperty<Color>,\n \"icon-halo-width\": DataDrivenProperty<number>,\n \"icon-halo-blur\": DataDrivenProperty<number>,\n \"icon-translate\": DataConstantProperty<[number, number]>,\n \"icon-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"text-opacity\": DataDrivenProperty<number>,\n \"text-color\": DataDrivenProperty<Color>,\n \"text-halo-color\": DataDrivenProperty<Color>,\n \"text-halo-width\": DataDrivenProperty<number>,\n \"text-halo-blur\": DataDrivenProperty<number>,\n \"text-translate\": DataConstantProperty<[number, number]>,\n \"text-translate-anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"icon-opacity\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-opacity\"]),\n \"icon-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-color\"]),\n \"icon-halo-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-color\"]),\n \"icon-halo-width\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-width\"]),\n \"icon-halo-blur\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"icon-halo-blur\"]),\n \"icon-translate\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"icon-translate\"]),\n \"icon-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"icon-translate-anchor\"]),\n \"text-opacity\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-opacity\"]),\n \"text-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-color\"], { runtimeType: ColorType, getOverride: (o) => o.textColor, hasOverride: (o) => !!o.textColor }),\n \"text-halo-color\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-color\"]),\n \"text-halo-width\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-width\"]),\n \"text-halo-blur\": new DataDrivenProperty(styleSpec[\"paint_symbol\"][\"text-halo-blur\"]),\n \"text-translate\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"text-translate\"]),\n \"text-translate-anchor\": new DataConstantProperty(styleSpec[\"paint_symbol\"][\"text-translate-anchor\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint, layout }: $Exact<{\n paint: Properties<PaintProps>, layout: Properties<LayoutProps>\n}>);\n","// @flow\n\nimport assert from 'assert';\nimport type {Expression} from '../style-spec/expression/expression';\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<T> implements Expression {\n type: Type;\n defaultValue: PossiblyEvaluatedPropertyValue<T>;\n\n constructor(defaultValue: PossiblyEvaluatedPropertyValue<T>) {\n assert(defaultValue.property.overrides !== undefined);\n this.type = defaultValue.property.overrides ? defaultValue.property.overrides.runtimeType : NullType;\n this.defaultValue = defaultValue;\n }\n\n evaluate(ctx: EvaluationContext) {\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';\nimport ProgramConfiguration from '../../data/program_configuration';\n\nclass SymbolStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout<LayoutProps>;\n layout: PossiblyEvaluated<LayoutProps>;\n\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n recalculate(parameters: EvaluationParameters, availableImages: Array<string>) {\n super.recalculate(parameters, availableImages);\n\n if (this.layout.get('icon-rotation-alignment') === 'auto') {\n if (this.layout.get('symbol-placement') !== 'point') {\n this.layout._values['icon-rotation-alignment'] = 'map';\n } else {\n this.layout._values['icon-rotation-alignment'] = 'viewport';\n }\n }\n\n if (this.layout.get('text-rotation-alignment') === 'auto') {\n if (this.layout.get('symbol-placement') !== 'point') {\n this.layout._values['text-rotation-alignment'] = 'map';\n } else {\n this.layout._values['text-rotation-alignment'] = 'viewport';\n }\n }\n\n // If unspecified, `*-pitch-alignment` inherits `*-rotation-alignment`\n if (this.layout.get('text-pitch-alignment') === 'auto') {\n this.layout._values['text-pitch-alignment'] = this.layout.get('text-rotation-alignment');\n }\n if (this.layout.get('icon-pitch-alignment') === 'auto') {\n this.layout._values['icon-pitch-alignment'] = this.layout.get('icon-rotation-alignment');\n }\n\n 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<string>) {\n const value = this.layout.get(name).evaluate(feature, {}, canonical, availableImages);\n const unevaluated = this._unevaluatedLayout._values[name];\n if (!unevaluated.isDataDriven() && !isExpression(unevaluated.value) && value) {\n return resolveTokens(feature.properties, value);\n }\n\n return value;\n }\n\n createBucket(parameters: BucketParameters<*>) {\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<T, R>(name: string, oldValue: PropertyValue<T, R>, newValue: PropertyValue<T, R>): boolean {\n if (!this.layout || oldValue.isDataDriven() || newValue.isDataDriven()) {\n return false;\n }\n return SymbolStyleLayer.hasPaintOverride(this.layout, name);\n }\n\n static hasPaintOverride(layout: PossiblyEvaluated<LayoutProps>, propertyName: string): boolean {\n const textField = layout.get('text-field');\n const property = properties.paint.properties[propertyName];\n let hasOverrides = false;\n\n const checkSections = (sections) => {\n for (const section of sections) {\n if (property.overrides && property.overrides.hasOverride(section)) {\n hasOverrides = true;\n return;\n }\n }\n };\n\n if (textField.value.kind === 'constant' && textField.value.value instanceof Formatted) {\n checkSections(textField.value.value.sections);\n } else if (textField.value.kind === 'source') {\n\n const checkExpression = (expression: Expression) => {\n if (hasOverrides) return;\n\n if (expression instanceof Literal && typeOf(expression.value) === FormattedType) {\n const formatted: Formatted = ((expression.value): any);\n checkSections(formatted.sections);\n } else if (expression instanceof FormatExpression) {\n checkSections(expression.sections);\n } else {\n expression.eachChild(checkExpression);\n }\n };\n\n const expr: ZoomConstantExpression<'source'> = ((textField.value): any);\n if (expr._styleExpression) {\n checkExpression(expr._styleExpression.expression);\n }\n }\n\n return hasOverrides;\n }\n\n getProgramConfiguration(zoom: number): ProgramConfiguration {\n return new ProgramConfiguration(this, zoom);\n }\n}\n\nexport default SymbolStyleLayer;\n","// @flow\nexport default resolveTokens;\n\n/**\n * Replace tokens in a string template with values in an object\n *\n * @param properties a key/value relationship between tokens and replacements\n * @param text the template string\n * @returns the template with tokens replaced\n * @private\n */\nfunction resolveTokens(properties: {+[string]: mixed}, text: string): string {\n return text.replace(/{([^{}]+)}/g, (match, key: string) => {\n return key in properties ? String(properties[key]) : '';\n });\n}\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest';\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<Color>,\n \"background-pattern\": CrossFadedProperty<ResolvedImage>,\n \"background-opacity\": DataConstantProperty<number>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"background-color\": new DataConstantProperty(styleSpec[\"paint_background\"][\"background-color\"]),\n \"background-pattern\": new 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<PaintProps>\n}>);\n","// This file is generated. Edit build/generate-style-code.js, then run `yarn run codegen`.\n// @flow\n/* eslint-disable */\n\nimport styleSpec from '../../style-spec/reference/latest';\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<number>,\n \"raster-hue-rotate\": DataConstantProperty<number>,\n \"raster-brightness-min\": DataConstantProperty<number>,\n \"raster-brightness-max\": DataConstantProperty<number>,\n \"raster-saturation\": DataConstantProperty<number>,\n \"raster-contrast\": DataConstantProperty<number>,\n \"raster-resampling\": DataConstantProperty<\"linear\" | \"nearest\">,\n \"raster-fade-duration\": DataConstantProperty<number>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"raster-opacity\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-opacity\"]),\n \"raster-hue-rotate\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-hue-rotate\"]),\n \"raster-brightness-min\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-brightness-min\"]),\n \"raster-brightness-max\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-brightness-max\"]),\n \"raster-saturation\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-saturation\"]),\n \"raster-contrast\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-contrast\"]),\n \"raster-resampling\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-resampling\"]),\n \"raster-fade-duration\": new DataConstantProperty(styleSpec[\"paint_raster\"][\"raster-fade-duration\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint }: $Exact<{\n paint: Properties<PaintProps>\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer';\nimport type Map from '../../ui/map';\nimport assert from 'assert';\n\ntype CustomRenderMethod = (gl: WebGLRenderingContext, matrix: Array<number>) => void;\n\n/**\n * Interface for custom style layers. This is a specification for\n * implementers to model: it is not an exported method or class.\n *\n * Custom layers allow a user to render directly into the map's GL context using the map's camera.\n * These layers can be added between any regular layers using {@link Map#addLayer}.\n *\n * Custom layers must have a unique `id` and must have the `type` of `\"custom\"`.\n * They must implement `render` and may implement `prerender`, `onAdd` and `onRemove`.\n * They can trigger rendering using {@link Map#triggerRepaint}\n * and they should appropriately handle {@link Map.event:webglcontextlost} and\n * {@link Map.event:webglcontextrestored}.\n *\n * The `renderingMode` property controls whether the layer is treated as a `\"2d\"` or `\"3d\"` map layer. Use:\n * - `\"renderingMode\": \"3d\"` to use the depth buffer and share it with other layers\n * - `\"renderingMode\": \"2d\"` to add a layer with no depth. If you need to use the depth buffer for a `\"2d\"` layer you must use an offscreen\n * framebuffer and {@link CustomLayerInterface#prerender}\n *\n * @interface CustomLayerInterface\n * @property {string} id A unique layer id.\n * @property {string} type The layer's type. Must be `\"custom\"`.\n * @property {string} renderingMode Either `\"2d\"` or `\"3d\"`. Defaults to `\"2d\"`.\n * @example\n * // Custom layer implemented as ES6 class\n * class NullIslandLayer {\n * constructor() {\n * this.id = 'null-island';\n * this.type = 'custom';\n * this.renderingMode = '2d';\n * }\n *\n * onAdd(map, gl) {\n * const vertexSource = `\n * uniform mat4 u_matrix;\n * void main() {\n * gl_Position = u_matrix * vec4(0.5, 0.5, 0.0, 1.0);\n * gl_PointSize = 20.0;\n * }`;\n *\n * const fragmentSource = `\n * void main() {\n * gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n * }`;\n *\n * const vertexShader = gl.createShader(gl.VERTEX_SHADER);\n * gl.shaderSource(vertexShader, vertexSource);\n * gl.compileShader(vertexShader);\n * const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);\n * gl.shaderSource(fragmentShader, fragmentSource);\n * gl.compileShader(fragmentShader);\n *\n * this.program = gl.createProgram();\n * gl.attachShader(this.program, vertexShader);\n * gl.attachShader(this.program, fragmentShader);\n * gl.linkProgram(this.program);\n * }\n *\n * render(gl, matrix) {\n * gl.useProgram(this.program);\n * gl.uniformMatrix4fv(gl.getUniformLocation(this.program, \"u_matrix\"), false, matrix);\n * gl.drawArrays(gl.POINTS, 0, 1);\n * }\n * }\n *\n * map.on('load', 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<number>} matrix The map's camera matrix. It projects spherical mercator\n * coordinates to gl coordinates. The mercator coordinate `[0, 0]` represents the\n * top left corner of the mercator world and `[1, 1]` represents the bottom right corner. When\n * the `renderingMode` is `\"3d\"`, the z coordinate is conformal. A box with identical x, y, and z\n * lengths in mercator units would be rendered as a cube. {@link MercatorCoordinate}.fromLngLat\n * can be used to project a `LngLat` to a mercator coordinate.\n */\n\n/**\n * Called during a render frame allowing the layer to draw into the GL context.\n *\n * The layer can assume blending and depth state is set to allow the layer to properly\n * blend and clip other layers. The layer cannot make any other assumptions about the\n * current GL state.\n *\n * If the layer needs to render to a texture, it should implement the `prerender` method\n * to do this and only use the `render` method for drawing directly into the main framebuffer.\n *\n * The blend function is set to `gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`. This expects\n * colors to be provided in premultiplied alpha form where the `r`, `g` and `b` values are already\n * multiplied by the `a` value. If you are unable to provide colors in premultiplied form you\n * may want to change the blend function to\n * `gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA)`.\n *\n * @function\n * @memberof CustomLayerInterface\n * @instance\n * @name render\n * @param {WebGLRenderingContext} gl The map's gl context.\n * @param {Array<number>} matrix The map's camera matrix. It projects spherical mercator\n * coordinates to gl coordinates. The spherical mercator coordinate `[0, 0]` represents the\n * top left corner of the mercator world and `[1, 1]` represents the bottom right corner. When\n * the `renderingMode` is `\"3d\"`, the z coordinate is conformal. A box with identical x, y, and z\n * lengths in mercator units would be rendered as a cube. {@link MercatorCoordinate}.fromLngLat\n * can be used to project a `LngLat` to a mercator coordinate.\n */\nexport type CustomLayerInterface = {\n id: string,\n type: \"custom\",\n renderingMode: \"2d\" | \"3d\",\n render: CustomRenderMethod,\n prerender: ?CustomRenderMethod,\n 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","// 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 \"sky-type\": DataConstantProperty<\"gradient\" | \"atmosphere\">,\n \"sky-atmosphere-sun\": DataConstantProperty<[number, number]>,\n \"sky-atmosphere-sun-intensity\": DataConstantProperty<number>,\n \"sky-gradient-center\": DataConstantProperty<[number, number]>,\n \"sky-gradient-radius\": DataConstantProperty<number>,\n \"sky-gradient\": ColorRampProperty,\n \"sky-atmosphere-halo-color\": DataConstantProperty<Color>,\n \"sky-atmosphere-color\": DataConstantProperty<Color>,\n \"sky-opacity\": DataConstantProperty<number>,\n|};\n\nconst paint: Properties<PaintProps> = new Properties({\n \"sky-type\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-type\"]),\n \"sky-atmosphere-sun\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-atmosphere-sun\"]),\n \"sky-atmosphere-sun-intensity\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-atmosphere-sun-intensity\"]),\n \"sky-gradient-center\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-gradient-center\"]),\n \"sky-gradient-radius\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-gradient-radius\"]),\n \"sky-gradient\": new ColorRampProperty(styleSpec[\"paint_sky\"][\"sky-gradient\"]),\n \"sky-atmosphere-halo-color\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-atmosphere-halo-color\"]),\n \"sky-atmosphere-color\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-atmosphere-color\"]),\n \"sky-opacity\": new DataConstantProperty(styleSpec[\"paint_sky\"][\"sky-opacity\"]),\n});\n\n// Note: without adding the explicit type annotation, Flow infers weaker types\n// for these objects from their use in the constructor to StyleLayer, as\n// {layout?: Properties<...>, paint: Properties<...>}\nexport default ({ paint }: $Exact<{\n paint: Properties<PaintProps>\n}>);\n","// @flow\n\nimport StyleLayer from '../style_layer';\nimport properties from './sky_style_layer_properties';\nimport {Transitionable, Transitioning, PossiblyEvaluated} from '../properties';\nimport {renderColorRamp} from '../../util/color_ramp';\nimport type {PaintProps} from './sky_style_layer_properties';\nimport type Texture from '../../render/texture';\nimport type Painter from '../../render/painter';\nimport type {LayerSpecification} from '../../style-spec/types';\nimport type Framebuffer from '../../gl/framebuffer';\nimport type {RGBAImage} from '../../util/image';\nimport type SkyboxGeometry from '../../render/skybox_geometry';\nimport type {LightPosition} from '../light';\nimport {warnOnce, degToRad} from '../../util/util';\nimport {vec3, quat} from 'gl-matrix';\n\nfunction getCelestialDirection(azimuth: number, altitude: number, leftHanded: boolean): vec3 {\n const up = vec3.fromValues(0, 0, 1);\n const rotation = quat.identity(quat.create());\n\n quat.rotateY(rotation, rotation, leftHanded ? -degToRad(azimuth) + Math.PI : degToRad(azimuth));\n quat.rotateX(rotation, rotation, -degToRad(altitude));\n vec3.transformQuat(up, up, rotation);\n\n return vec3.normalize(up, up);\n}\n\nclass SkyLayer extends StyleLayer {\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n _lightPosition: LightPosition;\n\n skyboxFbo: ?Framebuffer;\n skyboxTexture: ?WebGLTexture;\n _skyboxInvalidated: ?boolean;\n\n colorRamp: RGBAImage;\n colorRampTexture: ?Texture;\n\n skyboxGeometry: SkyboxGeometry;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n this._updateColorRamp();\n }\n\n _handleSpecialPaintPropertyUpdate(name: string) {\n if (name === 'sky-gradient') {\n this._updateColorRamp();\n } else if (name === 'sky-atmosphere-sun' ||\n name === 'sky-atmosphere-halo-color' ||\n name === 'sky-atmosphere-color' ||\n name === 'sky-atmosphere-sun-intensity') {\n this._skyboxInvalidated = true;\n }\n }\n\n _updateColorRamp() {\n const expression = this._transitionablePaint._values['sky-gradient'].value.expression;\n this.colorRamp = renderColorRamp({\n expression,\n evaluationKey: 'skyRadialProgress'\n });\n if (this.colorRampTexture) {\n this.colorRampTexture.destroy();\n this.colorRampTexture = null;\n }\n }\n\n needsSkyboxCapture(painter: Painter) {\n if (!!this._skyboxInvalidated || !this.skyboxTexture || !this.skyboxGeometry) {\n return true;\n }\n if (!this.paint.get('sky-atmosphere-sun')) {\n const lightPosition = painter.style.light.properties.get('position');\n return this._lightPosition.azimuthal !== lightPosition.azimuthal ||\n this._lightPosition.polar !== lightPosition.polar;\n }\n }\n\n getCenter(painter: Painter, leftHanded: boolean) {\n const type = this.paint.get('sky-type');\n if (type === 'atmosphere') {\n const sunPosition = this.paint.get('sky-atmosphere-sun');\n const useLightPosition = !sunPosition;\n const light = painter.style.light;\n const lightPosition = light.properties.get('position');\n\n if (useLightPosition && light.properties.get('anchor') === 'viewport') {\n warnOnce('The sun direction is attached to a light with viewport anchor, lighting may behave unexpectedly.');\n }\n\n return useLightPosition ?\n getCelestialDirection(lightPosition.azimuthal, -lightPosition.polar + 90, leftHanded) :\n getCelestialDirection(sunPosition[0], -sunPosition[1] + 90, leftHanded);\n } else if (type === 'gradient') {\n const direction = this.paint.get('sky-gradient-center');\n return getCelestialDirection(direction[0], -direction[1] + 90, leftHanded);\n }\n }\n\n is3D() {\n return false;\n }\n\n isSky() {\n return true;\n }\n\n markSkyboxValid(painter: Painter) {\n this._skyboxInvalidated = false;\n this._lightPosition = painter.style.light.properties.get('position');\n }\n\n hasOffscreenPass() {\n return true;\n }\n\n getProgramIds(): string[] | null {\n const type = this.paint.get('sky-type');\n if (type === 'atmosphere') {\n return ['skyboxCapture', 'skybox'];\n } else if (type === 'gradient') {\n return ['skyboxGradient'];\n }\n return null;\n }\n}\n\nexport default SkyLayer;\n","// @flow\n\nimport 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 sky from './style_layer/sky_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 sky\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 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';\nimport ProgramConfiguration from '../../data/program_configuration';\n\nclass HeatmapStyleLayer extends StyleLayer {\n\n heatmapFbo: ?Framebuffer;\n colorRamp: RGBAImage;\n colorRampTexture: ?Texture;\n\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n createBucket(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 getProgramIds() {\n return ['heatmap', 'heatmapTexture'];\n }\n\n getProgramConfiguration(zoom: number): ProgramConfiguration {\n return new ProgramConfiguration(this, zoom);\n }\n}\n\nexport default HeatmapStyleLayer;\n","// @flow\n\nimport StyleLayer from '../style_layer';\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';\nimport ProgramConfiguration from '../../data/program_configuration';\n\nclass HillshadeStyleLayer extends StyleLayer {\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n hasOffscreenPass() {\n return this.paint.get('hillshade-exaggeration') !== 0 && this.visibility !== 'none';\n }\n\n getProgramIds() {\n return ['hillshade', 'hillshadePrepare'];\n }\n\n getProgramConfiguration(zoom: number): ProgramConfiguration {\n return new ProgramConfiguration(this, zoom);\n }\n}\n\nexport default HillshadeStyleLayer;\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';\nimport ProgramConfiguration from '../../data/program_configuration';\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';\nimport type {TilespaceQueryGeometry} from '../query_geometry';\n\nclass FillStyleLayer extends StyleLayer {\n _unevaluatedLayout: Layout<LayoutProps>;\n layout: PossiblyEvaluated<LayoutProps>;\n\n _transitionablePaint: Transitionable<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n getProgramIds(): string[] {\n const pattern = this.paint.get('fill-pattern');\n const image = pattern && pattern.constantOr((1: any));\n\n const ids = [image ? 'fillPattern' : 'fill'];\n\n if (this.paint.get('fill-antialias')) {\n ids.push(image && !this.getPaintProperty('fill-outline-color') ? 'fillOutlinePattern' : 'fillOutline');\n }\n\n return ids;\n }\n\n getProgramConfiguration(zoom: number): ProgramConfiguration {\n return new ProgramConfiguration(this, zoom);\n }\n\n recalculate(parameters: EvaluationParameters, availableImages: Array<string>) {\n super.recalculate(parameters, availableImages);\n\n const outlineColor = this.paint._values['fill-outline-color'];\n if (outlineColor.value.kind === 'constant' && outlineColor.value.value === undefined) {\n this.paint._values['fill-outline-color'] = this.paint._values['fill-color'];\n }\n }\n\n createBucket(parameters: BucketParameters<*>) {\n return new FillBucket(parameters);\n }\n\n queryRadius(): number {\n return translateDistance(this.paint.get('fill-translate'));\n }\n\n queryIntersectsFeature(queryGeometry: TilespaceQueryGeometry,\n feature: VectorTileFeature,\n featureState: FeatureState,\n geometry: Array<Array<Point>>,\n zoom: number,\n transform: Transform): boolean {\n if (queryGeometry.queryGeometry.isAboveHorizon) return false;\n\n const translatedPolygon = translate(queryGeometry.tilespaceGeometry,\n this.paint.get('fill-translate'),\n this.paint.get('fill-translate-anchor'),\n transform.angle, queryGeometry.pixelToTileUnitsFactor);\n return polygonIntersectsMultiPolygon(translatedPolygon, geometry);\n }\n\n isTileClipped() {\n return true;\n }\n}\n\nexport default FillStyleLayer;\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<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n getProgramIds() {\n const image = this.paint.get('background-pattern');\n return [image ? 'backgroundPattern' : 'background'];\n }\n}\n\nexport default BackgroundStyleLayer;\n","// @flow\n\nimport StyleLayer from '../style_layer';\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<PaintProps>;\n _transitioningPaint: Transitioning<PaintProps>;\n paint: PossiblyEvaluated<PaintProps>;\n\n constructor(layer: LayerSpecification) {\n super(layer, properties);\n }\n\n getProgramIds() {\n return ['raster'];\n }\n}\n\nexport default RasterStyleLayer;\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<WebGLRenderingContext, 'RGBA'>\n | $PropertyType<WebGLRenderingContext, 'ALPHA'>;\nexport type TextureFilter =\n | $PropertyType<WebGLRenderingContext, 'LINEAR'>\n | $PropertyType<WebGLRenderingContext, 'LINEAR_MIPMAP_NEAREST'>\n | $PropertyType<WebGLRenderingContext, 'NEAREST'>;\nexport type TextureWrap =\n | $PropertyType<WebGLRenderingContext, 'REPEAT'>\n | $PropertyType<WebGLRenderingContext, 'CLAMP_TO_EDGE'>\n | $PropertyType<WebGLRenderingContext, 'MIRRORED_REPEAT'>;\n\ntype EmptyImage = {\n width: number,\n height: number,\n data: null\n}\n\nexport type TextureImage =\n | RGBAImage\n | AlphaImage\n | HTMLImageElement\n | HTMLCanvasElement\n | HTMLVideoElement\n | ImageData\n | EmptyImage\n | ImageBitmap;\n\nclass Texture {\n context: Context;\n size: [number, number];\n texture: WebGLTexture;\n format: TextureFormat;\n filter: ?TextureFilter;\n wrap: ?TextureWrap;\n useMipmap: boolean;\n\n constructor(context: Context, image: TextureImage, format: TextureFormat, options: ?{ premultiply?: boolean, useMipmap?: boolean }) {\n this.context = context;\n this.format = format;\n this.texture = context.gl.createTexture();\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\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 window from '../util/window';\nimport type {RequestParameters} from '../util/ajax';\n\nconst performance = window.performance;\n\nexport type PerformanceMetrics = {\n loadTime: number,\n fullLoadTime: number,\n fps: number,\n percentDroppedFrames: number,\n parseTile: number,\n parseTile1: number,\n parseTile2: number,\n workerTask: number,\n workerInitialization: number,\n workerEvaluateScript: number,\n workerIdle: number,\n workerIdlePercent: number\n};\n\nexport const PerformanceMarkers = {\n create: 'create',\n load: 'load',\n fullLoad: 'fullLoad'\n};\n\nlet lastFrameTime = null;\nlet frameTimes = [];\nconst frameSequences = [frameTimes];\nlet i = 0;\n\n// The max milliseconds we should spend to render a single frame.\n// This value may need to be tweaked. I chose 14 by increasing frame\n// times with busy work and measuring the number of dropped frames.\n// On a page with only a map, more frames started being dropped after\n// going above 14ms. We might want to lower this to leave more room\n// for other work.\nconst CPU_FRAME_BUDGET = 14;\n\nconst framerateTarget = 60;\nconst frameTimeTarget = 1000 / framerateTarget;\n\nexport const PerformanceUtils = {\n mark(marker: $Keys<typeof PerformanceMarkers>) {\n performance.mark(marker);\n },\n measure(name: string, begin?: string, end?: string) {\n performance.measure(name, begin, end);\n },\n beginMeasure(name: string) {\n const mark = name + i++;\n performance.mark(mark);\n return {\n mark,\n name\n };\n },\n endMeasure(m: { name: string, mark: string }) {\n performance.measure(m.name, m.mark);\n },\n frame(timestamp: number, isRenderFrame: boolean) {\n const currTimestamp = timestamp;\n if (lastFrameTime != null) {\n const frameTime = currTimestamp - lastFrameTime;\n frameTimes.push(frameTime);\n }\n\n if (isRenderFrame) {\n lastFrameTime = currTimestamp;\n } else {\n lastFrameTime = null;\n frameTimes = [];\n frameSequences.push(frameTimes);\n }\n },\n clearMetrics() {\n lastFrameTime = null;\n frameTimes = [];\n performance.clearMeasures('loadTime');\n performance.clearMeasures('fullLoadTime');\n\n for (const marker in PerformanceMarkers) {\n performance.clearMarks(PerformanceMarkers[marker]);\n }\n },\n\n getPerformanceMetrics(): PerformanceMetrics {\n const metrics = {};\n\n performance.measure('loadTime', PerformanceMarkers.create, PerformanceMarkers.load);\n performance.measure('fullLoadTime', PerformanceMarkers.create, PerformanceMarkers.fullLoad);\n\n const measures = performance.getEntriesByType('measure');\n for (const measure of measures) {\n metrics[measure.name] = (metrics[measure.name] || 0) + measure.duration;\n }\n\n // We don't have a perfect way of measuring the actual number of dropped frames.\n // The best way of determining when frames happen is the timestamp passed to\n // requestAnimationFrame. In Chrome and Firefox the timestamps are generally\n // multiples of 1000/60ms (+-2ms).\n //\n // The differences between the timestamps vary a lot more in Safari.\n // It's not uncommon to see a 24ms difference followedd by a 8ms difference.\n // I'm not sure, but I think these might not be dropped frames (due to multiple\n // buffering?).\n //\n // For Safari, I think comparing the number of expected frames with the number of actual\n // frames is a more accurate way of measuring dropped frames than comparing\n // individual frame time differences to a target time. In Firefox and Chrome\n // both approaches produce the same result most of the time.\n let droppedFrames = 0;\n let totalFrameTimeSum = 0;\n let totalFrames = 0;\n metrics.jank = 0;\n\n for (const frameTimes of frameSequences) {\n if (!frameTimes.length) continue;\n const frameTimeSum = frameTimes.reduce((prev, curr) => prev + curr, 0);\n const expectedFrames = Math.max(1, Math.round(frameTimeSum / frameTimeTarget));\n droppedFrames += expectedFrames - frameTimes.length;\n totalFrameTimeSum += frameTimeSum;\n totalFrames += frameTimes.length;\n\n // Jank is a change in the frame rate.\n // Count the number of times a frame has a worse rate than the previous frame.\n // A consistent rate does not increase jank even if it is continuosly dropping frames.\n // A one-off frame does not increase jank even if it is really long.\n //\n // This is not that accurate in Safari because the differences between animation frame\n // times is not as close to a multiple of 1000/60ms.\n const roundedTimes = frameTimes.map(frameTime => Math.max(1, Math.round(frameTime / frameTimeTarget)));\n for (let n = 0; n < roundedTimes.length - 1; n++) {\n if (roundedTimes[n + 1] > roundedTimes[n]) {\n metrics.jank++;\n }\n }\n }\n const avgFrameTime = totalFrameTimeSum / totalFrames / 1000;\n metrics.fps = 1 / avgFrameTime;\n metrics.droppedFrames = droppedFrames;\n metrics.percentDroppedFrames = (droppedFrames / (totalFrames + droppedFrames)) * 100;\n\n metrics.cpuFrameBudgetExceeded = 0;\n const renderFrames = performance.getEntriesByName('render');\n for (const renderFrame of renderFrames) {\n metrics.cpuFrameBudgetExceeded += Math.max(0, renderFrame.duration - CPU_FRAME_BUDGET);\n }\n\n return metrics;\n },\n\n getWorkerPerformanceMetrics() {\n return JSON.parse(JSON.stringify({\n timeOrigin: performance.timeOrigin,\n measures: performance.getEntriesByType(\"measure\")\n }));\n }\n};\n\n/**\n * Safe wrapper for the performance resource timing API in web workers with graceful degradation\n *\n * @param {RequestParameters} request\n * @private\n */\nexport class RequestPerformance {\n _marks: {start: string, end: string, measure: string};\n\n constructor (request: RequestParameters) {\n this._marks = {\n start: [request.url, 'start'].join('#'),\n end: [request.url, 'end'].join('#'),\n measure: request.url.toString()\n };\n\n performance.mark(this._marks.start);\n }\n\n finish() {\n performance.mark(this._marks.end);\n let resourceTimingData = performance.getEntriesByName(this._marks.measure);\n\n // fallback if web worker implementation of perf.getEntriesByName returns empty\n if (resourceTimingData.length === 0) {\n performance.measure(this._marks.measure, this._marks.start, this._marks.end);\n resourceTimingData = performance.getEntriesByName(this._marks.measure);\n\n // cleanup\n performance.clearMarks(this._marks.start);\n performance.clearMarks(this._marks.end);\n performance.clearMeasures(this._marks.measure);\n }\n\n return resourceTimingData;\n }\n}\n\nexport default performance;\n","// @flow\n\nimport ThrottledInvoker from './throttled_invoker';\nimport {bindAll, isWorker} from './util';\nimport {PerformanceUtils} from './performance';\n\nclass Scheduler {\n\n tasks: { [number]: any };\n taskQueue: Array<number>;\n invoker: ThrottledInvoker;\n nextId: number;\n\n constructor() {\n this.tasks = {};\n this.taskQueue = [];\n bindAll(['process'], this);\n this.invoker = new ThrottledInvoker(this.process);\n\n this.nextId = 0;\n }\n\n add(fn: () => void, metadata: Object) {\n const id = this.nextId++;\n this.tasks[id] = {fn, metadata, priority: getPriority(metadata), id};\n this.taskQueue.push(id);\n this.invoker.trigger();\n return {\n cancel: () => {\n delete this.tasks[id];\n }\n };\n }\n\n process() {\n const m = isWorker() ? PerformanceUtils.beginMeasure('workerTask') : undefined;\n try {\n this.taskQueue = this.taskQueue.filter(id => !!this.tasks[id]);\n\n if (!this.taskQueue.length) {\n return;\n }\n const id = this.pick();\n if (id === null) return;\n\n const task = this.tasks[id];\n delete this.tasks[id];\n // Schedule another process call if we know there's more to process _before_ invoking the\n // current task. This is necessary so that processing continues even if the current task\n // doesn't execute successfully.\n if (this.taskQueue.length) {\n this.invoker.trigger();\n }\n if (!task) {\n // If the task ID doesn't have associated task data anymore, it was canceled.\n return;\n }\n\n task.fn();\n } finally {\n if (m) PerformanceUtils.endMeasure(m);\n }\n }\n\n pick() {\n let minIndex = null;\n let minPriority = Infinity;\n for (let i = 0; i < this.taskQueue.length; i++) {\n const id = this.taskQueue[i];\n const task = this.tasks[id];\n if (task.priority < minPriority) {\n minPriority = task.priority;\n minIndex = i;\n }\n }\n if (minIndex === null) return null;\n const id = this.taskQueue[minIndex];\n this.taskQueue.splice(minIndex, 1);\n return id;\n }\n\n remove() {\n this.invoker.remove();\n }\n}\n\nfunction getPriority({type, isSymbolTile, zoom}: Object) {\n zoom = zoom || 0;\n if (type === 'message') return 0;\n if (type === 'maybePrepare' && !isSymbolTile) return 100 - zoom;\n if (type === 'parseTile' && !isSymbolTile) return 200 - zoom;\n if (type === 'parseTile' && isSymbolTile) return 300 - zoom;\n if (type === 'maybePrepare' && isSymbolTile) return 400 - zoom;\n return 500;\n}\n\nexport default Scheduler;\n","// @flow\n\nimport 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<Array<number>>} The bounding box represented as an array, consisting of the\n * southwest and northeast coordinates of the bounding represented as arrays of numbers.\n * @example\n * 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<number>} 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: <lng>, lat: <lat>}, an object {lon: <lng>, lat: <lat>}, or an array of [<lng>, <lat>]\");\n }\n}\n\n/**\n * A {@link LngLat} object, an array of two numbers representing longitude and latitude,\n * or an object with `lng` and `lat` or `lon` and `lat` properties.\n *\n * @typedef {LngLat | {lng: number, lat: number} | {lon: number, lat: number} | [number, number]} LngLatLike\n * @example\n * 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","export { getURL, getTileBBox, getMercCoords };\n\n\n/**\n * getURL\n *\n * @param {String} baseUrl Base url of the WMS server\n * @param {String} layer Layer name\n * @param {Number} x Tile coordinate x\n * @param {Number} y Tile coordinate y\n * @param {Number} z Tile zoom\n * @param {Object} [options]\n * @param {String} [options.format='image/png']\n * @param {String} [options.service='WMS']\n * @param {String} [options.version='1.1.1']\n * @param {String} [options.request='GetMap']\n * @param {String} [options.srs='EPSG:3857']\n * @param {Number} [options.width='256']\n * @param {Number} [options.height='256']\n * @returns {String} url\n * @example\n * var baseUrl = 'http://geodata.state.nj.us/imagerywms/Natural2015';\n * var layer = 'Natural2015';\n * var url = whoots.getURL(baseUrl, layer, 154308, 197167, 19);\n */\nfunction getURL(baseUrl, layer, x, y, z, options) {\n options = options || {};\n\n var url = baseUrl + '?' + [\n 'bbox=' + getTileBBox(x, y, z),\n 'format=' + (options.format || 'image/png'),\n 'service=' + (options.service || 'WMS'),\n 'version=' + (options.version || '1.1.1'),\n 'request=' + (options.request || 'GetMap'),\n 'srs=' + (options.srs || 'EPSG:3857'),\n 'width=' + (options.width || 256),\n 'height=' + (options.height || 256),\n 'layers=' + layer\n ].join('&');\n\n return url;\n}\n\n\n/**\n * getTileBBox\n *\n * @param {Number} x Tile coordinate x\n * @param {Number} y Tile coordinate y\n * @param {Number} z Tile zoom\n * @returns {String} String of the bounding box\n */\nfunction getTileBBox(x, y, z) {\n // for Google/OSM tile scheme we need to alter the y\n y = (Math.pow(2, z) - y - 1);\n\n var min = getMercCoords(x * 256, y * 256, z),\n max = getMercCoords((x + 1) * 256, (y + 1) * 256, z);\n\n return min[0] + ',' + min[1] + ',' + max[0] + ',' + max[1];\n}\n\n\n/**\n * getMercCoords\n *\n * @param {Number} x Pixel coordinate x\n * @param {Number} y Pixel coordinate y\n * @param {Number} z Tile zoom\n * @returns {Array} [x, y]\n */\nfunction getMercCoords(x, y, z) {\n var resolution = (2 * Math.PI * 6378137 / 256) / Math.pow(2, z),\n merc_x = (x * resolution - 2 * Math.PI * 6378137 / 2.0),\n merc_y = (y * resolution - 2 * Math.PI * 6378137 / 2.0);\n\n return [merc_x, merc_y];\n}\n","// @flow\n\nimport {getTileBBox} from '@mapbox/whoots-js';\nimport EXTENT from '../data/extent';\nimport Point from '@mapbox/point-geometry';\nimport MercatorCoordinate, {altitudeFromMercatorZ} from '../geo/mercator_coordinate';\nimport {MAX_SAFE_INTEGER} from '../util/util';\nimport assert from 'assert';\nimport {register} from '../util/web_worker_transfer';\nimport {vec3} from 'gl-matrix';\n\nexport class CanonicalTileID {\n z: number;\n x: number;\n y: number;\n key: number;\n\n constructor(z: number, x: number, y: number) {\n assert(z >= 0 && z <= 25);\n assert(x >= 0 && x < Math.pow(2, z));\n assert(y >= 0 && y < Math.pow(2, z));\n this.z = z;\n this.x = x;\n this.y = y;\n this.key = calculateKey(0, z, z, x, y);\n }\n\n equals(id: CanonicalTileID) {\n return this.z === id.z && this.x === id.x && this.y === id.y;\n }\n\n // given a list of urls, choose a url template and return a tile URL\n url(urls: Array<string>, scheme: ?string) {\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 getTileVec3(coord: MercatorCoordinate): vec3 {\n const tilesAtZoom = Math.pow(2, this.z);\n const x = (coord.x * tilesAtZoom - this.x) * EXTENT;\n const y = (coord.y * tilesAtZoom - this.y) * EXTENT;\n return vec3.fromValues(x, y, altitudeFromMercatorZ(coord.z, coord.y));\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: number;\n\n constructor(wrap: number, canonical: CanonicalTileID) {\n this.wrap = wrap;\n this.canonical = canonical;\n this.key = calculateKey(wrap, canonical.z, canonical.z, canonical.x, canonical.y);\n }\n}\n\nexport class OverscaledTileID {\n overscaledZ: number;\n wrap: number;\n canonical: CanonicalTileID;\n key: number;\n 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 = wrap === 0 && overscaledZ === z ? this.canonical.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 = true): number {\n if (this.overscaledZ === targetZ && withWrap) return this.key;\n if (targetZ > this.canonical.z) {\n return calculateKey(this.wrap * +withWrap, targetZ, this.canonical.z, this.canonical.x, this.canonical.y);\n } else {\n const zDifference = this.canonical.z - targetZ;\n return calculateKey(this.wrap * +withWrap, targetZ, targetZ, this.canonical.x >> zDifference, this.canonical.y >> zDifference);\n }\n }\n\n isChildOf(parent: OverscaledTileID) {\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 getTileVec3(coord: MercatorCoordinate) {\n return this.canonical.getTileVec3(new MercatorCoordinate(coord.x - this.wrap, coord.y, coord.z));\n }\n}\n\nfunction calculateKey(wrap: number, overscaledZ: number, z: number, x: number, y: number): number {\n // only use 22 bits for x & y so that the key fits into MAX_SAFE_INTEGER\n const dim = 1 << Math.min(z, 22);\n let xy = dim * (y % dim) + (x % dim);\n\n // zigzag-encode wrap if we have the room for it\n if (wrap && z < 22) {\n const bitsAvailable = 2 * (22 - z);\n xy += dim * dim * ((wrap < 0 ? -2 * wrap - 1 : 2 * wrap) % (1 << bitsAvailable));\n }\n\n // encode z into 5 bits (24 max) and overscaledZ into 4 bits (10 max)\n const key = ((xy * 32) + z) * 16 + (overscaledZ - z);\n assert(key >= 0 && key <= MAX_SAFE_INTEGER);\n\n return key;\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 strict\n\nimport assert from 'assert';\n\nclass DictionaryCoder {\n _stringToNumber: {[_: string]: number };\n _numberToString: Array<string>;\n\n constructor(strings: Array<string>) {\n this._stringToNumber = {};\n this._numberToString = [];\n for (let i = 0; i < strings.length; i++) {\n const string = strings[i];\n this._stringToNumber[string] = i;\n this._numberToString[i] = string;\n }\n }\n\n encode(string: string) {\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 {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 {Debug} from '../util/debug';\nimport toEvaluationFeature from '../data/evaluation_feature';\nimport EvaluationParameters from '../style/evaluation_parameters';\nimport SourceFeatureState from '../source/source_state';\nimport {lazyLoadRTLTextPlugin} from './rtl_text_plugin';\nimport {TileSpaceDebugBuffer} from '../data/debug_viz';\nimport Color from '../style-spec/util/color';\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';\nimport type {TilespaceQueryGeometry} from '../style/query_geometry';\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 tileZoom: 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 isSymbolTile: ?boolean;\n\n neighboringTiles: ?Object;\n dem: ?DEMData;\n aborted: ?boolean;\n needsHillshadePrepare: ?boolean;\n needsDEMTextureUpload: ?boolean;\n request: ?Cancelable;\n texture: any;\n fbo: ?Framebuffer;\n demTexture: ?Texture;\n refreshedUponExpiration: boolean;\n reloadCallback: any;\n resourceTiming: ?Array<PerformanceResourceTiming>;\n queryPadding: number;\n\n symbolFadeHoldUntil: ?number;\n hasSymbolBuckets: boolean;\n hasRTLText: boolean;\n dependencies: Object;\n\n queryGeometryDebugViz: TileSpaceDebugBuffer;\n queryBoundsDebugViz: TileSpaceDebugBuffer;\n /**\n * @param {OverscaledTileID} tileID\n * @param size\n * @private\n */\n constructor(tileID: OverscaledTileID, size: number, tileZoom: number) {\n this.tileID = tileID;\n this.uid = uniqueId();\n this.uses = 0;\n this.tileSize = size;\n this.tileZoom = tileZoom;\n this.buckets = {};\n this.expirationTime = null;\n this.queryPadding = 0;\n this.hasSymbolBuckets = false;\n this.hasRTLText = false;\n this.dependencies = {};\n\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 Debug.run(() => {\n if (this.queryGeometryDebugViz) {\n this.queryGeometryDebugViz.unload();\n delete this.queryGeometryDebugViz;\n }\n if (this.queryBoundsDebugViz) {\n this.queryBoundsDebugViz.unload();\n delete this.queryBoundsDebugViz;\n }\n });\n this.latestFeatureIndex = null;\n this.state = 'unloaded';\n }\n\n getBucket(layer: StyleLayer) {\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 tileResult: TilespaceQueryGeometry,\n params: { filter: FilterSpecification, layers: Array<string>, availableImages: Array<string> },\n transform: Transform,\n pixelPosMatrix: Float32Array,\n visualizeQueryGeometry: boolean): {[_: string]: Array<{ featureIndex: number, feature: GeoJSONFeature }>} {\n Debug.run(() => {\n if (visualizeQueryGeometry) {\n if (!this.queryGeometryDebugViz) {\n this.queryGeometryDebugViz = new TileSpaceDebugBuffer(this.tileSize);\n }\n if (!this.queryBoundsDebugViz) {\n this.queryBoundsDebugViz = new TileSpaceDebugBuffer(this.tileSize, Color.blue);\n }\n\n this.queryGeometryDebugViz.addPoints(tileResult.tilespaceGeometry);\n this.queryBoundsDebugViz.addPoints(tileResult.bufferedTilespaceGeometry);\n }\n });\n\n if (!this.latestFeatureIndex || !this.latestFeatureIndex.rawTileData)\n return {};\n\n return this.latestFeatureIndex.query({\n tileResult,\n pixelPosMatrix,\n transform,\n params\n }, layers, serializedLayers, sourceFeatureState);\n }\n\n querySourceFeatures(result: Array<GeoJSONFeature>, 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<string>) {\n const index = {};\n for (const dep of dependencies) {\n index[dep] = true;\n }\n this.dependencies[namespace] = index;\n }\n\n hasDependency(namespaces: Array<string>, keys: Array<string>) {\n for (const namespace of namespaces) {\n const dependencies = this.dependencies[namespace];\n if (dependencies) {\n for (const key of keys) {\n if (dependencies[key]) {\n return true;\n }\n }\n }\n }\n return false;\n }\n\n clearQueryDebugViz() {\n Debug.run(() => {\n if (this.queryGeometryDebugViz) {\n this.queryGeometryDebugViz.clearPoints();\n }\n if (this.queryBoundsDebugViz) {\n this.queryBoundsDebugViz.clearPoints();\n }\n });\n }\n}\n\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<Layer: TypedStyleLayer> = {\n index: number,\n layers: Array<Layer>,\n zoom: number,\n pixelRatio: number,\n overscaling: number,\n collisionBoxArray: CollisionBoxArray,\n sourceLayerIndex: number,\n sourceID: string,\n enableTerrain: boolean\n}\n\nexport type PopulateParameters = {\n featureIndex: FeatureIndex,\n iconDependencies: {},\n patternDependencies: {},\n glyphDependencies: {},\n availableImages: Array<string>\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<Array<Point>>,\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<string>;\n hasPattern: boolean;\n +layers: Array<any>;\n +stateDependentLayers: Array<any>;\n +stateDependentLayerIds: Array<string>;\n populate(features: Array<IndexedFeature>, options: PopulateParameters, canonical: CanonicalTileID): 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<Bucket>, style: Style): {[_: string]: Bucket} {\n const output = {};\n\n // Guard against the case where the map's style has been set to null while\n // this bucket has been parsing.\n if (!style) return output;\n\n for (const bucket of input) {\n const layers = bucket.layerIds\n .map((id) => style.getLayer(id))\n .filter(Boolean);\n\n if (layers.length === 0) {\n continue;\n }\n\n // look up StyleLayer objects from layer ids (since we don't\n // want to waste time serializing/copying them from the worker)\n (bucket: any).layers = layers;\n if ((bucket: any).stateDependentLayerIds) {\n (bucket: any).stateDependentLayers = (bucket: any).stateDependentLayerIds.map((lId) => layers.filter((l) => l.id === lId)[0]);\n }\n for (const layer of layers) {\n output[layer.id] = bucket;\n }\n }\n\n return output;\n}\n","// @flow\n\nimport {extend} from '../util/util';\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 DEMData from \"./dem_data\";\nimport {vec3} from 'gl-matrix';\nimport {number as interpolate} from '../style-spec/util/interpolate';\nimport {clamp} from '../util/util';\n\ntype vec3Like = vec3 | [number, number, number];\n\nclass MipLevel {\n size: number;\n minimums: Array<number>;\n maximums: Array<number>;\n leaves: Array<number>;\n\n constructor(size_: number) {\n this.size = size_;\n this.minimums = [];\n this.maximums = [];\n this.leaves = [];\n }\n\n getElevation(x: number, y: number): { min: number, max: number} {\n const idx = this.toIdx(x, y);\n return {\n min: this.minimums[idx],\n max: this.maximums[idx]\n };\n }\n\n isLeaf(x: number, y: number): number {\n return this.leaves[this.toIdx(x, y)];\n }\n\n toIdx(x: number, y: number): number {\n return y * this.size + x;\n }\n}\n\nfunction aabbRayIntersect(min: vec3Like, max: vec3Like, pos: vec3Like, dir: vec3Like): ?number {\n let tMin = 0;\n let tMax = Number.MAX_VALUE;\n\n const epsilon = 1e-15;\n\n for (let i = 0; i < 3; i++) {\n if (Math.abs(dir[i]) < epsilon) {\n // Parallel ray\n if (pos[i] < min[i] || pos[i] > max[i])\n return null;\n } else {\n const ood = 1.0 / dir[i];\n let t1 = (min[i] - pos[i]) * ood;\n let t2 = (max[i] - pos[i]) * ood;\n if (t1 > t2) {\n const temp = t1;\n t1 = t2;\n t2 = temp;\n }\n if (t1 > tMin)\n tMin = t1;\n if (t2 < tMax)\n tMax = t2;\n if (tMin > tMax)\n return null;\n }\n }\n\n return tMin;\n}\n\nfunction triangleRayIntersect(ax, ay, az, bx, by, bz, cx, cy, cz, pos: vec3Like, dir: vec3Like): ?number {\n // Compute barycentric coordinates u and v to find the intersection\n const abX = bx - ax;\n const abY = by - ay;\n const abZ = bz - az;\n\n const acX = cx - ax;\n const acY = cy - ay;\n const acZ = cz - az;\n\n // pvec = cross(dir, a), det = dot(ab, pvec)\n const pvecX = dir[1] * acZ - dir[2] * acY;\n const pvecY = dir[2] * acX - dir[0] * acZ;\n const pvecZ = dir[0] * acY - dir[1] * acX;\n const det = abX * pvecX + abY * pvecY + abZ * pvecZ;\n\n if (Math.abs(det) < 1e-15)\n return null;\n\n const invDet = 1.0 / det;\n const tvecX = pos[0] - ax;\n const tvecY = pos[1] - ay;\n const tvecZ = pos[2] - az;\n const u = (tvecX * pvecX + tvecY * pvecY + tvecZ * pvecZ) * invDet;\n\n if (u < 0.0 || u > 1.0)\n return null;\n\n // qvec = cross(tvec, ab)\n const qvecX = tvecY * abZ - tvecZ * abY;\n const qvecY = tvecZ * abX - tvecX * abZ;\n const qvecZ = tvecX * abY - tvecY * abX;\n const v = (dir[0] * qvecX + dir[1] * qvecY + dir[2] * qvecZ) * invDet;\n\n if (v < 0.0 || u + v > 1.0)\n return null;\n\n return (acX * qvecX + acY * qvecY + acZ * qvecZ) * invDet;\n}\n\nfunction frac(v, lo, hi) {\n return (v - lo) / (hi - lo);\n}\n\nfunction decodeBounds(x, y, depth, boundsMinx, boundsMiny, boundsMaxx, boundsMaxy, outMin, outMax) {\n const scale = 1 << depth;\n const rangex = boundsMaxx - boundsMinx;\n const rangey = boundsMaxy - boundsMiny;\n\n const minX = (x + 0) / scale * rangex + boundsMinx;\n const maxX = (x + 1) / scale * rangex + boundsMinx;\n const minY = (y + 0) / scale * rangey + boundsMiny;\n const maxY = (y + 1) / scale * rangey + boundsMiny;\n\n outMin[0] = minX;\n outMin[1] = minY;\n outMax[0] = maxX;\n outMax[1] = maxY;\n}\n\n// A small padding value is used with bounding boxes to extend the bottom below sea level\nconst aabbSkirtPadding = 100;\n\n// A sparse min max quad tree for performing accelerated queries against dem elevation data.\n// Each tree node stores the minimum and maximum elevation of its children nodes and a flag whether the node is a leaf.\n// Node data is stored in non-interleaved arrays where the root is at index 0.\nexport default class DemMinMaxQuadTree {\n maximums: Array<number>;\n minimums: Array<number>;\n leaves: Array<number>;\n childOffsets: Array<number>;\n nodeCount: number;\n dem: DEMData;\n _siblingOffset: Array<Array<number>>;\n\n constructor(dem_: DEMData) {\n this.maximums = [];\n this.minimums = [];\n this.leaves = [];\n this.childOffsets = [];\n this.nodeCount = 0;\n this.dem = dem_;\n\n // Precompute the order of 4 sibling nodes in the memory. Top-left, top-right, bottom-left, bottom-right\n this._siblingOffset = [\n [0, 0],\n [1, 0],\n [0, 1],\n [1, 1]\n ];\n\n if (!this.dem)\n return;\n\n const mips = buildDemMipmap(this.dem);\n const maxLvl = mips.length - 1;\n\n // Create the root node\n const rootMip = mips[maxLvl];\n const min = rootMip.minimums;\n const max = rootMip.maximums;\n const leaves = rootMip.leaves;\n this._addNode(min[0], max[0], leaves[0]);\n\n // Construct the rest of the tree recursively\n this._construct(mips, 0, 0, maxLvl, 0);\n }\n\n // Performs raycast against the tree root only. Min and max coordinates defines the size of the root node\n raycastRoot(minx: number, miny: number, maxx: number, maxy: number, p: vec3Like, d: vec3Like, exaggeration: number = 1): ?number {\n const min = [minx, miny, -aabbSkirtPadding];\n const max = [maxx, maxy, this.maximums[0] * exaggeration];\n return aabbRayIntersect(min, max, p, d);\n }\n\n raycast(rootMinx: number, rootMiny: number, rootMaxx: number, rootMaxy: number, p: vec3Like, d: vec3Like, exaggeration: number = 1): ?number {\n if (!this.nodeCount)\n return null;\n\n const t = this.raycastRoot(rootMinx, rootMiny, rootMaxx, rootMaxy, p, d, exaggeration);\n if (t == null)\n return null;\n\n const tHits = [];\n const sortedHits = [];\n const boundsMin = [];\n const boundsMax = [];\n\n const stack = [{\n idx: 0,\n t,\n nodex: 0,\n nodey: 0,\n depth: 0\n }];\n\n // Traverse the tree until something is hit or the ray escapes\n while (stack.length > 0) {\n const {idx, t, nodex, nodey, depth} = stack.pop();\n\n if (this.leaves[idx]) {\n // Create 2 triangles to approximate the surface plane for more precise tests\n decodeBounds(nodex, nodey, depth, rootMinx, rootMiny, rootMaxx, rootMaxy, boundsMin, boundsMax);\n\n const scale = 1 << depth;\n const minxUv = (nodex + 0) / scale;\n const maxxUv = (nodex + 1) / scale;\n const minyUv = (nodey + 0) / scale;\n const maxyUv = (nodey + 1) / scale;\n\n // 4 corner points A, B, C and D defines the (quad) area covered by this node\n const az = sampleElevation(minxUv, minyUv, this.dem) * exaggeration;\n const bz = sampleElevation(maxxUv, minyUv, this.dem) * exaggeration;\n const cz = sampleElevation(maxxUv, maxyUv, this.dem) * exaggeration;\n const dz = sampleElevation(minxUv, maxyUv, this.dem) * exaggeration;\n\n const t0: any = triangleRayIntersect(\n boundsMin[0], boundsMin[1], az, // A\n boundsMax[0], boundsMin[1], bz, // B\n boundsMax[0], boundsMax[1], cz, // C\n p, d);\n\n const t1: any = triangleRayIntersect(\n boundsMax[0], boundsMax[1], cz,\n boundsMin[0], boundsMax[1], dz,\n boundsMin[0], boundsMin[1], az,\n p, d);\n\n const tMin = Math.min(\n t0 !== null ? t0 : Number.MAX_VALUE,\n t1 !== null ? t1 : Number.MAX_VALUE);\n\n // The ray might go below the two surface triangles but hit one of the sides.\n // This covers the case of skirt geometry between two dem tiles of different zoom level\n if (tMin === Number.MAX_VALUE) {\n const hitPos = vec3.scaleAndAdd([], p, d, t);\n const fracx = frac(hitPos[0], boundsMin[0], boundsMax[0]);\n const fracy = frac(hitPos[1], boundsMin[1], boundsMax[1]);\n\n if (bilinearLerp(az, bz, dz, cz, fracx, fracy) >= hitPos[2])\n return t;\n } else {\n return tMin;\n }\n\n continue;\n }\n\n // Perform intersection tests agains each of the 4 child nodes and store results from closest to furthest.\n let hitCount = 0;\n\n for (let i = 0; i < this._siblingOffset.length; i++) {\n\n const childNodeX = (nodex << 1) + this._siblingOffset[i][0];\n const childNodeY = (nodey << 1) + this._siblingOffset[i][1];\n\n // Decode node aabb from the morton code\n decodeBounds(childNodeX, childNodeY, depth + 1, rootMinx, rootMiny, rootMaxx, rootMaxy, boundsMin, boundsMax);\n\n boundsMin[2] = -aabbSkirtPadding;\n boundsMax[2] = this.maximums[this.childOffsets[idx] + i] * exaggeration;\n\n const result = aabbRayIntersect(boundsMin, boundsMax, p, d);\n if (result != null) {\n // Build the result list from furthest to closest hit.\n // The order will be inversed when building the stack\n const tHit: number = result;\n tHits[i] = tHit;\n\n let added = false;\n for (let j = 0; j < hitCount && !added; j++) {\n if (tHit >= tHits[sortedHits[j]]) {\n sortedHits.splice(j, 0, i);\n added = true;\n }\n }\n if (!added)\n sortedHits[hitCount] = i;\n hitCount++;\n }\n }\n\n // Continue recursion from closest to furthest\n for (let i = 0; i < hitCount; i++) {\n const hitIdx = sortedHits[i];\n stack.push({\n idx: this.childOffsets[idx] + hitIdx,\n t: tHits[hitIdx],\n nodex: (nodex << 1) + this._siblingOffset[hitIdx][0],\n nodey: (nodey << 1) + this._siblingOffset[hitIdx][1],\n depth: depth + 1\n });\n }\n }\n\n return null;\n }\n\n _addNode(min: number, max: number, leaf: number) {\n this.minimums.push(min);\n this.maximums.push(max);\n this.leaves.push(leaf);\n this.childOffsets.push(0);\n return this.nodeCount++;\n }\n\n _construct(mips: Array<MipLevel>, x: number, y: number, lvl: number, parentIdx: number) {\n if (mips[lvl].isLeaf(x, y) === 1) {\n return;\n }\n\n // Update parent offset\n if (!this.childOffsets[parentIdx])\n this.childOffsets[parentIdx] = this.nodeCount;\n\n // Construct all 4 children and place them next to each other in memory\n const childLvl = lvl - 1;\n const childMip = mips[childLvl];\n\n let leafMask = 0;\n let firstNodeIdx;\n\n for (let i = 0; i < this._siblingOffset.length; i++) {\n const childX = x * 2 + this._siblingOffset[i][0];\n const childY = y * 2 + this._siblingOffset[i][1];\n\n const elevation = childMip.getElevation(childX, childY);\n const leaf = childMip.isLeaf(childX, childY);\n const nodeIdx = this._addNode(elevation.min, elevation.max, leaf);\n\n if (leaf)\n leafMask |= 1 << i;\n if (!firstNodeIdx)\n firstNodeIdx = nodeIdx;\n }\n\n // Continue construction of the tree recursively to non-leaf nodes.\n for (let i = 0; i < this._siblingOffset.length; i++) {\n if (!(leafMask & (1 << i))) {\n this._construct(mips, x * 2 + this._siblingOffset[i][0], y * 2 + this._siblingOffset[i][1], childLvl, firstNodeIdx + i);\n }\n }\n }\n}\n\nfunction bilinearLerp(p00: any, p10: any, p01: any, p11: any, x: number, y: number): any {\n return interpolate(\n interpolate(p00, p01, y),\n interpolate(p10, p11, y),\n x);\n}\n\n// Sample elevation in normalized uv-space ([0, 0] is the top left)\n// This function does not account for exaggeration\nexport function sampleElevation(fx: number, fy: number, dem: DEMData): number {\n // Sample position in texels\n const demSize = dem.dim;\n const x = clamp(fx * demSize - 0.5, 0, demSize - 1);\n const y = clamp(fy * demSize - 0.5, 0, demSize - 1);\n\n // Compute 4 corner points for bilinear interpolation\n const ixMin = Math.floor(x);\n const iyMin = Math.floor(y);\n const ixMax = Math.min(ixMin + 1, demSize - 1);\n const iyMax = Math.min(iyMin + 1, demSize - 1);\n\n const e00 = dem.get(ixMin, iyMin);\n const e10 = dem.get(ixMax, iyMin);\n const e01 = dem.get(ixMin, iyMax);\n const e11 = dem.get(ixMax, iyMax);\n\n return bilinearLerp(e00, e10, e01, e11, x - ixMin, y - iyMin);\n}\n\nexport function buildDemMipmap(dem: DEMData): Array<MipLevel> {\n const demSize = dem.dim;\n\n const elevationDiffThreshold = 5;\n const texelSizeOfMip0 = 8;\n const levelCount = Math.ceil(Math.log2(demSize / texelSizeOfMip0));\n const mips: Array<MipLevel> = [];\n\n let blockCount = Math.ceil(Math.pow(2, levelCount));\n const blockSize = 1 / blockCount;\n\n const blockSamples = (x, y, size, exclusive, outBounds) => {\n const padding = exclusive ? 1 : 0;\n const minx = x * size;\n const maxx = (x + 1) * size - padding;\n const miny = y * size;\n const maxy = (y + 1) * size - padding;\n\n outBounds[0] = minx;\n outBounds[1] = miny;\n outBounds[2] = maxx;\n outBounds[3] = maxy;\n };\n\n // The first mip (0) is built by sampling 4 corner points of each 8x8 texel block\n let mip = new MipLevel(blockCount);\n const blockBounds = [];\n\n for (let idx = 0; idx < blockCount * blockCount; idx++) {\n const y = Math.floor(idx / blockCount);\n const x = idx % blockCount;\n\n blockSamples(x, y, blockSize, false, blockBounds);\n\n const e0 = sampleElevation(blockBounds[0], blockBounds[1], dem); // minx, miny\n const e1 = sampleElevation(blockBounds[2], blockBounds[1], dem); // maxx, miny\n const e2 = sampleElevation(blockBounds[2], blockBounds[3], dem); // maxx, maxy\n const e3 = sampleElevation(blockBounds[0], blockBounds[3], dem); // minx, maxy\n\n mip.minimums.push(Math.min(e0, e1, e2, e3));\n mip.maximums.push(Math.max(e0, e1, e2, e3));\n mip.leaves.push(1);\n }\n\n mips.push(mip);\n\n // Construct the rest of the mip levels from bottom to up\n for (blockCount /= 2; blockCount >= 1; blockCount /= 2) {\n const prevMip = mips[mips.length - 1];\n\n mip = new MipLevel(blockCount);\n\n for (let idx = 0; idx < blockCount * blockCount; idx++) {\n const y = Math.floor(idx / blockCount);\n const x = idx % blockCount;\n\n // Sample elevation of all 4 children mip texels. 4 leaf nodes can be concatenated into a single\n // leaf if the total elevation difference is below the threshold value\n blockSamples(x, y, 2, true, blockBounds);\n\n const e0 = prevMip.getElevation(blockBounds[0], blockBounds[1]);\n const e1 = prevMip.getElevation(blockBounds[2], blockBounds[1]);\n const e2 = prevMip.getElevation(blockBounds[2], blockBounds[3]);\n const e3 = prevMip.getElevation(blockBounds[0], blockBounds[3]);\n\n const l0 = prevMip.isLeaf(blockBounds[0], blockBounds[1]);\n const l1 = prevMip.isLeaf(blockBounds[2], blockBounds[1]);\n const l2 = prevMip.isLeaf(blockBounds[2], blockBounds[3]);\n const l3 = prevMip.isLeaf(blockBounds[0], blockBounds[3]);\n\n const minElevation = Math.min(e0.min, e1.min, e2.min, e3.min);\n const maxElevation = Math.max(e0.max, e1.max, e2.max, e3.max);\n const canConcatenate = l0 && l1 && l2 && l3;\n\n mip.maximums.push(maxElevation);\n mip.minimums.push(minElevation);\n\n if (maxElevation - minElevation <= elevationDiffThreshold && canConcatenate) {\n // All samples have uniform elevation. Mark this as a leaf\n mip.leaves.push(1);\n } else {\n mip.leaves.push(0);\n }\n }\n\n mips.push(mip);\n }\n\n return mips;\n}\n","// @flow\nimport {RGBAImage} from '../util/image';\n\nimport {warnOnce, clamp} from '../util/util';\nimport {register} from '../util/web_worker_transfer';\nimport DemMinMaxQuadTree from './dem_tree';\nimport assert from 'assert';\n\n// DEMData is a data structure for decoding, backfilling, and storing elevation data for processing in the hillshade shaders\n// data can be populated either from a pngraw image tile or from serliazed data sent back from a worker. When data is initially\n// loaded from a image tile, we decode the pixel values using the appropriate decoding formula, but we store the\n// elevation data as an Int32 value. we add 65536 (2^16) to eliminate negative values and enable the use of\n// integer overflow when creating the texture used in the hillshadePrepare step.\n\n// DEMData also handles the backfilling of data from a tile's neighboring tiles. This is necessary because we use a pixel's 8\n// surrounding pixel values to compute the slope at that pixel, and we cannot accurately calculate the slope at pixels on a\n// tile's edge without backfilling from neighboring tiles.\n\nexport type DEMEncoding = \"mapbox\" | \"terrarium\";\n\nconst unpackVectors = {\n mapbox: [6553.6, 25.6, 0.1, 10000.0],\n terrarium: [256.0, 1.0, 1.0 / 256.0, 32768.0]\n};\n\nexport default class DEMData {\n uid: number;\n data: Uint32Array;\n stride: number;\n dim: number;\n encoding: DEMEncoding;\n borderReady: boolean;\n _tree: DemMinMaxQuadTree;\n get tree(): DemMinMaxQuadTree {\n if (!this._tree) this._buildQuadTree();\n return this._tree;\n }\n\n // RGBAImage data has uniform 1px padding on all sides: square tile edge size defines stride\n // and dim is calculated as stride - 2.\n constructor(uid: number, data: RGBAImage, encoding: DEMEncoding, borderReady: boolean = false, buildQuadTree: boolean = false) {\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 this.borderReady = borderReady;\n\n if (borderReady) return;\n\n // in order to avoid flashing seams between tiles, here we are initially populating a 1px border of pixels around the image\n // with the data of the nearest pixel from the image. this data is eventually replaced when the tile's neighboring\n // tiles are loaded and the accurate data can be backfilled using DEMData#backfillBorder\n for (let x = 0; x < dim; x++) {\n // left vertical border\n 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 if (buildQuadTree) this._buildQuadTree();\n }\n\n _buildQuadTree() {\n assert(!this._tree);\n // Construct the implicit sparse quad tree by traversing mips from top to down\n this._tree = new DemMinMaxQuadTree(this);\n }\n\n get(x: number, y: number, clampToEdge: boolean = false) {\n const pixels = new Uint8Array(this.data.buffer);\n if (clampToEdge) {\n x = clamp(x, -1, this.dim);\n y = clamp(y, -1, this.dim);\n }\n const index = this._idx(x, y) * 4;\n const unpack = this.encoding === \"terrarium\" ? this._unpackTerrarium : this._unpackMapbox;\n return unpack(pixels[index], pixels[index + 1], pixels[index + 2]);\n }\n\n static getUnpackVector(encoding: DEMEncoding): [number, number, number, number] {\n return unpackVectors[encoding];\n }\n\n get unpackVector(): [number, number, number, number] {\n return unpackVectors[this.encoding];\n }\n\n _idx(x: number, y: number) {\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 static pack(altitude: number, encoding: DEMEncoding): [number, number, number, number] {\n const color = [0, 0, 0, 0];\n const vector = DEMData.getUnpackVector(encoding);\n let v = Math.floor((altitude + vector[3]) / vector[2]);\n color[2] = v % 256;\n v = Math.floor(v / 256);\n color[1] = v % 256;\n v = Math.floor(v / 256);\n color[0] = v;\n return color;\n }\n\n getPixels() {\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 onDeserialize() {\n if (this._tree) this._tree.dem = this;\n }\n}\n\nregister('DEMData', DEMData);\nregister('DemMinMaxQuadTree', DemMinMaxQuadTree, {omit: ['dem']});\n","// @flow\n\nimport {OverscaledTileID} from './tile_id';\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 | number]: Array<{ value: Tile, timeout: ?TimeoutID}>};\n order: Array<number>;\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: number): ?Tile {\n const data = this.data[key].shift();\n if (data.timeout) clearTimeout(data.timeout);\n\n if (this.data[key].length === 0) {\n delete this.data[key];\n }\n this.order.splice(this.order.indexOf(key), 1);\n\n return data.value;\n }\n\n /*\n * Get the value with the specified (wrapped tile) key.\n */\n getByKey(key: number): ?Tile {\n const data = this.data[key];\n return data ? data[0].value : null;\n }\n\n /**\n * Get the value attached to a specific key without removing data\n * from the cache. If the key is not found, returns `null`\n *\n * @param {OverscaledTileID} tileID the key to look up\n * @returns {*} the data, or null if it isn't found\n * @private\n */\n get(tileID: OverscaledTileID): ?Tile {\n if (!this.has(tileID)) { return null; }\n\n const data = this.data[tileID.wrapped().key][0];\n return data.value;\n }\n\n /**\n * Remove a key/value combination from the cache.\n *\n * @param {OverscaledTileID} tileID the key for the pair to delete\n * @param {Tile} value If a value is provided, remove that exact version of the value.\n * @returns {TileCache} this cache\n * @private\n */\n remove(tileID: OverscaledTileID, value: ?{ value: Tile, timeout: ?TimeoutID}) {\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<StructArrayMember>;\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<StructArrayMember>, 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';\nimport assert from 'assert';\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<T> {\n current: T;\n default: T;\n dirty: boolean;\n get(): T;\n setDefault(): void;\n set(value: T): void;\n}\n\nclass BaseValue<T> implements Value<T> {\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<Color> {\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<number> {\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<number> {\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<ColorMaskType> {\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<DepthMaskType> {\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<number> {\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<StencilFuncType> {\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 // Assume UNSIGNED_INT_24_8 storage, with 8 bits dedicated to stencil.\n // Please revise your stencil values if this threshold is triggered.\n assert(v.ref >= 0 && v.ref <= 255);\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<StencilOpType> {\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<boolean> {\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<DepthRangeType> {\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<boolean> {\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<DepthFuncType> {\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<boolean> {\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<BlendFuncType> {\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<Color> {\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<BlendEquationType> {\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<boolean> {\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<CullFaceModeType> {\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<FrontFaceType> {\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<?WebGLProgram> {\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<TextureUnitType> {\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<ViewportType> {\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<?WebGLFramebuffer> {\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<?WebGLRenderbuffer> {\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<?WebGLTexture> {\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<?WebGLBuffer> {\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<?WebGLBuffer> {\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<any> {\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<number> {\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<boolean> {\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<boolean> {\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<T> extends BaseValue<?T> {\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<WebGLTexture> {\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<WebGLRenderbuffer> {\n attachment(): number { return this.gl.DEPTH_ATTACHMENT; }\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, this.attachment(), gl.RENDERBUFFER, v);\n this.current = v;\n this.dirty = false;\n }\n}\n\nexport class DepthStencilAttachment extends DepthAttachment {\n attachment(): number { return this.gl.DEPTH_STENCIL_ATTACHMENT; }\n}\n","// @flow\nimport {ColorAttachment, DepthAttachment} from './value';\n\nimport type Context from './context';\nimport assert from 'assert';\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<DepthMode>;\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<StencilMode>;\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<ColorMode>;\n static unblended: $ReadOnly<ColorMode>;\n static alphaBlended: $ReadOnly<ColorMode>;\n}\n\nColorMode.Replace = [ONE, ZERO];\n\nColorMode.disabled = new ColorMode(ColorMode.Replace, Color.transparent, [false, false, false, false]);\nColorMode.unblended = new ColorMode(ColorMode.Replace, Color.transparent, [true, true, true, true]);\nColorMode.alphaBlended = new ColorMode([ONE, ONE_MINUS_SRC_ALPHA], Color.transparent, [true, true, true, true]);\n\nexport default ColorMode;\n","// @flow\n\nimport type {CullFaceModeType, FrontFaceType} from './types';\n\nconst BACK = 0x0405;\nconst FRONT = 0x0404;\nconst CCW = 0x0901;\nconst CW = 0x0900;\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<CullFaceMode>;\n static backCCW: $ReadOnly<CullFaceMode>;\n static backCW: $ReadOnly<CullFaceMode>;\n static frontCW: $ReadOnly<CullFaceMode>;\n static frontCCW: $ReadOnly<CullFaceMode>;\n}\n\nCullFaceMode.disabled = new CullFaceMode(false, BACK, CCW);\nCullFaceMode.backCCW = new CullFaceMode(true, BACK, CCW);\nCullFaceMode.backCW = new CullFaceMode(true, BACK, CW);\nCullFaceMode.frontCW = new CullFaceMode(true, FRONT, CW);\nCullFaceMode.frontCCW = new CullFaceMode(true, FRONT, CCW);\n\nexport default CullFaceMode;\n","// @flow\n\nimport Tile from './tile';\nimport {Event, ErrorEvent, Evented} from '../util/evented';\nimport TileCache from './tile_cache';\nimport {keysDifference, values} from '../util/util';\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 Transform from '../geo/transform';\nimport type {TileState} from './tile';\nimport type {Callback} from '../types/callback';\nimport type {QueryGeometry, TilespaceQueryGeometry} from '../style/query_geometry';\n\n/**\n * `SourceCache` is responsible for\n *\n * - creating an instance of `Source`\n * - forwarding events from `Source`\n * - caching tiles loaded from an instance of `Source`\n * - loading the tiles needed to render a given viewport\n * - unloading the cached tiles not needed to render a given viewport\n *\n * @private\n */\nclass SourceCache extends Evented {\n id: string;\n map: Map;\n style: Style;\n\n _source: Source;\n _sourceLoaded: boolean;\n _sourceErrored: boolean;\n _tiles: {[_: string | number]: Tile};\n _prevLng: number | void;\n _cache: TileCache;\n _timers: {[_: any]: TimeoutID};\n _cacheTimers: {[_: any]: TimeoutID};\n _maxTileCacheSize: ?number;\n _paused: boolean;\n _shouldReloadOnResume: boolean;\n _coveredTiles: {[_: number | string]: boolean};\n transform: Transform;\n _isIdRenderable: (id: number, symbolLayer?: boolean) => boolean;\n used: boolean;\n usedForTerrain: boolean;\n _state: SourceFeatureState;\n _loadedParentTiles: {[_: number | string]: ?Tile};\n _onlySymbols: ?boolean;\n\n static maxUnderzooming: number;\n static maxOverzooming: number;\n\n constructor(id: string, source: Source, onlySymbols?: boolean) {\n super();\n this.id = id;\n this._onlySymbols = onlySymbols;\n\n source.on('data', (e) => {\n // this._sourceLoaded signifies that the TileJSON is loaded if applicable.\n // if the source type does not come with a TileJSON, the flag signifies the\n // source data has loaded (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 source.on('error', () => {\n this._sourceErrored = true;\n });\n\n this._source = source;\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 }\n\n /**\n * Return true if no tile data is pending, tiles will not change unless\n * an additional API call is received.\n * @private\n */\n loaded(): boolean {\n if (this._sourceErrored) { return true; }\n if (!this._sourceLoaded) { return false; }\n if (!this._source.loaded()) { return false; }\n for (const t in this._tiles) {\n const tile = this._tiles[t];\n if (tile.state !== 'loaded' && tile.state !== 'errored')\n return false;\n }\n return true;\n }\n\n getSource(): Source {\n return this._source;\n }\n\n pause() {\n this._paused = true;\n }\n\n resume() {\n if (!this._paused) return;\n const shouldReload = this._shouldReloadOnResume;\n this._paused = false;\n this._shouldReloadOnResume = false;\n if (shouldReload) this.reload();\n if (this.transform) this.update(this.transform);\n }\n\n _loadTile(tile: Tile, callback: Callback<void>) {\n tile.isSymbolTile = this._onlySymbols;\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<number> {\n return values((this._tiles: any)).map((tile: Tile) => tile.tileID).sort(compareTileId).map(id => id.key);\n }\n\n getRenderableIds(symbolLayer?: boolean): Array<number> {\n const renderables: Array<Tile> = [];\n for (const id in this._tiles) {\n if (this._isIdRenderable(+id, symbolLayer)) renderables.push(this._tiles[id]);\n }\n if (symbolLayer) {\n return renderables.sort((a_: Tile, b_: Tile) => {\n const a = a_.tileID;\n const b = b_.tileID;\n const rotatedA = (new Point(a.canonical.x, a.canonical.y))._rotate(this.transform.angle);\n const rotatedB = (new Point(b.canonical.x, b.canonical.y))._rotate(this.transform.angle);\n return a.overscaledZ - b.overscaledZ || rotatedB.y - rotatedA.y || rotatedB.x - rotatedA.x;\n }).map(tile => tile.tileID.key);\n }\n return renderables.map(tile => tile.tileID).sort(compareTileId).map(id => id.key);\n }\n\n hasRenderableParent(tileID: OverscaledTileID) {\n const parentTile = this.findLoadedParent(tileID, 0);\n if (parentTile) {\n return this._isIdRenderable(parentTile.tileID.key);\n }\n return false;\n }\n\n _isIdRenderable(id: number, symbolLayer?: boolean) {\n return this._tiles[id] && this._tiles[id].hasData() &&\n !this._coveredTiles[id] && (symbolLayer || !this._tiles[id].holdingForFade());\n }\n\n reload() {\n if (this._paused) {\n this._shouldReloadOnResume = true;\n return;\n }\n\n this._cache.reset();\n\n for (const i in this._tiles) {\n if (this._tiles[i].state !== \"errored\") this._reloadTile(+i, 'reloading');\n }\n }\n\n _reloadTile(id: number, state: TileState) {\n const tile = this._tiles[id];\n\n // this potentially does not address all underlying\n // issues https://github.com/mapbox/mapbox-gl-js/issues/4252\n // - hard to tell without repro steps\n if (!tile) return;\n\n // The difference between \"loading\" tiles and \"reloading\" or \"expired\"\n // tiles is that \"reloading\"/\"expired\" tiles are \"renderable\".\n // Therefore, a \"loading\" tile cannot become a \"reloading\" tile without\n // first becoming a \"loaded\" tile.\n if (tile.state !== 'loading') {\n tile.state = state;\n }\n\n this._loadTile(tile, this._tileLoaded.bind(this, tile, id, state));\n }\n\n _tileLoaded(tile: Tile, id: number, previousState: TileState, err: ?Error) {\n if (err) {\n tile.state = 'errored';\n if ((err: any).status !== 404) this._source.fire(new ErrorEvent(err, {tile}));\n // 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, 'sourceCacheId': this.id}));\n }\n\n /**\n * For raster terrain source, backfill DEM to eliminate visible tile boundaries\n * @private\n */\n _backfillDEM(tile: Tile) {\n const renderables = this.getRenderableIds();\n for (let i = 0; i < renderables.length; i++) {\n const borderId = renderables[i];\n if (tile.neighboringTiles && tile.neighboringTiles[borderId]) {\n const borderTile = this.getTileByID(borderId);\n fillBorder(tile, borderTile);\n fillBorder(borderTile, tile);\n }\n }\n\n function fillBorder(tile, borderTile) {\n if (!tile.dem || tile.dem.borderReady) return;\n tile.needsHillshadePrepare = true;\n tile.needsDEMTextureUpload = true;\n let dx = borderTile.tileID.canonical.x - tile.tileID.canonical.x;\n const dy = borderTile.tileID.canonical.y - tile.tileID.canonical.y;\n const dim = Math.pow(2, tile.tileID.canonical.z);\n const borderId = borderTile.tileID.key;\n if (dx === 0 && dy === 0) return;\n\n if (Math.abs(dy) > 1) {\n return;\n }\n if (Math.abs(dx) > 1) {\n // Adjust the delta coordinate for world wraparound.\n if (Math.abs(dx + dim) === 1) {\n dx += dim;\n } else if (Math.abs(dx - dim) === 1) {\n dx -= dim;\n }\n }\n if (!borderTile.dem || !tile.dem) return;\n tile.dem.backfillBorder(borderTile.dem, dx, dy);\n if (tile.neighboringTiles && tile.neighboringTiles[borderId])\n tile.neighboringTiles[borderId].backfilled = true;\n }\n }\n /**\n * Get a specific tile by TileID\n * @private\n */\n getTile(tileID: OverscaledTileID): Tile {\n return this.getTileByID(tileID.key);\n }\n\n /**\n * Get a specific tile by id\n * @private\n */\n getTileByID(id: number): Tile {\n return this._tiles[id];\n }\n\n /**\n * For a given set of tiles, retain children that are loaded and have a zoom\n * between `zoom` (exclusive) and `maxCoveringZoom` (inclusive)\n * @private\n */\n _retainLoadedChildren(\n idealTiles: {[_: 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(this._source.reparseOverscaled ? tileID.wrapped().key : tileID.canonical.key);\n return cachedTile;\n }\n\n /**\n * Resizes the tile cache based on the current viewport's size\n * or the 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, tileSize?: number) {\n tileSize = tileSize || this._source.tileSize;\n const widthInTiles = Math.ceil(transform.width / tileSize) + 1;\n const heightInTiles = Math.ceil(transform.height / tileSize) + 1;\n const approxTilesInView = widthInTiles * heightInTiles;\n const commonZoomRange = 5;\n\n const viewDependentMaxSize = Math.floor(approxTilesInView * commonZoomRange);\n const 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 | number]: Tile} = {};\n for (const key in this._tiles) {\n const tile = this._tiles[key];\n tile.tileID = tile.tileID.unwrapTo(tile.tileID.wrap + wrapDelta);\n tiles[tile.tileID.key] = tile;\n }\n this._tiles = tiles;\n\n // Reset tile reload timers\n for (const id in this._timers) {\n clearTimeout(this._timers[id]);\n delete this._timers[id];\n }\n for (const id in this._tiles) {\n const tile = this._tiles[id];\n this._setTileReloadTimer(+id, tile);\n }\n }\n }\n\n /**\n * Removes tiles that are outside the viewport and adds new tiles that\n * are inside the viewport.\n * @private\n * @param {boolean} updateForTerrain Signals to update tiles even if the\n * source is not used (this.used) by layers: it is used for terrain.\n * @param {tileSize} tileSize If needed to get lower resolution ideal cover,\n * override source.tileSize used in tile cover calculation.\n */\n update(transform: Transform, tileSize?: number, updateForTerrain?: boolean) {\n this.transform = transform;\n if (!this._sourceLoaded || this._paused || this.transform.freezeTileCoverage) { return; }\n assert(!(updateForTerrain && !this.usedForTerrain));\n if (this.usedForTerrain && !updateForTerrain) {\n // If source is used for both terrain and hillshade, don't update it twice.\n return;\n }\n\n this.updateCacheSize(transform, tileSize);\n 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 && !this.usedForTerrain) {\n idealTileIDs = [];\n } else if (this._source.tileID) {\n idealTileIDs = transform.getVisibleUnwrappedCoordinates(this._source.tileID)\n .map((unwrapped) => new OverscaledTileID(unwrapped.canonical.z, unwrapped.wrap, unwrapped.canonical.z, unwrapped.canonical.x, unwrapped.canonical.y));\n } else {\n idealTileIDs = transform.coveringTiles({\n tileSize: tileSize || this._source.tileSize,\n minzoom: this._source.minzoom,\n maxzoom: this._source.maxzoom,\n roundZoom: this._source.roundZoom && !updateForTerrain,\n reparseOverscaled: this._source.reparseOverscaled,\n useElevationData: !!this.transform.elevation && !this.usedForTerrain\n });\n\n if (this._source.hasTile) {\n idealTileIDs = idealTileIDs.filter((coord) => (this._source.hasTile: any)(coord));\n }\n }\n\n // Retain is a list of tiles that we shouldn't delete, even if they are not\n // the most ideal tile for the current viewport. This may include tiles like\n // parent or child tiles that are *already* loaded.\n const retain = this._updateRetainedTiles(idealTileIDs);\n\n if (isRasterType(this._source.type) && idealTileIDs.length !== 0) {\n const parentsForFading: {[_: string | number]: OverscaledTileID} = {};\n const fadingTiles = {};\n const ids = Object.keys(retain);\n for (const id of ids) {\n const tileID = retain[id];\n assert(tileID.key === +id);\n\n const tile = this._tiles[id];\n if (!tile || tile.fadeEndTime && tile.fadeEndTime <= browser.now()) continue;\n\n // if the tile is loaded but still fading in, find parents to cross-fade with it\n const parentTile = this.findLoadedParent(tileID, Math.max(tileID.overscaledZ - SourceCache.maxOverzooming, this._source.minzoom));\n if (parentTile) {\n this._addTile(parentTile.tileID);\n parentsForFading[parentTile.tileID.key] = parentTile.tileID;\n }\n\n fadingTiles[id] = tileID;\n }\n\n // for children tiles with parent tiles still fading in,\n // retain the children so the parent can fade on top\n const minZoom = idealTileIDs[idealTileIDs.length - 1].overscaledZ;\n for (const id in this._tiles) {\n const childTile = this._tiles[id];\n if (retain[id] || !childTile.hasData()) {\n continue;\n }\n\n let parentID = childTile.tileID;\n while (parentID.overscaledZ > minZoom) {\n parentID = parentID.scaledTo(parentID.overscaledZ - 1);\n const tile = this._tiles[parentID.key];\n if (tile && tile.hasData() && fadingTiles[parentID.key]) {\n retain[id] = childTile.tileID;\n break;\n }\n }\n }\n\n for (const id in parentsForFading) {\n if (!retain[id]) {\n // If a tile is only needed for fading, mark it as covered so that it isn't rendered on it's own.\n this._coveredTiles[id] = true;\n retain[id] = parentsForFading[id];\n }\n }\n }\n\n for (const retainedId in retain) {\n // Make sure retained tiles always clear any existing fade holds\n // so that if they're removed again their fade timer starts fresh.\n this._tiles[retainedId].clearFadeHold();\n }\n\n // Remove the tiles we don't need anymore.\n const remove = keysDifference((this._tiles: any), (retain: any));\n for (const tileID of remove) {\n const tile = this._tiles[tileID];\n if (tile.hasSymbolBuckets && !tile.holdingForFade()) {\n tile.setHoldDuration(this.map._fadeDuration);\n } else if (!tile.hasSymbolBuckets || tile.symbolFadeFinished()) {\n this._removeTile(+tileID);\n }\n }\n\n // Construct a cache of loaded parents\n this._updateLoadedParentTileCache();\n\n if (this._onlySymbols && this._source.afterUpdate) {\n this._source.afterUpdate();\n }\n }\n\n releaseSymbolFadeTiles() {\n for (const id in this._tiles) {\n if (this._tiles[id].holdingForFade()) {\n this._removeTile(+id);\n }\n }\n }\n\n _updateRetainedTiles(idealTileIDs: Array<OverscaledTileID>): {[_: number | string]: OverscaledTileID} {\n const retain: {[_: number | string]: OverscaledTileID} = {};\n if (idealTileIDs.length === 0) { return retain; }\n\n const checked: {[_: number | string]: boolean } = {};\n const minZoom = idealTileIDs[idealTileIDs.length - 1].overscaledZ;\n const maxZoom = idealTileIDs[0].overscaledZ;\n assert(minZoom <= maxZoom);\n const minCoveringZoom = Math.max(maxZoom - SourceCache.maxOverzooming, this._source.minzoom);\n const maxCoveringZoom = Math.max(maxZoom + SourceCache.maxUnderzooming, this._source.minzoom);\n\n const missingTiles = {};\n for (const tileID of idealTileIDs) {\n const tile = this._addTile(tileID);\n\n // retain the tile even if it's not loaded because it's an ideal tile.\n retain[tileID.key] = tileID;\n\n if (tile.hasData()) continue;\n\n if (minZoom < this._source.maxzoom) {\n // save missing tiles that potentially have loaded children\n missingTiles[tileID.key] = tileID;\n }\n }\n\n // retain any loaded children of ideal tiles up to maxCoveringZoom\n this._retainLoadedChildren(missingTiles, minZoom, maxCoveringZoom, retain);\n\n for (const tileID of idealTileIDs) {\n let tile = this._tiles[tileID.key];\n\n if (tile.hasData()) continue;\n\n // The tile we require is not yet loaded or does not exist;\n // Attempt to find children that fully cover it.\n\n if (tileID.canonical.z >= this._source.maxzoom) {\n // We're looking for an overzoomed child tile.\n const childCoord = tileID.children(this._source.maxzoom)[0];\n const childTile = this.getTile(childCoord);\n if (!!childTile && childTile.hasData()) {\n retain[childCoord.key] = childCoord;\n continue; // tile is covered by overzoomed child\n }\n } else {\n // check if all 4 immediate children are loaded (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(), this.transform.tileZoom);\n this._loadTile(tile, this._tileLoaded.bind(this, tile, tileID.key, tile.state));\n }\n\n // Impossible, but silence flow.\n if (!tile) return (null: any);\n\n tile.uses++;\n this._tiles[tileID.key] = tile;\n if (!cached) this._source.fire(new Event('dataloading', {tile, coord: tile.tileID, dataType: 'source'}));\n\n return tile;\n }\n\n _setTileReloadTimer(id: number, tile: Tile) {\n if (id in this._timers) {\n clearTimeout(this._timers[id]);\n delete this._timers[id];\n }\n\n const expiryTimeout = tile.getExpiryTimeout();\n if (expiryTimeout) {\n this._timers[id] = setTimeout(() => {\n this._reloadTile(id, 'expired');\n delete this._timers[id];\n }, expiryTimeout);\n }\n }\n\n /**\n * Remove a tile, given its id, from the pyramid\n * @private\n */\n _removeTile(id: number) {\n const tile = this._tiles[id];\n if (!tile)\n return;\n\n tile.uses--;\n delete this._tiles[id];\n if (this._timers[id]) {\n clearTimeout(this._timers[id]);\n delete this._timers[id];\n }\n\n if (tile.uses > 0)\n return;\n\n if (tile.hasData() && tile.state !== 'reloading') {\n this._cache.add(tile.tileID, tile, tile.getExpiryTimeout());\n } else {\n tile.aborted = true;\n this._abortTile(tile);\n this._unloadTile(tile);\n }\n }\n\n /**\n * Remove all tiles from this pyramid\n */\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 cover the given `queryGeometry`.\n *\n * @param {QueryGeometry} queryGeometry\n * @param {boolean} [visualizeQueryGeometry=false]\n * @param {boolean} use3DQuery\n * @returns\n * @private\n */\n tilesIn(queryGeometry: QueryGeometry, use3DQuery: boolean, visualizeQueryGeometry: boolean): TilespaceQueryGeometry[] {\n const tileResults = [];\n\n const transform = this.transform;\n if (!transform) return tileResults;\n\n for (const tileID in this._tiles) {\n const tile = this._tiles[tileID];\n if (visualizeQueryGeometry) {\n tile.clearQueryDebugViz();\n }\n if (tile.holdingForFade()) {\n // Tiles held for fading are covered by tiles that are closer to ideal\n continue;\n }\n\n const tileResult = queryGeometry.containsTile(tile, transform, use3DQuery);\n if (tileResult) {\n tileResults.push(tileResult);\n }\n }\n return tileResults;\n }\n\n getVisibleCoordinates(symbolLayer?: boolean): Array<OverscaledTileID> {\n const coords = this.getRenderableIds(symbolLayer).map((id) => this._tiles[id].tileID);\n for (const coord of coords) {\n coord.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: number, namespace: string, dependencies: Array<string>) {\n const tile = this._tiles[tileKey];\n if (tile) {\n tile.setDependencies(namespace, dependencies);\n }\n }\n\n /**\n * Reloads all tiles that depend on the given keys.\n * @private\n */\n reloadTilesForDependencies(namespaces: Array<string>, keys: Array<string>) {\n for (const id in this._tiles) {\n const tile = this._tiles[id];\n if (tile.hasDependency(namespaces, keys)) {\n this._reloadTile(+id, 'reloading');\n }\n }\n this._cache.filter(tile => !tile.hasDependency(namespaces, keys));\n }\n}\n\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 MercatorCoordinate, {mercatorZfromAltitude} from '../geo/mercator_coordinate';\nimport DEMData from '../data/dem_data';\nimport SourceCache from '../source/source_cache';\nimport {number as interpolate} from '../style-spec/util/interpolate';\nimport EXTENT from '../data/extent';\nimport {vec3} from 'gl-matrix';\nimport Point from '@mapbox/point-geometry';\nimport {OverscaledTileID} from '../source/tile_id';\n\nimport type Tile from '../source/tile';\n\n/**\n * Provides access to elevation data from raster-dem source cache.\n */\nexport class Elevation {\n\n /**\n * Altitude above sea level in meters at specified point.\n * @param {MercatorCoordinate} point Mercator coordinate of the point.\n * @param {number} defaultIfNotLoaded Value that is returned if the dem tile of the provided point is not loaded\n * @returns {number} Altitude in meters.\n * If there is no loaded tile that carries information for the requested\n * point elevation, returns `defaultIfNotLoaded`.\n * Doesn't invoke network request to fetch the data.\n */\n getAtPoint(point: MercatorCoordinate, defaultIfNotLoaded: number = 0): number {\n const src = this._source();\n if (!src) return defaultIfNotLoaded;\n if (point.y < 0.0 || point.y > 1.0) {\n return defaultIfNotLoaded;\n }\n const cache: SourceCache = src;\n const z = cache.getSource().maxzoom;\n const tiles = 1 << z;\n const wrap = Math.floor(point.x);\n const px = point.x - wrap;\n const tileID = new OverscaledTileID(z, wrap, z, Math.floor(px * tiles), Math.floor(point.y * tiles));\n const demTile = this.findDEMTileFor(tileID);\n if (!(demTile && demTile.dem)) { return defaultIfNotLoaded; }\n const dem: DEMData = demTile.dem;\n const tilesAtTileZoom = 1 << demTile.tileID.canonical.z;\n const x = (px * tilesAtTileZoom - demTile.tileID.canonical.x) * dem.dim;\n const y = (point.y * tilesAtTileZoom - demTile.tileID.canonical.y) * dem.dim;\n const i = Math.floor(x);\n const j = Math.floor(y);\n\n return this.exaggeration() * interpolate(\n interpolate(dem.get(i, j), dem.get(i, j + 1), y - j),\n interpolate(dem.get(i + 1, j), dem.get(i + 1, j + 1), y - j),\n x - i);\n }\n\n /*\n * x and y are offset within tile, in 0 .. EXTENT coordinate space.\n */\n getAtTileOffset(tileID: OverscaledTileID, x: number, y: number): number {\n const tilesAtTileZoom = 1 << tileID.canonical.z;\n return this.getAtPoint(new MercatorCoordinate(\n tileID.wrap + (tileID.canonical.x + x / EXTENT) / tilesAtTileZoom,\n (tileID.canonical.y + y / EXTENT) / tilesAtTileZoom));\n }\n\n /*\n * Batch fetch for multiple tile points: points holds input and return value:\n * vec3's items on index 0 and 1 define x and y offset within tile, in [0 .. EXTENT]\n * range, respectively. vec3 item at index 2 is output value, in meters.\n * If a DEM tile that covers tileID is loaded, true is returned, otherwise false.\n * Nearest filter sampling on dem data is done (no interpolation).\n */\n getForTilePoints(tileID: OverscaledTileID, points: Array<vec3>, interpolated: ?boolean, useDemTile: ?Tile): boolean {\n const helper = DEMSampler.create(this, tileID, useDemTile);\n if (!helper) { return false; }\n\n points.forEach(p => {\n p[2] = this.exaggeration() * helper.getElevationAt(p[0], p[1], interpolated);\n });\n return true;\n }\n\n /**\n * Get elevation minimum and maximum for tile identified by `tileID`.\n * @param {OverscaledTileID} tileID is a sub tile (or covers the same space) of the DEM tile we read the information from.\n * @returns {?{min: number, max: number}} The min and max elevation.\n */\n getMinMaxForTile(tileID: OverscaledTileID): ?{min: number, max: number} {\n const demTile = this.findDEMTileFor(tileID);\n if (!(demTile && demTile.dem)) { return null; }\n const dem: DEMData = demTile.dem;\n const tree = dem.tree;\n const demTileID = demTile.tileID;\n const scale = 1 << tileID.canonical.z - demTileID.canonical.z;\n let xOffset = tileID.canonical.x / scale - demTileID.canonical.x;\n let yOffset = tileID.canonical.y / scale - demTileID.canonical.y;\n let index = 0; // Start from DEM tree root.\n for (let i = 0; i < tileID.canonical.z - demTileID.canonical.z; i++) {\n if (tree.leaves[index]) break;\n xOffset *= 2;\n yOffset *= 2;\n const childOffset = 2 * Math.floor(yOffset) + Math.floor(xOffset);\n index = tree.childOffsets[index] + childOffset;\n xOffset = xOffset % 1;\n yOffset = yOffset % 1;\n }\n return {min: this.exaggeration() * tree.minimums[index], max: this.exaggeration() * tree.maximums[index]};\n }\n\n /**\n * Performs raycast against visible DEM tiles on the screen and returns the distance travelled along the ray.\n * x & y components of the position are expected to be in normalized mercator coordinates [0, 1] and z in meters.\n * @param {vec3} position The ray origin.\n * @param {vec3} dir The ray direction.\n * @param {number} exaggeration The terrain exaggeration.\n */\n raycast(position: vec3, dir: vec3, exaggeration: number): ?number {\n throw new Error('Pure virtual method called.');\n }\n\n /**\n * Given a point on screen, returns 3D MercatorCoordinate on terrain.\n * Reconstructs a picked world position by casting a ray from screen coordinates\n * and sampling depth from the custom depth buffer. This function (currently) introduces\n * a potential stall (few frames) due to it reading pixel information from the gpu.\n * Depth buffer will also be generated if it doesn't already exist.\n * @param {Point} screenPoint Screen point in pixels in top-left origin coordinate system.\n * @returns {vec3} If there is intersection with terrain, returns 3D MercatorCoordinate's of\n * intersection, as vec3(x, y, z), otherwise null.\n */ /* eslint no-unused-vars: [\"error\", { \"args\": \"none\" }] */\n pointCoordinate(screenPoint: Point): ?vec3 {\n throw new Error('Pure virtual method called.');\n }\n\n /*\n * Implementation provides SourceCache of raster-dem source type cache, in\n * order to access already loaded cached tiles.\n */\n _source(): ?SourceCache {\n throw new Error('Pure virtual method called.');\n }\n\n /*\n * A multiplier defined by style as terrain exaggeration. Elevation provided\n * by getXXXX methods is multiplied by this.\n */\n exaggeration(): number {\n throw new Error('Pure virtual method called.');\n }\n\n /**\n * Lookup DEM tile that corresponds to (covers) tileID.\n * @private\n */\n findDEMTileFor(_: OverscaledTileID): ?Tile {\n throw new Error('Pure virtual method called.');\n }\n\n /**\n * Get list of DEM tiles used to render current frame.\n * @private\n */\n get visibleDemTiles(): Array<Tile> {\n throw new Error('Getter must be implemented in subclass.');\n }\n}\n\n/**\n * Helper class computes and caches data required to lookup elevation offsets at the tile level.\n */\nexport class DEMSampler {\n _demTile: Tile;\n _dem: DEMData;\n _scale: number;\n _offset: [number, number];\n\n constructor(demTile: Tile, scale: number, offset: [number, number]) {\n this._demTile = demTile;\n // demTile.dem will always exist because the factory method `create` does the check\n // Make flow happy with a cast through any\n this._dem = (((this._demTile.dem): any): DEMData);\n this._scale = scale;\n this._offset = offset;\n }\n\n static create(elevation: Elevation, tileID: OverscaledTileID, useDemTile: ?Tile): ?DEMSampler {\n const demTile = useDemTile || elevation.findDEMTileFor(tileID);\n if (!(demTile && demTile.dem)) { return; }\n const dem: DEMData = demTile.dem;\n const demTileID = demTile.tileID;\n const scale = 1 << tileID.canonical.z - demTileID.canonical.z;\n const xOffset = (tileID.canonical.x / scale - demTileID.canonical.x) * dem.dim;\n const yOffset = (tileID.canonical.y / scale - demTileID.canonical.y) * dem.dim;\n const k = demTile.tileSize / EXTENT / scale;\n\n return new DEMSampler(demTile, k, [xOffset, yOffset]);\n }\n\n tileCoordToPixel(x: number, y: number): Point {\n const px = x * this._scale + this._offset[0];\n const py = y * this._scale + this._offset[1];\n const i = Math.floor(px);\n const j = Math.floor(py);\n return new Point(i, j);\n }\n\n getElevationAt(x: number, y: number, interpolated: ?boolean, clampToEdge: ?boolean): number {\n const px = x * this._scale + this._offset[0];\n const py = y * this._scale + this._offset[1];\n const i = Math.floor(px);\n const j = Math.floor(py);\n const dem = this._dem;\n\n clampToEdge = !!clampToEdge;\n\n return interpolated ? interpolate(\n interpolate(dem.get(i, j, clampToEdge), dem.get(i, j + 1, clampToEdge), py - j),\n interpolate(dem.get(i + 1, j, clampToEdge), dem.get(i + 1, j + 1, clampToEdge), py - j),\n px - i) :\n dem.get(i, j, clampToEdge);\n }\n\n getElevationAtPixel(x: number, y: number, clampToEdge: ?boolean): number {\n return this._dem.get(x, y, !!clampToEdge);\n }\n\n getMeterToDEM(lat: number): number {\n return (1 << this._demTile.tileID.canonical.z) * mercatorZfromAltitude(1, lat) * this._dem.stride;\n }\n}\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport loadGeometry from './load_geometry';\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';\nimport {FeatureIndexArray} from './array_types';\nimport {DEMSampler} from '../terrain/elevation';\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';\nimport type {TilespaceQueryGeometry} from '../style/query_geometry';\nimport type {FeatureIndex as FeatureIndexStruct} from './array_types';\n\ntype QueryParameters = {\n pixelPosMatrix: Float32Array,\n transform: Transform,\n tileResult: TilespaceQueryGeometry,\n params: {\n filter: FilterSpecification,\n layers: Array<string>,\n availableImages: Array<string>\n }\n}\n\ntype FeatureIndices = {\n bucketIndex: number,\n sourceLayerIndex: number,\n featureIndex: number,\n layoutVertexArrayOffset: number\n} | FeatureIndexStruct;\n\nclass FeatureIndex {\n tileID: OverscaledTileID;\n x: number;\n y: number;\n z: number;\n grid: Grid;\n featureIndexArray: FeatureIndexArray;\n promoteId: ?PromoteIdSpecification;\n\n rawTileData: ArrayBuffer;\n bucketLayerIDs: Array<Array<string>>;\n\n vtLayers: {[_: string]: 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.featureIndexArray = new FeatureIndexArray();\n this.promoteId = promoteId;\n }\n\n insert(feature: VectorTileFeature, geometry: Array<Array<Point>>, featureIndex: number, sourceLayerIndex: number, bucketIndex: number, layoutVertexArrayOffset: number = 0) {\n const key = this.featureIndexArray.length;\n this.featureIndexArray.emplaceBack(featureIndex, sourceLayerIndex, bucketIndex, layoutVertexArrayOffset);\n\n const grid = this.grid;\n\n for (let r = 0; r < geometry.length; r++) {\n const ring = geometry[r];\n\n const bbox = [Infinity, Infinity, -Infinity, -Infinity];\n for (let i = 0; i < ring.length; i++) {\n const p = ring[i];\n bbox[0] = Math.min(bbox[0], p.x);\n bbox[1] = Math.min(bbox[1], p.y);\n bbox[2] = Math.max(bbox[2], p.x);\n bbox[3] = Math.max(bbox[3], p.y);\n }\n\n if (bbox[0] < EXTENT &&\n bbox[1] < EXTENT &&\n bbox[2] >= 0 &&\n bbox[3] >= 0) {\n grid.insert(key, bbox[0], bbox[1], bbox[2], bbox[3]);\n }\n }\n }\n\n loadVTLayers(): {[_: string]: 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 const params = args.params || {},\n filter = featureFilter(params.filter);\n const tilespaceGeometry = args.tileResult;\n const transform = args.transform;\n\n const bounds = tilespaceGeometry.bufferedTilespaceBounds;\n const queryPredicate = (bx1, by1, bx2, by2) => {\n return polygonIntersectsBox(tilespaceGeometry.bufferedTilespaceGeometry, bx1, by1, bx2, by2);\n };\n const matching = this.grid.query(bounds.min.x, bounds.min.y, bounds.max.x, bounds.max.y, queryPredicate);\n matching.sort(topDownFeatureComparator);\n\n let elevationHelper = null;\n if (transform.elevation && matching.length > 0) {\n elevationHelper = DEMSampler.create(transform.elevation, this.tileID);\n }\n\n const result = {};\n let previousIndex;\n for (let k = 0; k < matching.length; k++) {\n const index = matching[k];\n\n // don't check the same feature more than once\n if (index === previousIndex) continue;\n previousIndex = index;\n\n const match = this.featureIndexArray.get(index);\n let featureGeometry = null;\n this.loadMatchingFeature(\n result,\n match,\n filter,\n params.layers,\n params.availableImages,\n styleLayers,\n serializedLayers,\n sourceFeatureState,\n (feature: VectorTileFeature, styleLayer: StyleLayer, featureState: Object, layoutVertexArrayOffset: number = 0) => {\n if (!featureGeometry) {\n featureGeometry = loadGeometry(feature);\n }\n\n return styleLayer.queryIntersectsFeature(tilespaceGeometry, feature, featureState, featureGeometry, this.z, args.transform, args.pixelPosMatrix, elevationHelper, layoutVertexArrayOffset);\n }\n );\n }\n\n return result;\n }\n\n loadMatchingFeature(\n result: {[_: string]: Array<{ featureIndex: number, feature: GeoJSONFeature }>},\n featureIndexData: FeatureIndices,\n filter: FeatureFilter,\n filterLayerIDs: Array<string>,\n availableImages: Array<string>,\n styleLayers: {[_: string]: StyleLayer},\n serializedLayers: {[_: string]: Object},\n sourceFeatureState?: SourceFeatureState,\n intersectionTest?: (feature: VectorTileFeature, styleLayer: StyleLayer, featureState: Object, layoutVertexArrayOffset: number) => boolean | number) {\n\n const {featureIndex, bucketIndex, sourceLayerIndex, layoutVertexArrayOffset} = featureIndexData;\n const layerIDs = this.bucketLayerIDs[bucketIndex];\n if (filterLayerIDs && !arraysIntersect(filterLayerIDs, layerIDs))\n return;\n\n const sourceLayerName = this.sourceLayerCoder.decode(sourceLayerIndex);\n const sourceLayer = this.vtLayers[sourceLayerName];\n const feature = sourceLayer.feature(featureIndex);\n\n if (filter.needGeometry) {\n const evaluationFeature = toEvaluationFeature(feature, true);\n 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, layoutVertexArrayOffset);\n if (!intersectionZ) {\n // Only applied for non-symbol features\n continue;\n }\n\n const geojsonFeature = new GeoJSONFeature(feature, this.z, this.x, this.y, id);\n (geojsonFeature: 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<number>,\n serializedLayers: {[string]: StyleLayer},\n bucketIndex: number,\n sourceLayerIndex: number,\n filterSpec: FilterSpecification,\n filterLayerIDs: Array<string>,\n availableImages: Array<string>,\n styleLayers: {[_: string]: StyleLayer}) {\n const result = {};\n this.loadVTLayers();\n\n const filter = featureFilter(filterSpec);\n\n for (const symbolFeatureIndex of symbolFeatureIndexes) {\n this.loadMatchingFeature(\n result, {\n bucketIndex,\n sourceLayerIndex,\n featureIndex: symbolFeatureIndex,\n layoutVertexArrayOffset: 0\n },\n filter,\n filterLayerIDs,\n availableImages,\n styleLayers,\n serializedLayers\n );\n\n }\n return result;\n }\n\n 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 topDownFeatureComparator(a, b) {\n return b - a;\n}\n","// @flow\n\nimport {SDF_SCALE} from '../render/glyph_manager';\nimport {AlphaImage} from '../util/image';\nimport {register} from '../util/web_worker_transfer';\nimport potpack from 'potpack';\n\nimport type {GlyphMetrics, StyleGlyph} from '../style/style_glyph';\n\nconst glyphPadding = 1;\n/*\n The glyph padding is just to prevent sampling errors at the boundaries between\n glyphs in the atlas texture, and for that purpose there's no need to make it\n bigger with high-res SDFs. However, layout is done based on the glyph size\n including this padding, so scaling this padding is the easiest way to keep\n layout exactly the same as the SDF_SCALE changes.\n*/\nconst localGlyphPadding = glyphPadding * SDF_SCALE;\n\nexport type Rect = {\n x: number,\n y: number,\n w: number,\n h: number\n};\n\nexport type GlyphPosition = {\n rect: Rect,\n metrics: GlyphMetrics\n};\n\nexport type GlyphPositions = {[_: string]: {[_: number]: GlyphPosition } }\n\nexport default class GlyphAtlas {\n image: AlphaImage;\n positions: GlyphPositions;\n\n constructor(stacks: {[_: string]: {[_: number]: ?StyleGlyph } }) {\n const positions = {};\n const bins = [];\n\n for (const stack in stacks) {\n const glyphs = stacks[stack];\n const stackPositions = positions[stack] = {};\n\n for (const id in glyphs) {\n const src = glyphs[+id];\n if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) continue;\n\n const padding = src.metrics.localGlyph ? localGlyphPadding : glyphPadding;\n const bin = {\n x: 0,\n y: 0,\n w: src.bitmap.width + 2 * padding,\n h: src.bitmap.height + 2 * padding\n };\n bins.push(bin);\n stackPositions[id] = {rect: bin, metrics: src.metrics};\n }\n }\n\n const {w, h} = potpack(bins);\n const image = new AlphaImage({width: w || 1, height: h || 1});\n\n for (const stack in stacks) {\n const glyphs = stacks[stack];\n\n for (const id in glyphs) {\n const src = glyphs[+id];\n if (!src || src.bitmap.width === 0 || src.bitmap.height === 0) continue;\n const bin = positions[stack][id].rect;\n const padding = src.metrics.localGlyph ? localGlyphPadding : glyphPadding;\n AlphaImage.copy(src.bitmap, image, {x: 0, y: 0}, {x: bin.x + padding, y: bin.y + padding}, src.bitmap);\n }\n }\n\n this.image = image;\n this.positions = positions;\n }\n}\n\nregister('GlyphAtlas', GlyphAtlas);\n","// @flow\n\nimport FeatureIndex from '../data/feature_index';\n\nimport {performSymbolLayout} from '../symbol/symbol_layout';\nimport {CollisionBoxArray} from '../data/array_types';\nimport DictionaryCoder from '../util/dictionary_coder';\nimport SymbolBucket from '../data/bucket/symbol_bucket';\nimport LineBucket from '../data/bucket/line_bucket';\nimport FillBucket from '../data/bucket/fill_bucket';\nimport FillExtrusionBucket from '../data/bucket/fill_extrusion_bucket';\nimport {warnOnce, mapObject, values} from '../util/util';\nimport assert from 'assert';\nimport ImageAtlas from '../render/image_atlas';\nimport GlyphAtlas from '../render/glyph_atlas';\nimport EvaluationParameters from '../style/evaluation_parameters';\nimport {OverscaledTileID} from './tile_id';\nimport {PerformanceUtils} from '../util/performance';\n\nimport type {Bucket} from '../data/bucket';\nimport type Actor from '../util/actor';\nimport type StyleLayer from '../style/style_layer';\nimport type StyleLayerIndex from '../style/style_layer_index';\nimport type {StyleImage} from '../style/style_image';\nimport type {StyleGlyph} from '../style/style_glyph';\nimport type {\n WorkerTileParameters,\n WorkerTileCallback,\n} from '../source/worker_source';\nimport type {PromoteIdSpecification} from '../style-spec/types';\n\nclass WorkerTile {\n tileID: OverscaledTileID;\n uid: number;\n zoom: number;\n tileZoom: number;\n pixelRatio: number;\n tileSize: number;\n source: string;\n promoteId: ?PromoteIdSpecification;\n overscaling: number;\n showCollisionBoxes: boolean;\n collectResourceTiming: boolean;\n returnDependencies: boolean;\n enableTerrain: boolean;\n isSymbolTile: ?boolean;\n\n status: 'parsing' | 'done';\n data: VectorTile;\n collisionBoxArray: CollisionBoxArray;\n\n abort: ?() => void;\n reloadCallback: WorkerTileCallback;\n vectorTile: VectorTile;\n\n constructor(params: WorkerTileParameters) {\n this.tileID = new OverscaledTileID(params.tileID.overscaledZ, params.tileID.wrap, params.tileID.canonical.z, params.tileID.canonical.x, params.tileID.canonical.y);\n this.tileZoom = params.tileZoom;\n this.uid = params.uid;\n this.zoom = params.zoom;\n this.pixelRatio = params.pixelRatio;\n this.tileSize = params.tileSize;\n this.source = params.source;\n this.overscaling = this.tileID.overscaleFactor();\n this.showCollisionBoxes = params.showCollisionBoxes;\n this.collectResourceTiming = !!params.collectResourceTiming;\n this.returnDependencies = !!params.returnDependencies;\n this.promoteId = params.promoteId;\n this.enableTerrain = !!params.enableTerrain;\n this.isSymbolTile = params.isSymbolTile;\n }\n\n parse(data: VectorTile, layerIndex: StyleLayerIndex, availableImages: Array<string>, actor: Actor, callback: WorkerTileCallback) {\n const m = PerformanceUtils.beginMeasure('parseTile1');\n this.status = 'parsing';\n this.data = data;\n\n this.collisionBoxArray = new CollisionBoxArray();\n const sourceLayerCoder = new DictionaryCoder(Object.keys(data.layers).sort());\n\n const featureIndex = new FeatureIndex(this.tileID, this.promoteId);\n featureIndex.bucketLayerIDs = [];\n\n const buckets: {[_: string]: Bucket} = {};\n\n const options = {\n featureIndex,\n iconDependencies: {},\n patternDependencies: {},\n glyphDependencies: {},\n availableImages\n };\n\n const layerFamilies = layerIndex.familiesBySource[this.source];\n for (const sourceLayerId in layerFamilies) {\n const sourceLayer = data.layers[sourceLayerId];\n if (!sourceLayer) {\n continue;\n }\n\n let anySymbolLayers = false;\n let anyOtherLayers = false;\n for (const family of layerFamilies[sourceLayerId]) {\n if (family[0].type === 'symbol') {\n anySymbolLayers = true;\n } else {\n anyOtherLayers = true;\n }\n }\n\n if (this.isSymbolTile === true && !anySymbolLayers) {\n continue;\n } else if (this.isSymbolTile === false && !anyOtherLayers) {\n continue;\n }\n\n if (sourceLayer.version === 1) {\n warnOnce(`Vector tile source \"${this.source}\" layer \"${sourceLayerId}\" ` +\n `does not use vector tile spec v2 and therefore may have some rendering errors.`);\n }\n\n const sourceLayerIndex = sourceLayerCoder.encode(sourceLayerId);\n const features = [];\n for (let index = 0; index < sourceLayer.length; index++) {\n const feature = sourceLayer.feature(index);\n const id = featureIndex.getId(feature, sourceLayerId);\n features.push({feature, id, index, sourceLayerIndex});\n }\n\n for (const family of layerFamilies[sourceLayerId]) {\n const layer = family[0];\n if (this.isSymbolTile !== undefined && (layer.type === 'symbol') !== this.isSymbolTile) continue;\n\n assert(layer.source === this.source);\n if (layer.minzoom && this.zoom < Math.floor(layer.minzoom)) continue;\n if (layer.maxzoom && this.zoom >= layer.maxzoom) continue;\n if (layer.visibility === 'none') continue;\n\n recalculateLayers(family, this.zoom, availableImages);\n\n const bucket = buckets[layer.id] = layer.createBucket({\n index: featureIndex.bucketLayerIDs.length,\n layers: family,\n zoom: this.zoom,\n pixelRatio: this.pixelRatio,\n overscaling: this.overscaling,\n collisionBoxArray: this.collisionBoxArray,\n sourceLayerIndex,\n sourceID: this.source,\n enableTerrain: this.enableTerrain\n });\n\n bucket.populate(features, options, this.tileID.canonical);\n featureIndex.bucketLayerIDs.push(family.map((l) => l.id));\n }\n }\n\n let error: ?Error;\n let glyphMap: ?{[_: string]: {[_: number]: ?StyleGlyph}};\n let iconMap: ?{[_: string]: StyleImage};\n let patternMap: ?{[_: string]: StyleImage};\n const taskMetadata = {type: 'maybePrepare', isSymbolTile: this.isSymbolTile, zoom: this.zoom};\n\n const stacks = mapObject(options.glyphDependencies, (glyphs) => Object.keys(glyphs).map(Number));\n if (Object.keys(stacks).length) {\n actor.send('getGlyphs', {uid: this.uid, stacks}, (err, result) => {\n if (!error) {\n error = err;\n glyphMap = result;\n maybePrepare.call(this);\n }\n }, undefined, undefined, taskMetadata);\n } else {\n glyphMap = {};\n }\n\n const icons = Object.keys(options.iconDependencies);\n if (icons.length) {\n actor.send('getImages', {icons, source: this.source, tileID: this.tileID, type: 'icons'}, (err, result) => {\n if (!error) {\n error = err;\n iconMap = result;\n maybePrepare.call(this);\n }\n }, undefined, undefined, taskMetadata);\n } else {\n iconMap = {};\n }\n\n const patterns = Object.keys(options.patternDependencies);\n if (patterns.length) {\n actor.send('getImages', {icons: patterns, source: this.source, tileID: this.tileID, type: 'patterns'}, (err, result) => {\n if (!error) {\n error = err;\n patternMap = result;\n maybePrepare.call(this);\n }\n }, undefined, undefined, taskMetadata);\n } else {\n patternMap = {};\n }\n\n PerformanceUtils.endMeasure(m);\n\n maybePrepare.call(this);\n\n function maybePrepare() {\n if (error) {\n return callback(error);\n } else if (glyphMap && iconMap && patternMap) {\n const m = PerformanceUtils.beginMeasure('parseTile2');\n const glyphAtlas = new GlyphAtlas(glyphMap);\n const imageAtlas = new ImageAtlas(iconMap, patternMap);\n\n for (const key in buckets) {\n const bucket = buckets[key];\n if (bucket instanceof SymbolBucket) {\n recalculateLayers(bucket.layers, this.zoom, availableImages);\n performSymbolLayout(bucket,\n glyphMap,\n glyphAtlas.positions,\n iconMap,\n imageAtlas.iconPositions,\n this.showCollisionBoxes,\n this.tileID.canonical,\n this.tileZoom);\n } else if (bucket.hasPattern &&\n (bucket instanceof LineBucket ||\n bucket instanceof FillBucket ||\n bucket instanceof FillExtrusionBucket)) {\n recalculateLayers(bucket.layers, this.zoom, availableImages);\n bucket.addFeatures(options, this.tileID.canonical, imageAtlas.patternPositions);\n }\n }\n\n this.status = 'done';\n callback(null, {\n buckets: values(buckets).filter(b => !b.isEmpty()),\n featureIndex,\n collisionBoxArray: this.collisionBoxArray,\n glyphAtlasImage: glyphAtlas.image,\n imageAtlas,\n // Only used for benchmarking:\n glyphMap: this.returnDependencies ? glyphMap : null,\n iconMap: this.returnDependencies ? iconMap : null,\n glyphPositions: this.returnDependencies ? glyphAtlas.positions : null\n });\n PerformanceUtils.endMeasure(m);\n }\n }\n }\n}\n\nfunction recalculateLayers(layers: $ReadOnlyArray<StyleLayer>, zoom: number, availableImages: Array<string>) {\n // Layers are shared and may have been used by a WorkerTile with a different zoom.\n const parameters = new EvaluationParameters(zoom);\n for (const layer of layers) {\n layer.recalculate(parameters, availableImages);\n }\n}\n\nexport default WorkerTile;\n","// @flow\n\nimport {getArrayBuffer} from '../util/ajax';\n\nimport vt from '@mapbox/vector-tile';\nimport Protobuf from 'pbf';\nimport WorkerTile from './worker_tile';\nimport {extend} from '../util/util';\nimport {RequestPerformance} from '../util/performance';\nimport {Evented} from '../util/evented';\n\nimport type {\n WorkerSource,\n WorkerTileParameters,\n RequestedTileParameters,\n WorkerTileCallback,\n TileParameters\n} from '../source/worker_source';\n\nimport type Actor from '../util/actor';\nimport type StyleLayerIndex from '../style/style_layer_index';\nimport type {Callback} from '../types/callback';\nimport type Scheduler from '../util/scheduler';\n\nexport type LoadVectorTileResult = {\n rawData: ArrayBuffer;\n vectorTile?: VectorTile;\n expires?: any;\n cacheControl?: any;\n resourceTiming?: Array<PerformanceResourceTiming>;\n};\n\n/**\n * @callback LoadVectorDataCallback\n * @param error\n * @param vectorTile\n * @private\n */\nexport type LoadVectorDataCallback = Callback<?LoadVectorTileResult>;\n\nexport type AbortVectorData = () => void;\nexport type LoadVectorData = (params: RequestedTileParameters, callback: LoadVectorDataCallback) => ?AbortVectorData;\n\nexport class DedupedRequest {\n entries: { [string]: Object };\n scheduler: ?Scheduler;\n constructor(scheduler?: Scheduler) {\n this.entries = {};\n this.scheduler = scheduler;\n }\n\n request(key: string, metadata: Object, request: any, callback: LoadVectorDataCallback) {\n const entry = this.entries[key] = this.entries[key] || {callbacks: []};\n\n if (entry.result) {\n const [err, result] = entry.result;\n if (this.scheduler) {\n this.scheduler.add(() => {\n callback(err, result);\n }, metadata);\n } else {\n callback(err, result);\n }\n return () => {};\n }\n\n entry.callbacks.push(callback);\n\n if (!entry.cancel) {\n entry.cancel = request((err, result) => {\n entry.result = [err, result];\n for (const cb of entry.callbacks) {\n if (this.scheduler) {\n this.scheduler.add(() => {\n cb(err, result);\n }, metadata);\n } else {\n cb(err, result);\n }\n }\n setTimeout(() => delete this.entries[key], 1000 * 3);\n });\n }\n\n return () => {\n if (entry.result) return;\n entry.callbacks = entry.callbacks.filter(cb => cb !== callback);\n if (!entry.callbacks.length) {\n entry.cancel();\n delete this.entries[key];\n }\n };\n }\n}\n\n/**\n * @private\n */\nexport function loadVectorTile(params: RequestedTileParameters, callback: LoadVectorDataCallback, skipParse?: boolean) {\n const key = JSON.stringify(params.request);\n\n const makeRequest = (callback) => {\n const request = getArrayBuffer(params.request, (err: ?Error, data: ?ArrayBuffer, cacheControl: ?string, expires: ?string) => {\n if (err) {\n callback(err);\n } else if (data) {\n callback(null, {\n vectorTile: skipParse ? undefined : new vt.VectorTile(new Protobuf(data)),\n rawData: data,\n cacheControl,\n expires\n });\n }\n });\n return () => {\n request.cancel();\n callback();\n };\n };\n\n if (params.data) {\n // if we already got the result earlier (on the main thread), return it directly\n this.deduped.entries[key] = {result: [null, params.data]};\n }\n\n const callbackMetadata = {type: 'parseTile', isSymbolTile: params.isSymbolTile, zoom: params.tileZoom};\n return this.deduped.request(key, callbackMetadata, makeRequest, callback);\n}\n\n/**\n * The {@link WorkerSource} implementation that supports {@link VectorTileSource}.\n * This class is designed to be easily reused to support custom source types\n * for data formats that can be parsed/converted into an in-memory VectorTile\n * representation. To do so, create it with\n * `new VectorTileWorkerSource(actor, styleLayers, customLoadVectorDataFunction)`.\n *\n * @private\n */\nclass VectorTileWorkerSource extends Evented implements WorkerSource {\n actor: Actor;\n layerIndex: StyleLayerIndex;\n availableImages: Array<string>;\n loadVectorData: LoadVectorData;\n loading: {[_: number]: WorkerTile };\n loaded: {[_: number]: WorkerTile };\n deduped: DedupedRequest;\n isSpriteLoaded: boolean;\n scheduler: ?Scheduler;\n\n /**\n * @param [loadVectorData] Optional method for custom loading of a VectorTile\n * object based on parameters passed from the main-thread Source. See\n * {@link VectorTileWorkerSource#loadTile}. The default implementation simply\n * loads the pbf at `params.url`.\n * @private\n */\n constructor(actor: Actor, layerIndex: StyleLayerIndex, availableImages: Array<string>, isSpriteLoaded: boolean, loadVectorData: ?LoadVectorData) {\n super();\n this.actor = actor;\n this.layerIndex = layerIndex;\n this.availableImages = availableImages;\n this.loadVectorData = loadVectorData || loadVectorTile;\n this.loading = {};\n this.loaded = {};\n this.deduped = new DedupedRequest(actor.scheduler);\n this.isSpriteLoaded = isSpriteLoaded;\n this.scheduler = actor.scheduler;\n }\n\n /**\n * Implements {@link WorkerSource#loadTile}. Delegates to\n * {@link VectorTileWorkerSource#loadVectorData} (which by default expects\n * a `params.url` property) for fetching and producing a VectorTile object.\n * @private\n */\n loadTile(params: WorkerTileParameters, callback: WorkerTileCallback) {\n const uid = params.uid;\n\n const perf = (params && params.request && params.request.collectResourceTiming) ?\n new RequestPerformance(params.request) : false;\n\n const workerTile = this.loading[uid] = new WorkerTile(params);\n workerTile.abort = this.loadVectorData(params, (err, response) => {\n\n const aborted = !this.loading[uid];\n\n delete this.loading[uid];\n\n if (aborted || err || !response) {\n workerTile.status = 'done';\n if (!aborted) this.loaded[uid] = workerTile;\n return callback(err);\n }\n\n const rawTileData = response.rawData;\n const cacheControl = {};\n if (response.expires) cacheControl.expires = response.expires;\n if (response.cacheControl) cacheControl.cacheControl = response.cacheControl;\n\n const resourceTiming = {};\n if (perf) {\n const resourceTimingData = perf.finish();\n // it's necessary to eval the result of getEntriesByName() here via parse/stringify\n // late evaluation in the main thread causes TypeError: illegal invocation\n if (resourceTimingData)\n resourceTiming.resourceTiming = JSON.parse(JSON.stringify(resourceTimingData));\n }\n\n // response.vectorTile will be present in the GeoJSON worker case (which inherits from this class)\n // because we stub the vector tile interface around JSON data instead of parsing it directly\n workerTile.vectorTile = response.vectorTile || new vt.VectorTile(new Protobuf(rawTileData));\n const parseTile = () => {\n workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, (err, result) => {\n if (err || !result) return callback(err);\n\n // Transferring a copy of rawTileData because the worker needs to retain its copy.\n callback(null, extend({rawTileData: rawTileData.slice(0)}, result, cacheControl, resourceTiming));\n });\n };\n\n if (this.isSpriteLoaded) {\n parseTile();\n } else {\n this.once('isSpriteLoaded', () => {\n if (this.scheduler) {\n const metadata = {type: 'parseTile', isSymbolTile: params.isSymbolTile, zoom: params.tileZoom};\n this.scheduler.add(parseTile, metadata);\n } else {\n parseTile();\n }\n });\n }\n\n this.loaded = this.loaded || {};\n this.loaded[uid] = workerTile;\n });\n }\n\n /**\n * Implements {@link WorkerSource#reloadTile}.\n * @private\n */\n reloadTile(params: WorkerTileParameters, callback: WorkerTileCallback) {\n const loaded = this.loaded,\n uid = params.uid,\n vtSource = this;\n if (loaded && loaded[uid]) {\n const workerTile = loaded[uid];\n workerTile.showCollisionBoxes = params.showCollisionBoxes;\n workerTile.enableTerrain = !!params.enableTerrain;\n\n const done = (err, data) => {\n const reloadCallback = workerTile.reloadCallback;\n if (reloadCallback) {\n delete workerTile.reloadCallback;\n workerTile.parse(workerTile.vectorTile, vtSource.layerIndex, this.availableImages, vtSource.actor, reloadCallback);\n }\n callback(err, data);\n };\n\n if (workerTile.status === 'parsing') {\n workerTile.reloadCallback = done;\n } else if (workerTile.status === 'done') {\n // if there was no vector tile data on the initial load, don't try and re-parse tile\n if (workerTile.vectorTile) {\n workerTile.parse(workerTile.vectorTile, this.layerIndex, this.availableImages, this.actor, done);\n } else {\n done();\n }\n }\n }\n }\n\n /**\n * Implements {@link WorkerSource#abortTile}.\n *\n * @param params\n * @param params.uid The UID for this tile.\n * @private\n */\n abortTile(params: TileParameters, callback: WorkerTileCallback) {\n const uid = params.uid;\n const tile = this.loading[uid];\n if (tile) {\n if (tile.abort) tile.abort();\n delete this.loading[uid];\n }\n callback();\n }\n\n /**\n * Implements {@link WorkerSource#removeTile}.\n *\n * @param params\n * @param params.uid The UID for this tile.\n * @private\n */\n removeTile(params: TileParameters, callback: WorkerTileCallback) {\n const loaded = this.loaded,\n uid = params.uid;\n if (loaded && loaded[uid]) {\n delete loaded[uid];\n }\n callback();\n }\n}\n\nexport default VectorTileWorkerSource;\n","// @flow\n\nimport {bindAll, isWorker, isSafari} from './util';\nimport window from './window';\nimport {serialize, deserialize} from './web_worker_transfer';\nimport Scheduler from './scheduler';\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 cancelCallbacks: { number: Cancelable };\n globalScope: any;\n scheduler: Scheduler;\n\n constructor(target: any, parent: any, mapId: ?number) {\n this.target = target;\n this.parent = parent;\n this.mapId = mapId;\n this.callbacks = {};\n this.cancelCallbacks = {};\n bindAll(['receive'], this);\n this.target.addEventListener('message', this.receive, false);\n this.globalScope = isWorker() ? target : window;\n this.scheduler = new Scheduler();\n }\n\n /**\n * Sends a message from a main-thread map to a Worker or from a Worker back to\n * a main-thread map instance.\n *\n * @param type The name of the target method to invoke or '[source-type].[source-name].name' for a method on a WorkerSource.\n * @param targetMapId A particular mapId to which to send this message.\n * @private\n */\n send(type: string, data: mixed, callback: ?Function, targetMapId: ?string, mustQueue: boolean = false, callbackMetadata?: Object): ?Cancelable {\n // We're using a string ID instead of numbers because they are being used as object keys\n // anyway, and thus stringified implicitly. We use random IDs because an actor may receive\n // message from multiple other actors which could run in different execution context. A\n // linearly increasing ID could produce collisions.\n const id = Math.round((Math.random() * 1e18)).toString(36).substring(0, 10);\n if (callback) {\n callback.metadata = callbackMetadata;\n this.callbacks[id] = callback;\n }\n const buffers: ?Array<Transferable> = isSafari(this.globalScope) ? undefined : [];\n this.target.postMessage({\n id,\n type,\n hasCallback: !!callback,\n targetMapId,\n mustQueue,\n sourceMapId: this.mapId,\n data: serialize(data, buffers)\n }, buffers);\n return {\n cancel: () => {\n if (callback) {\n // Set the callback to null so that it never fires after the request is aborted.\n delete this.callbacks[id];\n }\n this.target.postMessage({\n id,\n type: '<cancel>',\n targetMapId,\n sourceMapId: this.mapId\n });\n }\n };\n }\n\n receive(message: Object) {\n const data = message.data,\n id = data.id;\n\n if (!id) {\n return;\n }\n\n if (data.targetMapId && this.mapId !== data.targetMapId) {\n return;\n }\n\n if (data.type === '<cancel>') {\n // Remove the original request from the queue. This is only possible if it\n // hasn't been kicked off yet. The id will remain in the queue, but because\n // there is no associated task, it will be dropped once it's time to execute it.\n const cancel = this.cancelCallbacks[id];\n delete this.cancelCallbacks[id];\n if (cancel) {\n cancel.cancel();\n }\n } else {\n if (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 // <cancel> 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 <cancel>\n // messages can be processed. We're using a MessageChannel object to get throttle the\n // process() flow to one at a time.\n const callback = this.callbacks[id];\n const metadata = (callback && callback.metadata) || {type: \"message\"};\n this.cancelCallbacks[id] = this.scheduler.add(() => this.processTask(id, data), metadata);\n } else {\n // In the main thread, process messages immediately so that other work does not slip in\n // between getting partial data back from workers.\n this.processTask(id, data);\n }\n }\n }\n\n processTask(id: number, task: any) {\n if (task.type === '<response>') {\n // The done() function in the counterpart has been called, and we are now\n // firing the callback in the originating actor, if there is one.\n const callback = this.callbacks[id];\n delete this.callbacks[id];\n if (callback) {\n // If we get a response, but don't have a callback, the request was canceled.\n if (task.error) {\n callback(deserialize(task.error));\n } else {\n callback(null, deserialize(task.data));\n }\n }\n } else {\n const buffers: ?Array<Transferable> = isSafari(this.globalScope) ? undefined : [];\n const done = task.hasCallback ? (err, data) => {\n delete this.cancelCallbacks[id];\n this.target.postMessage({\n id,\n type: '<response>',\n sourceMapId: this.mapId,\n error: err ? serialize(err) : null,\n data: serialize(data, buffers)\n }, buffers);\n } : (_) => {\n };\n\n const params = (deserialize(task.data): any);\n if (this.parent[task.type]) {\n // task.type == 'loadTile', 'removeTile', etc.\n this.parent[task.type](task.sourceMapId, params, done);\n } else if (this.parent.getWorkerSource) {\n // task.type == sourcetype.method\n const keys = task.type.split('.');\n const scope = (this.parent: any).getWorkerSource(task.sourceMapId, keys[0], params.source);\n scope[keys[1]](params, done);\n } else {\n // No function was found.\n done(new Error(`Could not find function ${task.type}`));\n }\n }\n }\n\n remove() {\n this.scheduler.remove();\n this.target.removeEventListener('message', this.receive, false);\n }\n}\n\nexport default Actor;\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 extTextureFilterAnisotropicForceOff: boolean;\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 this.extTextureFilterAnisotropicForceOff = false;\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<StructArrayMember>, 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, stencil}: 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 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<CullFaceMode>) {\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<DepthMode>) {\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<StencilMode>) {\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<ColorMode>) {\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","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;","\nimport refProperties from './util/ref_properties';\n\nfunction stringify(obj) {\n const type = typeof obj;\n if (type === 'number' || type === 'boolean' || type === 'string' || obj === undefined || obj === null)\n return JSON.stringify(obj);\n\n if (Array.isArray(obj)) {\n let str = '[';\n for (const val of obj) {\n str += `${stringify(val)},`;\n }\n return `${str}]`;\n }\n\n const keys = Object.keys(obj).sort();\n\n let str = '{';\n for (let i = 0; i < keys.length; i++) {\n str += `${JSON.stringify(keys[i])}:${stringify(obj[keys[i]])},`;\n }\n return `${str}}`;\n}\n\nfunction getKey(layer) {\n let key = '';\n for (const k of refProperties) {\n key += `/${stringify(layer[k])}`;\n }\n return key;\n}\n\nexport default groupByLayout;\n\n/**\n * Given an array of layers, return an array of arrays of layers where all\n * layers in each group have identical layout-affecting properties. These\n * are the properties that were formerly used by explicit `ref` mechanism\n * for layers: 'type', 'source', 'source-layer', 'minzoom', 'maxzoom',\n * 'filter', and 'layout'.\n *\n * The input is not modified. The output layers are references to the\n * input layers.\n *\n * @private\n * @param {Array<Layer>} layers\n * @param {Object} [cachedKeys] - an object to keep already calculated keys.\n * @returns {Array<Array<Layer>>}\n */\nfunction groupByLayout(layers, cachedKeys) {\n const groups = {};\n\n for (let i = 0; i < layers.length; i++) {\n\n const k = (cachedKeys && cachedKeys[layers[i].id]) || getKey(layers[i]);\n // update the cache if there is one\n if (cachedKeys)\n cachedKeys[layers[i].id] = k;\n\n let group = groups[k];\n if (!group) {\n group = groups[k] = [];\n }\n group.push(layers[i]);\n }\n\n const result = [];\n\n for (const k in groups) {\n result.push(groups[k]);\n }\n\n return result;\n}\n","// @flow\n\nimport StyleLayer from './style_layer';\nimport createStyleLayer from './create_style_layer';\n\nimport {values} from '../util/util';\nimport featureFilter from '../style-spec/feature_filter';\nimport groupByLayout from '../style-spec/group_by_layout';\n\nimport type {TypedStyleLayer} from './style_layer/typed_style_layer';\nimport type {LayerSpecification} from '../style-spec/types';\n\nexport type LayerConfigs = {[_: string]: LayerSpecification };\nexport type Family<Layer: TypedStyleLayer> = Array<Layer>;\n\nclass StyleLayerIndex {\n familiesBySource: { [source: string]: { [sourceLayer: string]: Array<Family<*>> } };\n keyCache: { [source: string]: string };\n\n _layerConfigs: LayerConfigs;\n _layers: {[_: string]: StyleLayer };\n\n constructor(layerConfigs: ?Array<LayerSpecification>) {\n this.keyCache = {};\n if (layerConfigs) {\n this.replace(layerConfigs);\n }\n }\n\n replace(layerConfigs: Array<LayerSpecification>) {\n this._layerConfigs = {};\n this._layers = {};\n this.update(layerConfigs, []);\n }\n\n update(layerConfigs: Array<LayerSpecification>, removedIds: Array<string>) {\n for (const layerConfig of layerConfigs) {\n this._layerConfigs[layerConfig.id] = layerConfig;\n\n const layer = this._layers[layerConfig.id] = createStyleLayer(layerConfig);\n layer._featureFilter = featureFilter(layer.filter);\n if (this.keyCache[layerConfig.id])\n delete this.keyCache[layerConfig.id];\n }\n for (const id of removedIds) {\n delete this.keyCache[id];\n delete this._layerConfigs[id];\n delete this._layers[id];\n }\n\n this.familiesBySource = {};\n\n const groups = groupByLayout(values(this._layerConfigs), this.keyCache);\n\n for (const layerConfigs of groups) {\n const layers = layerConfigs.map((layerConfig) => this._layers[layerConfig.id]);\n\n const layer = layers[0];\n if (layer.visibility === 'none') {\n continue;\n }\n\n const sourceId = layer.source || '';\n let sourceGroup = this.familiesBySource[sourceId];\n if (!sourceGroup) {\n sourceGroup = this.familiesBySource[sourceId] = {};\n }\n\n const sourceLayerId = layer.sourceLayer || '_geojsonTileLayer';\n let sourceLayerFamilies = sourceGroup[sourceLayerId];\n if (!sourceLayerFamilies) {\n sourceLayerFamilies = sourceGroup[sourceLayerId] = [];\n }\n\n sourceLayerFamilies.push(layers);\n }\n }\n}\n\nexport default StyleLayerIndex;\n","// @flow\n\nimport DEMData from '../data/dem_data';\nimport {RGBAImage} from '../util/image';\nimport window from '../util/window';\n\nimport type Actor from '../util/actor';\nimport type {WorkerDEMTileParameters, WorkerDEMTileCallback} from './worker_source';\nconst {ImageBitmap} = window;\n\nclass RasterDEMTileWorkerSource {\n actor: Actor;\n offscreenCanvas: OffscreenCanvas;\n offscreenCanvasContext: CanvasRenderingContext2D;\n\n loadTile(params: WorkerDEMTileParameters, callback: WorkerDEMTileCallback) {\n const {uid, encoding, rawImageData, padding, buildQuadTree} = params;\n // Main thread will transfer ImageBitmap if offscreen decode with OffscreenCanvas is supported, else it will transfer an already decoded image.\n const imagePixels = (ImageBitmap && rawImageData instanceof ImageBitmap) ? this.getImageData(rawImageData, padding) : rawImageData;\n const dem = new DEMData(uid, imagePixels, encoding, padding < 1, buildQuadTree);\n callback(null, dem);\n }\n\n getImageData(imgBitmap: ImageBitmap, padding: number): RGBAImage {\n // Lazily initialize OffscreenCanvas\n if (!this.offscreenCanvas || !this.offscreenCanvasContext) {\n // Dem tiles are typically 256x256\n this.offscreenCanvas = new OffscreenCanvas(imgBitmap.width, imgBitmap.height);\n this.offscreenCanvasContext = this.offscreenCanvas.getContext('2d');\n }\n\n this.offscreenCanvas.width = imgBitmap.width;\n this.offscreenCanvas.height = imgBitmap.height;\n\n this.offscreenCanvasContext.drawImage(imgBitmap, 0, 0, imgBitmap.width, imgBitmap.height);\n // Insert or remove defined padding around the image to allow backfilling for neighboring data.\n const imgData = this.offscreenCanvasContext.getImageData(-padding, -padding, imgBitmap.width + 2 * padding, imgBitmap.height + 2 * padding);\n this.offscreenCanvasContext.clearRect(0, 0, this.offscreenCanvas.width, this.offscreenCanvas.height);\n return new RGBAImage({width: imgData.width, height: imgData.height}, imgData.data);\n }\n}\n\nexport default RasterDEMTileWorkerSource;\n","\nmodule.exports = rewind;\n\nfunction rewind(gj, outer) {\n var type = gj && gj.type, i;\n\n if (type === 'FeatureCollection') {\n for (i = 0; i < gj.features.length; i++) rewind(gj.features[i], outer);\n\n } else if (type === 'GeometryCollection') {\n for (i = 0; i < gj.geometries.length; i++) rewind(gj.geometries[i], outer);\n\n } else if (type === 'Feature') {\n rewind(gj.geometry, outer);\n\n } else if (type === 'Polygon') {\n rewindRings(gj.coordinates, outer);\n\n } else if (type === 'MultiPolygon') {\n for (i = 0; i < gj.coordinates.length; i++) rewindRings(gj.coordinates[i], outer);\n }\n\n return gj;\n}\n\nfunction rewindRings(rings, outer) {\n if (rings.length === 0) return;\n\n rewindRing(rings[0], outer);\n for (var i = 1; i < rings.length; i++) {\n rewindRing(rings[i], !outer);\n }\n}\n\nfunction rewindRing(ring, dir) {\n var area = 0;\n for (var i = 0, len = ring.length, j = len - 1; i < len; j = i++) {\n area += (ring[i][0] - ring[j][0]) * (ring[j][1] + ring[i][1]);\n }\n if (area >= 0 !== !!dir) ring.reverse();\n}\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\n\nimport mvt from '@mapbox/vector-tile';\nconst toGeoJSON = mvt.VectorTileFeature.prototype.toGeoJSON;\nimport EXTENT from '../data/extent';\n\n// The feature type used by geojson-vt and supercluster. Should be extracted to\n// global type and used in module definitions for those two modules.\ntype Feature = {\n type: 1,\n id: mixed,\n tags: {[_: string]: string | number | boolean},\n geometry: Array<[number, number]>,\n} | {\n type: 2 | 3,\n id: mixed,\n tags: {[_: string]: string | number | boolean},\n geometry: Array<Array<[number, number]>>,\n}\n\nclass FeatureWrapper implements VectorTileFeature {\n _feature: Feature;\n\n extent: number;\n type: 1 | 2 | 3;\n id: number;\n properties: {[_: string]: string | number | boolean};\n\n constructor(feature: Feature) {\n this._feature = feature;\n\n this.extent = EXTENT;\n this.type = feature.type;\n this.properties = feature.tags;\n\n // If the feature has a top-level `id` property, copy it over, but only\n // if it can be coerced to an integer, because this wrapper is used for\n // serializing geojson feature data into vector tile PBF data, and the\n // vector tile spec only supports integer values for feature ids --\n // allowing non-integer values here results in a non-compliant PBF\n // that causes an exception when it is parsed with vector-tile-js\n if ('id' in feature && !isNaN(feature.id)) {\n this.id = parseInt(feature.id, 10);\n }\n }\n\n loadGeometry() {\n if (this._feature.type === 1) {\n const geometry = [];\n for (const point of this._feature.geometry) {\n geometry.push([new Point(point[0], point[1])]);\n }\n return geometry;\n } else {\n const geometry = [];\n for (const ring of this._feature.geometry) {\n const newRing = [];\n for (const point of ring) {\n newRing.push(new Point(point[0], point[1]));\n }\n geometry.push(newRing);\n }\n return geometry;\n }\n }\n\n toGeoJSON(x: number, y: number, z: number) {\n return toGeoJSON.call(this, x, y, z);\n }\n}\n\nclass GeoJSONWrapper implements VectorTile, VectorTileLayer {\n layers: {[_: string]: VectorTileLayer};\n name: string;\n extent: number;\n length: number;\n _features: Array<Feature>;\n\n constructor(features: Array<Feature>) {\n this.layers = {'_geojsonTileLayer': this};\n this.name = '_geojsonTileLayer';\n this.extent = EXTENT;\n this.length = features.length;\n this._features = features;\n }\n\n feature(i: number): VectorTileFeature {\n return new FeatureWrapper(this._features[i]);\n }\n}\n\nexport default GeoJSONWrapper;\n","'use strict'\n\nvar Point = require('@mapbox/point-geometry')\nvar VectorTileFeature = require('@mapbox/vector-tile').VectorTileFeature\n\nmodule.exports = GeoJSONWrapper\n\n// conform to vectortile api\nfunction GeoJSONWrapper (features, options) {\n this.options = options || {}\n this.features = features\n this.length = features.length\n}\n\nGeoJSONWrapper.prototype.feature = function (i) {\n return new FeatureWrapper(this.features[i], this.options.extent)\n}\n\nfunction FeatureWrapper (feature, extent) {\n this.id = typeof feature.id === 'number' ? feature.id : undefined\n this.type = feature.type\n this.rawGeometry = feature.type === 1 ? [feature.geometry] : feature.geometry\n this.properties = feature.tags\n this.extent = extent || 4096\n}\n\nFeatureWrapper.prototype.loadGeometry = function () {\n var rings = this.rawGeometry\n this.geometry = []\n\n for (var i = 0; i < rings.length; i++) {\n var ring = rings[i]\n var newRing = []\n for (var j = 0; j < ring.length; j++) {\n newRing.push(new Point(ring[j][0], ring[j][1]))\n }\n this.geometry.push(newRing)\n }\n return this.geometry\n}\n\nFeatureWrapper.prototype.bbox = function () {\n if (!this.geometry) this.loadGeometry()\n\n var rings = this.geometry\n var x1 = Infinity\n var x2 = -Infinity\n var y1 = Infinity\n var y2 = -Infinity\n\n for (var i = 0; i < rings.length; i++) {\n var ring = rings[i]\n\n for (var j = 0; j < ring.length; j++) {\n var coord = ring[j]\n\n x1 = Math.min(x1, coord.x)\n x2 = Math.max(x2, coord.x)\n y1 = Math.min(y1, coord.y)\n y2 = Math.max(y2, coord.y)\n }\n }\n\n return [x1, y1, x2, y2]\n}\n\nFeatureWrapper.prototype.toGeoJSON = VectorTileFeature.prototype.toGeoJSON\n","var Pbf = require('pbf')\nvar GeoJSONWrapper = require('./lib/geojson_wrapper')\n\nmodule.exports = fromVectorTileJs\nmodule.exports.fromVectorTileJs = fromVectorTileJs\nmodule.exports.fromGeojsonVt = fromGeojsonVt\nmodule.exports.GeoJSONWrapper = GeoJSONWrapper\n\n/**\n * Serialize a vector-tile-js-created tile to pbf\n *\n * @param {Object} tile\n * @return {Buffer} uncompressed, pbf-serialized tile data\n */\nfunction fromVectorTileJs (tile) {\n var out = new Pbf()\n writeTile(tile, out)\n return out.finish()\n}\n\n/**\n * Serialized a geojson-vt-created tile to pbf.\n *\n * @param {Object} layers - An object mapping layer names to geojson-vt-created vector tile objects\n * @param {Object} [options] - An object specifying the vector-tile specification version and extent that were used to create `layers`.\n * @param {Number} [options.version=1] - Version of vector-tile spec used\n * @param {Number} [options.extent=4096] - Extent of the vector tile\n * @return {Buffer} uncompressed, pbf-serialized tile data\n */\nfunction fromGeojsonVt (layers, options) {\n options = options || {}\n var l = {}\n for (var k in layers) {\n l[k] = new GeoJSONWrapper(layers[k].features, options)\n l[k].name = k\n l[k].version = options.version\n l[k].extent = options.extent\n }\n return fromVectorTileJs({layers: l})\n}\n\nfunction writeTile (tile, pbf) {\n for (var key in tile.layers) {\n pbf.writeMessage(3, writeLayer, tile.layers[key])\n }\n}\n\nfunction writeLayer (layer, pbf) {\n pbf.writeVarintField(15, layer.version || 1)\n pbf.writeStringField(1, layer.name || '')\n pbf.writeVarintField(5, layer.extent || 4096)\n\n var i\n var context = {\n keys: [],\n values: [],\n keycache: {},\n valuecache: {}\n }\n\n for (i = 0; i < layer.length; i++) {\n context.feature = layer.feature(i)\n pbf.writeMessage(2, writeFeature, context)\n }\n\n var keys = context.keys\n for (i = 0; i < keys.length; i++) {\n pbf.writeStringField(3, keys[i])\n }\n\n var values = context.values\n for (i = 0; i < values.length; i++) {\n pbf.writeMessage(4, writeValue, values[i])\n }\n}\n\nfunction writeFeature (context, pbf) {\n var feature = context.feature\n\n if (feature.id !== undefined) {\n pbf.writeVarintField(1, feature.id)\n }\n\n pbf.writeMessage(2, writeProperties, context)\n pbf.writeVarintField(3, feature.type)\n pbf.writeMessage(4, writeGeometry, feature)\n}\n\nfunction writeProperties (context, pbf) {\n var feature = context.feature\n var keys = context.keys\n var values = context.values\n var keycache = context.keycache\n var valuecache = context.valuecache\n\n for (var key in feature.properties) {\n var keyIndex = keycache[key]\n if (typeof keyIndex === 'undefined') {\n keys.push(key)\n keyIndex = keys.length - 1\n keycache[key] = keyIndex\n }\n pbf.writeVarint(keyIndex)\n\n var value = feature.properties[key]\n var type = typeof value\n if (type !== 'string' && type !== 'boolean' && type !== 'number') {\n value = JSON.stringify(value)\n }\n var valueKey = type + ':' + value\n var valueIndex = valuecache[valueKey]\n if (typeof valueIndex === 'undefined') {\n values.push(value)\n valueIndex = values.length - 1\n valuecache[valueKey] = valueIndex\n }\n pbf.writeVarint(valueIndex)\n }\n}\n\nfunction command (cmd, length) {\n return (length << 3) + (cmd & 0x7)\n}\n\nfunction zigzag (num) {\n return (num << 1) ^ (num >> 31)\n}\n\nfunction writeGeometry (feature, pbf) {\n var geometry = feature.loadGeometry()\n var type = feature.type\n var x = 0\n var y = 0\n var rings = geometry.length\n for (var r = 0; r < rings; r++) {\n var ring = geometry[r]\n var count = 1\n if (type === 1) {\n count = ring.length\n }\n pbf.writeVarint(command(1, count)) // moveto\n // do not write polygon closing path as lineto\n var lineCount = type === 3 ? ring.length - 1 : ring.length\n for (var i = 0; i < lineCount; i++) {\n if (i === 1 && type !== 1) {\n pbf.writeVarint(command(2, lineCount - 1)) // lineto\n }\n var dx = ring[i].x - x\n var dy = ring[i].y - y\n pbf.writeVarint(zigzag(dx))\n pbf.writeVarint(zigzag(dy))\n x += dx\n y += dy\n }\n if (type === 3) {\n pbf.writeVarint(command(7, 1)) // closepath\n }\n }\n}\n\nfunction writeValue (value, pbf) {\n var type = typeof value\n if (type === 'string') {\n pbf.writeStringField(1, value)\n } else if (type === 'boolean') {\n pbf.writeBooleanField(7, value)\n } else if (type === 'number') {\n if (value % 1 !== 0) {\n pbf.writeDoubleField(3, value)\n } else if (value < 0) {\n pbf.writeSVarintField(6, value)\n } else {\n pbf.writeVarintField(5, value)\n }\n }\n}\n","\nexport default function sortKD(ids, coords, nodeSize, left, right, depth) {\n if (right - left <= nodeSize) return;\n\n const m = (left + right) >> 1;\n\n select(ids, coords, m, left, right, depth % 2);\n\n sortKD(ids, coords, nodeSize, left, m - 1, depth + 1);\n sortKD(ids, coords, nodeSize, m + 1, right, depth + 1);\n}\n\nfunction select(ids, coords, k, left, right, inc) {\n\n while (right > left) {\n if (right - left > 600) {\n const n = right - left + 1;\n const m = k - left + 1;\n const z = Math.log(n);\n const s = 0.5 * Math.exp(2 * z / 3);\n const sd = 0.5 * Math.sqrt(z * s * (n - s) / n) * (m - n / 2 < 0 ? -1 : 1);\n const newLeft = Math.max(left, Math.floor(k - m * s / n + sd));\n const newRight = Math.min(right, Math.floor(k + (n - m) * s / n + sd));\n select(ids, coords, k, newLeft, newRight, inc);\n }\n\n const t = coords[2 * k + inc];\n let i = left;\n let j = right;\n\n swapItem(ids, coords, left, k);\n if (coords[2 * right + inc] > t) swapItem(ids, coords, left, right);\n\n while (i < j) {\n swapItem(ids, coords, i, j);\n i++;\n j--;\n while (coords[2 * i + inc] < t) i++;\n while (coords[2 * j + inc] > t) j--;\n }\n\n if (coords[2 * left + inc] === t) swapItem(ids, coords, left, j);\n else {\n j++;\n swapItem(ids, coords, j, right);\n }\n\n if (j <= k) left = j + 1;\n if (k <= j) right = j - 1;\n }\n}\n\nfunction swapItem(ids, coords, i, j) {\n swap(ids, i, j);\n swap(coords, 2 * i, 2 * j);\n swap(coords, 2 * i + 1, 2 * j + 1);\n}\n\nfunction swap(arr, i, j) {\n const tmp = arr[i];\n arr[i] = arr[j];\n arr[j] = tmp;\n}\n","\nexport default function within(ids, coords, qx, qy, r, nodeSize) {\n const stack = [0, ids.length - 1, 0];\n const result = [];\n const r2 = r * r;\n\n while (stack.length) {\n const axis = stack.pop();\n const right = stack.pop();\n const left = stack.pop();\n\n if (right - left <= nodeSize) {\n for (let i = left; i <= right; i++) {\n if (sqDist(coords[2 * i], coords[2 * i + 1], qx, qy) <= r2) result.push(ids[i]);\n }\n continue;\n }\n\n const m = Math.floor((left + right) / 2);\n\n const x = coords[2 * m];\n const y = coords[2 * m + 1];\n\n if (sqDist(x, y, qx, qy) <= r2) result.push(ids[m]);\n\n const nextAxis = (axis + 1) % 2;\n\n if (axis === 0 ? qx - r <= x : qy - r <= y) {\n stack.push(left);\n stack.push(m - 1);\n stack.push(nextAxis);\n }\n if (axis === 0 ? qx + r >= x : qy + r >= y) {\n stack.push(m + 1);\n stack.push(right);\n stack.push(nextAxis);\n }\n }\n\n return result;\n}\n\nfunction sqDist(ax, ay, bx, by) {\n const dx = ax - bx;\n const dy = ay - by;\n return dx * dx + dy * dy;\n}\n","\nimport sort from './sort';\nimport range from './range';\nimport within from './within';\n\nconst defaultGetX = p => p[0];\nconst defaultGetY = p => p[1];\n\nexport default class KDBush {\n constructor(points, getX = defaultGetX, getY = defaultGetY, nodeSize = 64, ArrayType = Float64Array) {\n this.nodeSize = nodeSize;\n this.points = points;\n\n const IndexArrayType = points.length < 65536 ? Uint16Array : Uint32Array;\n\n const ids = this.ids = new IndexArrayType(points.length);\n const coords = this.coords = new ArrayType(points.length * 2);\n\n for (let i = 0; i < points.length; i++) {\n ids[i] = i;\n coords[2 * i] = getX(points[i]);\n coords[2 * i + 1] = getY(points[i]);\n }\n\n sort(ids, coords, nodeSize, 0, ids.length - 1, 0);\n }\n\n range(minX, minY, maxX, maxY) {\n return range(this.ids, this.coords, minX, minY, maxX, maxY, this.nodeSize);\n }\n\n within(x, y, r) {\n return within(this.ids, this.coords, x, y, r, this.nodeSize);\n }\n}\n","\nexport default function range(ids, coords, minX, minY, maxX, maxY, nodeSize) {\n const stack = [0, ids.length - 1, 0];\n const result = [];\n let x, y;\n\n while (stack.length) {\n const axis = stack.pop();\n const right = stack.pop();\n const left = stack.pop();\n\n if (right - left <= nodeSize) {\n for (let i = left; i <= right; i++) {\n x = coords[2 * i];\n y = coords[2 * i + 1];\n if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[i]);\n }\n continue;\n }\n\n const m = Math.floor((left + right) / 2);\n\n x = coords[2 * m];\n y = coords[2 * m + 1];\n\n if (x >= minX && x <= maxX && y >= minY && y <= maxY) result.push(ids[m]);\n\n const nextAxis = (axis + 1) % 2;\n\n if (axis === 0 ? minX <= x : minY <= y) {\n stack.push(left);\n stack.push(m - 1);\n stack.push(nextAxis);\n }\n if (axis === 0 ? maxX >= x : maxY >= y) {\n stack.push(m + 1);\n stack.push(right);\n stack.push(nextAxis);\n }\n }\n\n return result;\n}\n","\nimport KDBush from 'kdbush';\n\nconst defaultOptions = {\n minZoom: 0, // min zoom to generate clusters on\n maxZoom: 16, // max zoom level to cluster the points on\n minPoints: 2, // minimum points to form a cluster\n radius: 40, // cluster radius in pixels\n extent: 512, // tile extent (radius is calculated relative to it)\n nodeSize: 64, // size of the KD-tree leaf node, affects performance\n log: false, // whether to log timing info\n\n // whether to generate numeric ids for input features (in vector tiles)\n generateId: false,\n\n // a reduce function for calculating custom cluster properties\n reduce: null, // (accumulated, props) => { accumulated.sum += props.sum; }\n\n // properties to use for individual points when running the reducer\n map: props => props // props => ({sum: props.my_value})\n};\n\nconst fround = Math.fround || (tmp => ((x) => { tmp[0] = +x; return tmp[0]; }))(new Float32Array(1));\n\nexport default class Supercluster {\n constructor(options) {\n this.options = extend(Object.create(defaultOptions), options);\n this.trees = new Array(this.options.maxZoom + 1);\n }\n\n load(points) {\n const {log, minZoom, maxZoom, nodeSize} = this.options;\n\n if (log) console.time('total time');\n\n const timerId = `prepare ${ points.length } points`;\n if (log) console.time(timerId);\n\n this.points = points;\n\n // generate a cluster object for each point and index input points into a KD-tree\n let clusters = [];\n for (let i = 0; i < points.length; i++) {\n if (!points[i].geometry) continue;\n clusters.push(createPointCluster(points[i], i));\n }\n this.trees[maxZoom + 1] = new KDBush(clusters, getX, getY, nodeSize, Float32Array);\n\n if (log) console.timeEnd(timerId);\n\n // cluster points on max zoom, then cluster the results on previous zoom, etc.;\n // results in a cluster hierarchy across zoom levels\n for (let z = maxZoom; z >= minZoom; z--) {\n const now = +Date.now();\n\n // create a new set of clusters for the zoom and index them with a KD-tree\n clusters = this._cluster(clusters, z);\n this.trees[z] = new KDBush(clusters, getX, getY, nodeSize, Float32Array);\n\n if (log) console.log('z%d: %d clusters in %dms', z, clusters.length, +Date.now() - now);\n }\n\n if (log) console.timeEnd('total time');\n\n return this;\n }\n\n getClusters(bbox, zoom) {\n let minLng = ((bbox[0] + 180) % 360 + 360) % 360 - 180;\n const minLat = Math.max(-90, Math.min(90, bbox[1]));\n let maxLng = bbox[2] === 180 ? 180 : ((bbox[2] + 180) % 360 + 360) % 360 - 180;\n const maxLat = Math.max(-90, Math.min(90, bbox[3]));\n\n if (bbox[2] - bbox[0] >= 360) {\n minLng = -180;\n maxLng = 180;\n } else if (minLng > maxLng) {\n const easternHem = this.getClusters([minLng, minLat, 180, maxLat], zoom);\n const westernHem = this.getClusters([-180, minLat, maxLng, maxLat], zoom);\n return easternHem.concat(westernHem);\n }\n\n const tree = this.trees[this._limitZoom(zoom)];\n const ids = tree.range(lngX(minLng), latY(maxLat), lngX(maxLng), latY(minLat));\n const clusters = [];\n for (const id of ids) {\n const c = tree.points[id];\n clusters.push(c.numPoints ? getClusterJSON(c) : this.points[c.index]);\n }\n return clusters;\n }\n\n getChildren(clusterId) {\n const originId = this._getOriginId(clusterId);\n const originZoom = this._getOriginZoom(clusterId);\n const errorMsg = 'No cluster with the specified id.';\n\n const index = this.trees[originZoom];\n if (!index) throw new Error(errorMsg);\n\n const origin = index.points[originId];\n if (!origin) throw new Error(errorMsg);\n\n const r = this.options.radius / (this.options.extent * Math.pow(2, originZoom - 1));\n const ids = index.within(origin.x, origin.y, r);\n const children = [];\n for (const id of ids) {\n const c = index.points[id];\n if (c.parentId === clusterId) {\n children.push(c.numPoints ? getClusterJSON(c) : this.points[c.index]);\n }\n }\n\n if (children.length === 0) throw new Error(errorMsg);\n\n return children;\n }\n\n getLeaves(clusterId, limit, offset) {\n limit = limit || 10;\n offset = offset || 0;\n\n const leaves = [];\n this._appendLeaves(leaves, clusterId, limit, offset, 0);\n\n return leaves;\n }\n\n getTile(z, x, y) {\n const tree = this.trees[this._limitZoom(z)];\n const z2 = Math.pow(2, z);\n const {extent, radius} = this.options;\n const p = radius / extent;\n const top = (y - p) / z2;\n const bottom = (y + 1 + p) / z2;\n\n const tile = {\n features: []\n };\n\n this._addTileFeatures(\n tree.range((x - p) / z2, top, (x + 1 + p) / z2, bottom),\n tree.points, x, y, z2, tile);\n\n if (x === 0) {\n this._addTileFeatures(\n tree.range(1 - p / z2, top, 1, bottom),\n tree.points, z2, y, z2, tile);\n }\n if (x === z2 - 1) {\n this._addTileFeatures(\n tree.range(0, top, p / z2, bottom),\n tree.points, -1, y, z2, tile);\n }\n\n return tile.features.length ? tile : null;\n }\n\n getClusterExpansionZoom(clusterId) {\n let expansionZoom = this._getOriginZoom(clusterId) - 1;\n while (expansionZoom <= this.options.maxZoom) {\n const children = this.getChildren(clusterId);\n expansionZoom++;\n if (children.length !== 1) break;\n clusterId = children[0].properties.cluster_id;\n }\n return expansionZoom;\n }\n\n _appendLeaves(result, clusterId, limit, offset, skipped) {\n const children = this.getChildren(clusterId);\n\n for (const child of children) {\n const props = child.properties;\n\n if (props && props.cluster) {\n if (skipped + props.point_count <= offset) {\n // skip the whole cluster\n skipped += props.point_count;\n } else {\n // enter the cluster\n skipped = this._appendLeaves(result, props.cluster_id, limit, offset, skipped);\n // exit the cluster\n }\n } else if (skipped < offset) {\n // skip a single point\n skipped++;\n } else {\n // add a single point\n result.push(child);\n }\n if (result.length === limit) break;\n }\n\n return skipped;\n }\n\n _addTileFeatures(ids, points, x, y, z2, tile) {\n for (const i of ids) {\n const c = points[i];\n const isCluster = c.numPoints;\n const f = {\n type: 1,\n geometry: [[\n Math.round(this.options.extent * (c.x * z2 - x)),\n Math.round(this.options.extent * (c.y * z2 - y))\n ]],\n tags: isCluster ? getClusterProperties(c) : this.points[c.index].properties\n };\n\n // assign id\n let id;\n if (isCluster) {\n id = c.id;\n } else if (this.options.generateId) {\n // optionally generate id\n id = c.index;\n } else if (this.points[c.index].id) {\n // keep id if already assigned\n id = this.points[c.index].id;\n }\n\n if (id !== undefined) f.id = id;\n\n tile.features.push(f);\n }\n }\n\n _limitZoom(z) {\n return Math.max(this.options.minZoom, Math.min(+z, this.options.maxZoom + 1));\n }\n\n _cluster(points, zoom) {\n const clusters = [];\n const {radius, extent, reduce, minPoints} = this.options;\n const r = radius / (extent * Math.pow(2, zoom));\n\n // loop through each point\n for (let i = 0; i < points.length; i++) {\n const p = points[i];\n // if we've already visited the point at this zoom level, skip it\n if (p.zoom <= zoom) continue;\n p.zoom = zoom;\n\n // find all nearby points\n const tree = this.trees[zoom + 1];\n const neighborIds = tree.within(p.x, p.y, r);\n\n const numPointsOrigin = p.numPoints || 1;\n let numPoints = numPointsOrigin;\n\n // count the number of points in a potential cluster\n for (const neighborId of neighborIds) {\n const b = tree.points[neighborId];\n // filter out neighbors that are already processed\n if (b.zoom > zoom) numPoints += b.numPoints || 1;\n }\n\n if (numPoints >= minPoints) { // enough points to form a cluster\n let wx = p.x * numPointsOrigin;\n let wy = p.y * numPointsOrigin;\n\n let clusterProperties = reduce && numPointsOrigin > 1 ? this._map(p, true) : null;\n\n // encode both zoom and point index on which the cluster originated -- offset by total length of features\n const id = (i << 5) + (zoom + 1) + this.points.length;\n\n for (const neighborId of neighborIds) {\n const b = tree.points[neighborId];\n\n if (b.zoom <= zoom) continue;\n b.zoom = zoom; // save the zoom (so it doesn't get processed twice)\n\n const numPoints2 = b.numPoints || 1;\n wx += b.x * numPoints2; // accumulate coordinates for calculating weighted center\n wy += b.y * numPoints2;\n\n b.parentId = id;\n\n if (reduce) {\n if (!clusterProperties) clusterProperties = this._map(p, true);\n reduce(clusterProperties, this._map(b));\n }\n }\n\n p.parentId = id;\n clusters.push(createCluster(wx / numPoints, wy / numPoints, id, numPoints, clusterProperties));\n\n } else { // left points as unclustered\n clusters.push(p);\n\n if (numPoints > 1) {\n for (const neighborId of neighborIds) {\n const b = tree.points[neighborId];\n if (b.zoom <= zoom) continue;\n b.zoom = zoom;\n clusters.push(b);\n }\n }\n }\n }\n\n return clusters;\n }\n\n // get index of the point from which the cluster originated\n _getOriginId(clusterId) {\n return (clusterId - this.points.length) >> 5;\n }\n\n // get zoom of the point from which the cluster originated\n _getOriginZoom(clusterId) {\n return (clusterId - this.points.length) % 32;\n }\n\n _map(point, clone) {\n if (point.numPoints) {\n return clone ? extend({}, point.properties) : point.properties;\n }\n const original = this.points[point.index].properties;\n const result = this.options.map(original);\n return clone && result === original ? extend({}, result) : result;\n }\n}\n\nfunction createCluster(x, y, id, numPoints, properties) {\n return {\n x: fround(x), // weighted cluster center; round for consistency with Float32Array index\n y: fround(y),\n zoom: Infinity, // the last zoom the cluster was processed at\n id, // encodes index of the first child of the cluster and its zoom level\n parentId: -1, // parent cluster id\n numPoints,\n properties\n };\n}\n\nfunction createPointCluster(p, id) {\n const [x, y] = p.geometry.coordinates;\n return {\n x: fround(lngX(x)), // projected point coordinates\n y: fround(latY(y)),\n zoom: Infinity, // the last zoom the point was processed at\n index: id, // index of the source feature in the original input array,\n parentId: -1 // parent cluster id\n };\n}\n\nfunction getClusterJSON(cluster) {\n return {\n type: 'Feature',\n id: cluster.id,\n properties: getClusterProperties(cluster),\n geometry: {\n type: 'Point',\n coordinates: [xLng(cluster.x), yLat(cluster.y)]\n }\n };\n}\n\nfunction getClusterProperties(cluster) {\n const count = cluster.numPoints;\n const abbrev =\n count >= 10000 ? `${Math.round(count / 1000) }k` :\n count >= 1000 ? `${Math.round(count / 100) / 10 }k` : count;\n return extend(extend({}, cluster.properties), {\n cluster: true,\n cluster_id: cluster.id,\n point_count: count,\n point_count_abbreviated: abbrev\n });\n}\n\n// longitude/latitude to spherical mercator in [0..1] range\nfunction lngX(lng) {\n return lng / 360 + 0.5;\n}\nfunction latY(lat) {\n const sin = Math.sin(lat * Math.PI / 180);\n const y = (0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI);\n return y < 0 ? 0 : y > 1 ? 1 : y;\n}\n\n// spherical mercator to longitude/latitude\nfunction xLng(x) {\n return (x - 0.5) * 360;\n}\nfunction yLat(y) {\n const y2 = (180 - y * 360) * Math.PI / 180;\n return 360 * Math.atan(Math.exp(y2)) / Math.PI - 90;\n}\n\nfunction extend(dest, src) {\n for (const id in src) dest[id] = src[id];\n return dest;\n}\n\nfunction getX(p) {\n return p.x;\n}\nfunction getY(p) {\n return p.y;\n}\n","\n// calculate simplification data using optimized Douglas-Peucker algorithm\n\nexport default function simplify(coords, first, last, sqTolerance) {\n var maxSqDist = sqTolerance;\n var mid = (last - first) >> 1;\n var minPosToMid = last - first;\n var index;\n\n var ax = coords[first];\n var ay = coords[first + 1];\n var bx = coords[last];\n var by = coords[last + 1];\n\n for (var i = first + 3; i < last; i += 3) {\n var d = getSqSegDist(coords[i], coords[i + 1], ax, ay, bx, by);\n\n if (d > maxSqDist) {\n index = i;\n maxSqDist = d;\n\n } else if (d === maxSqDist) {\n // a workaround to ensure we choose a pivot close to the middle of the list,\n // reducing recursion depth, for certain degenerate inputs\n // https://github.com/mapbox/geojson-vt/issues/104\n var posToMid = Math.abs(i - mid);\n if (posToMid < minPosToMid) {\n index = i;\n minPosToMid = posToMid;\n }\n }\n }\n\n if (maxSqDist > sqTolerance) {\n if (index - first > 3) simplify(coords, first, index, sqTolerance);\n coords[index + 2] = maxSqDist;\n if (last - index > 3) simplify(coords, index, last, sqTolerance);\n }\n}\n\n// square distance from a point to a segment\nfunction getSqSegDist(px, py, x, y, bx, by) {\n\n var dx = bx - x;\n var dy = by - y;\n\n if (dx !== 0 || dy !== 0) {\n\n var t = ((px - x) * dx + (py - y) * dy) / (dx * dx + dy * dy);\n\n if (t > 1) {\n x = bx;\n y = by;\n\n } else if (t > 0) {\n x += dx * t;\n y += dy * t;\n }\n }\n\n dx = px - x;\n dy = py - y;\n\n return dx * dx + dy * dy;\n}\n","\nexport default function createFeature(id, type, geom, tags) {\n var feature = {\n id: typeof id === 'undefined' ? null : id,\n type: type,\n geometry: geom,\n tags: tags,\n minX: Infinity,\n minY: Infinity,\n maxX: -Infinity,\n maxY: -Infinity\n };\n calcBBox(feature);\n return feature;\n}\n\nfunction calcBBox(feature) {\n var geom = feature.geometry;\n var type = feature.type;\n\n if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') {\n calcLineBBox(feature, geom);\n\n } else if (type === 'Polygon' || type === 'MultiLineString') {\n for (var i = 0; i < geom.length; i++) {\n calcLineBBox(feature, geom[i]);\n }\n\n } else if (type === 'MultiPolygon') {\n for (i = 0; i < geom.length; i++) {\n for (var j = 0; j < geom[i].length; j++) {\n calcLineBBox(feature, geom[i][j]);\n }\n }\n }\n}\n\nfunction calcLineBBox(feature, geom) {\n for (var i = 0; i < geom.length; i += 3) {\n feature.minX = Math.min(feature.minX, geom[i]);\n feature.minY = Math.min(feature.minY, geom[i + 1]);\n feature.maxX = Math.max(feature.maxX, geom[i]);\n feature.maxY = Math.max(feature.maxY, geom[i + 1]);\n }\n}\n","\nimport simplify from './simplify';\nimport createFeature from './feature';\n\n// converts GeoJSON feature into an intermediate projected JSON vector format with simplification data\n\nexport default function convert(data, options) {\n var features = [];\n if (data.type === 'FeatureCollection') {\n for (var i = 0; i < data.features.length; i++) {\n convertFeature(features, data.features[i], options, i);\n }\n\n } else if (data.type === 'Feature') {\n convertFeature(features, data, options);\n\n } else {\n // single geometry or a geometry collection\n convertFeature(features, {geometry: data}, options);\n }\n\n return features;\n}\n\nfunction convertFeature(features, geojson, options, index) {\n if (!geojson.geometry) return;\n\n var coords = geojson.geometry.coordinates;\n var type = geojson.geometry.type;\n var tolerance = Math.pow(options.tolerance / ((1 << options.maxZoom) * options.extent), 2);\n var geometry = [];\n var id = geojson.id;\n if (options.promoteId) {\n id = geojson.properties[options.promoteId];\n } else if (options.generateId) {\n id = index || 0;\n }\n if (type === 'Point') {\n convertPoint(coords, geometry);\n\n } else if (type === 'MultiPoint') {\n for (var i = 0; i < coords.length; i++) {\n convertPoint(coords[i], geometry);\n }\n\n } else if (type === 'LineString') {\n convertLine(coords, geometry, tolerance, false);\n\n } else if (type === 'MultiLineString') {\n if (options.lineMetrics) {\n // explode into linestrings to be able to track metrics\n for (i = 0; i < coords.length; i++) {\n geometry = [];\n convertLine(coords[i], geometry, tolerance, false);\n features.push(createFeature(id, 'LineString', geometry, geojson.properties));\n }\n return;\n } else {\n convertLines(coords, geometry, tolerance, false);\n }\n\n } else if (type === 'Polygon') {\n convertLines(coords, geometry, tolerance, true);\n\n } else if (type === 'MultiPolygon') {\n for (i = 0; i < coords.length; i++) {\n var polygon = [];\n convertLines(coords[i], polygon, tolerance, true);\n geometry.push(polygon);\n }\n } else if (type === 'GeometryCollection') {\n for (i = 0; i < geojson.geometry.geometries.length; i++) {\n convertFeature(features, {\n id: id,\n geometry: geojson.geometry.geometries[i],\n properties: geojson.properties\n }, options, index);\n }\n return;\n } else {\n throw new Error('Input data is not a valid GeoJSON object.');\n }\n\n features.push(createFeature(id, type, geometry, geojson.properties));\n}\n\nfunction convertPoint(coords, out) {\n out.push(projectX(coords[0]));\n out.push(projectY(coords[1]));\n out.push(0);\n}\n\nfunction convertLine(ring, out, tolerance, isPolygon) {\n var x0, y0;\n var size = 0;\n\n for (var j = 0; j < ring.length; j++) {\n var x = projectX(ring[j][0]);\n var y = projectY(ring[j][1]);\n\n out.push(x);\n out.push(y);\n out.push(0);\n\n if (j > 0) {\n if (isPolygon) {\n size += (x0 * y - x * y0) / 2; // area\n } else {\n size += Math.sqrt(Math.pow(x - x0, 2) + Math.pow(y - y0, 2)); // length\n }\n }\n x0 = x;\n y0 = y;\n }\n\n var last = out.length - 3;\n out[2] = 1;\n simplify(out, 0, last, tolerance);\n out[last + 2] = 1;\n\n out.size = Math.abs(size);\n out.start = 0;\n out.end = out.size;\n}\n\nfunction convertLines(rings, out, tolerance, isPolygon) {\n for (var i = 0; i < rings.length; i++) {\n var geom = [];\n convertLine(rings[i], geom, tolerance, isPolygon);\n out.push(geom);\n }\n}\n\nfunction projectX(x) {\n return x / 360 + 0.5;\n}\n\nfunction projectY(y) {\n var sin = Math.sin(y * Math.PI / 180);\n var y2 = 0.5 - 0.25 * Math.log((1 + sin) / (1 - sin)) / Math.PI;\n return y2 < 0 ? 0 : y2 > 1 ? 1 : y2;\n}\n","\nimport createFeature from './feature';\n\n/* clip features between two axis-parallel lines:\n * | |\n * ___|___ | /\n * / | \\____|____/\n * | |\n */\n\nexport default function clip(features, scale, k1, k2, axis, minAll, maxAll, options) {\n\n k1 /= scale;\n k2 /= scale;\n\n if (minAll >= k1 && maxAll < k2) return features; // trivial accept\n else if (maxAll < k1 || minAll >= k2) return null; // trivial reject\n\n var clipped = [];\n\n for (var i = 0; i < features.length; i++) {\n\n var feature = features[i];\n var geometry = feature.geometry;\n var type = feature.type;\n\n var min = axis === 0 ? feature.minX : feature.minY;\n var max = axis === 0 ? feature.maxX : feature.maxY;\n\n if (min >= k1 && max < k2) { // trivial accept\n clipped.push(feature);\n continue;\n } else if (max < k1 || min >= k2) { // trivial reject\n continue;\n }\n\n var newGeometry = [];\n\n if (type === 'Point' || type === 'MultiPoint') {\n clipPoints(geometry, newGeometry, k1, k2, axis);\n\n } else if (type === 'LineString') {\n clipLine(geometry, newGeometry, k1, k2, axis, false, options.lineMetrics);\n\n } else if (type === 'MultiLineString') {\n clipLines(geometry, newGeometry, k1, k2, axis, false);\n\n } else if (type === 'Polygon') {\n clipLines(geometry, newGeometry, k1, k2, axis, true);\n\n } else if (type === 'MultiPolygon') {\n for (var j = 0; j < geometry.length; j++) {\n var polygon = [];\n clipLines(geometry[j], polygon, k1, k2, axis, true);\n if (polygon.length) {\n newGeometry.push(polygon);\n }\n }\n }\n\n if (newGeometry.length) {\n if (options.lineMetrics && type === 'LineString') {\n for (j = 0; j < newGeometry.length; j++) {\n clipped.push(createFeature(feature.id, type, newGeometry[j], feature.tags));\n }\n continue;\n }\n\n if (type === 'LineString' || type === 'MultiLineString') {\n if (newGeometry.length === 1) {\n type = 'LineString';\n newGeometry = newGeometry[0];\n } else {\n type = 'MultiLineString';\n }\n }\n if (type === 'Point' || type === 'MultiPoint') {\n type = newGeometry.length === 3 ? 'Point' : 'MultiPoint';\n }\n\n clipped.push(createFeature(feature.id, type, newGeometry, feature.tags));\n }\n }\n\n return clipped.length ? clipped : null;\n}\n\nfunction clipPoints(geom, newGeom, k1, k2, axis) {\n for (var i = 0; i < geom.length; i += 3) {\n var a = geom[i + axis];\n\n if (a >= k1 && a <= k2) {\n newGeom.push(geom[i]);\n newGeom.push(geom[i + 1]);\n newGeom.push(geom[i + 2]);\n }\n }\n}\n\nfunction clipLine(geom, newGeom, k1, k2, axis, isPolygon, trackMetrics) {\n\n var slice = newSlice(geom);\n var intersect = axis === 0 ? intersectX : intersectY;\n var len = geom.start;\n var segLen, t;\n\n for (var i = 0; i < geom.length - 3; i += 3) {\n var ax = geom[i];\n var ay = geom[i + 1];\n var az = geom[i + 2];\n var bx = geom[i + 3];\n var by = geom[i + 4];\n var a = axis === 0 ? ax : ay;\n var b = axis === 0 ? bx : by;\n var exited = false;\n\n if (trackMetrics) segLen = Math.sqrt(Math.pow(ax - bx, 2) + Math.pow(ay - by, 2));\n\n if (a < k1) {\n // ---|--> | (line enters the clip region from the left)\n if (b > k1) {\n t = intersect(slice, ax, ay, bx, by, k1);\n if (trackMetrics) slice.start = len + segLen * t;\n }\n } else if (a > k2) {\n // | <--|--- (line enters the clip region from the right)\n if (b < k2) {\n t = intersect(slice, ax, ay, bx, by, k2);\n if (trackMetrics) slice.start = len + segLen * t;\n }\n } else {\n addPoint(slice, ax, ay, az);\n }\n if (b < k1 && a >= k1) {\n // <--|--- | or <--|-----|--- (line exits the clip region on the left)\n t = intersect(slice, ax, ay, bx, by, k1);\n exited = true;\n }\n if (b > k2 && a <= k2) {\n // | ---|--> or ---|-----|--> (line exits the clip region on the right)\n t = intersect(slice, ax, ay, bx, by, k2);\n exited = true;\n }\n\n if (!isPolygon && exited) {\n if (trackMetrics) slice.end = len + segLen * t;\n newGeom.push(slice);\n slice = newSlice(geom);\n }\n\n if (trackMetrics) len += segLen;\n }\n\n // add the last point\n var last = geom.length - 3;\n ax = geom[last];\n ay = geom[last + 1];\n az = geom[last + 2];\n a = axis === 0 ? ax : ay;\n if (a >= k1 && a <= k2) addPoint(slice, ax, ay, az);\n\n // close the polygon if its endpoints are not the same after clipping\n last = slice.length - 3;\n if (isPolygon && last >= 3 && (slice[last] !== slice[0] || slice[last + 1] !== slice[1])) {\n addPoint(slice, slice[0], slice[1], slice[2]);\n }\n\n // add the final slice\n if (slice.length) {\n newGeom.push(slice);\n }\n}\n\nfunction newSlice(line) {\n var slice = [];\n slice.size = line.size;\n slice.start = line.start;\n slice.end = line.end;\n return slice;\n}\n\nfunction clipLines(geom, newGeom, k1, k2, axis, isPolygon) {\n for (var i = 0; i < geom.length; i++) {\n clipLine(geom[i], newGeom, k1, k2, axis, isPolygon, false);\n }\n}\n\nfunction addPoint(out, x, y, z) {\n out.push(x);\n out.push(y);\n out.push(z);\n}\n\nfunction intersectX(out, ax, ay, bx, by, x) {\n var t = (x - ax) / (bx - ax);\n out.push(x);\n out.push(ay + (by - ay) * t);\n out.push(1);\n return t;\n}\n\nfunction intersectY(out, ax, ay, bx, by, y) {\n var t = (y - ay) / (by - ay);\n out.push(ax + (bx - ax) * t);\n out.push(y);\n out.push(1);\n return t;\n}\n","\nimport clip from './clip';\nimport createFeature from './feature';\n\nexport default function wrap(features, options) {\n var buffer = options.buffer / options.extent;\n var merged = features;\n var left = clip(features, 1, -1 - buffer, buffer, 0, -1, 2, options); // left world copy\n var right = clip(features, 1, 1 - buffer, 2 + buffer, 0, -1, 2, options); // right world copy\n\n if (left || right) {\n merged = clip(features, 1, -buffer, 1 + buffer, 0, -1, 2, options) || []; // center world copy\n\n if (left) merged = shiftFeatureCoords(left, 1).concat(merged); // merge left into center\n if (right) merged = merged.concat(shiftFeatureCoords(right, -1)); // merge right into center\n }\n\n return merged;\n}\n\nfunction shiftFeatureCoords(features, offset) {\n var newFeatures = [];\n\n for (var i = 0; i < features.length; i++) {\n var feature = features[i],\n type = feature.type;\n\n var newGeometry;\n\n if (type === 'Point' || type === 'MultiPoint' || type === 'LineString') {\n newGeometry = shiftCoords(feature.geometry, offset);\n\n } else if (type === 'MultiLineString' || type === 'Polygon') {\n newGeometry = [];\n for (var j = 0; j < feature.geometry.length; j++) {\n newGeometry.push(shiftCoords(feature.geometry[j], offset));\n }\n } else if (type === 'MultiPolygon') {\n newGeometry = [];\n for (j = 0; j < feature.geometry.length; j++) {\n var newPolygon = [];\n for (var k = 0; k < feature.geometry[j].length; k++) {\n newPolygon.push(shiftCoords(feature.geometry[j][k], offset));\n }\n newGeometry.push(newPolygon);\n }\n }\n\n newFeatures.push(createFeature(feature.id, type, newGeometry, feature.tags));\n }\n\n return newFeatures;\n}\n\nfunction shiftCoords(points, offset) {\n var newPoints = [];\n newPoints.size = points.size;\n\n if (points.start !== undefined) {\n newPoints.start = points.start;\n newPoints.end = points.end;\n }\n\n for (var i = 0; i < points.length; i += 3) {\n newPoints.push(points[i] + offset, points[i + 1], points[i + 2]);\n }\n return newPoints;\n}\n","\n// Transforms the coordinates of each feature in the given tile from\n// mercator-projected space into (extent x extent) tile space.\nexport default function transformTile(tile, extent) {\n if (tile.transformed) return tile;\n\n var z2 = 1 << tile.z,\n tx = tile.x,\n ty = tile.y,\n i, j, k;\n\n for (i = 0; i < tile.features.length; i++) {\n var feature = tile.features[i],\n geom = feature.geometry,\n type = feature.type;\n\n feature.geometry = [];\n\n if (type === 1) {\n for (j = 0; j < geom.length; j += 2) {\n feature.geometry.push(transformPoint(geom[j], geom[j + 1], extent, z2, tx, ty));\n }\n } else {\n for (j = 0; j < geom.length; j++) {\n var ring = [];\n for (k = 0; k < geom[j].length; k += 2) {\n ring.push(transformPoint(geom[j][k], geom[j][k + 1], extent, z2, tx, ty));\n }\n feature.geometry.push(ring);\n }\n }\n }\n\n tile.transformed = true;\n\n return tile;\n}\n\nfunction transformPoint(x, y, extent, z2, tx, ty) {\n return [\n Math.round(extent * (x * z2 - tx)),\n Math.round(extent * (y * z2 - ty))];\n}\n","\nexport default function createTile(features, z, tx, ty, options) {\n var tolerance = z === options.maxZoom ? 0 : options.tolerance / ((1 << z) * options.extent);\n var tile = {\n features: [],\n numPoints: 0,\n numSimplified: 0,\n numFeatures: 0,\n source: null,\n x: tx,\n y: ty,\n z: z,\n transformed: false,\n minX: 2,\n minY: 1,\n maxX: -1,\n maxY: 0\n };\n for (var i = 0; i < features.length; i++) {\n tile.numFeatures++;\n addFeature(tile, features[i], tolerance, options);\n\n var minX = features[i].minX;\n var minY = features[i].minY;\n var maxX = features[i].maxX;\n var maxY = features[i].maxY;\n\n if (minX < tile.minX) tile.minX = minX;\n if (minY < tile.minY) tile.minY = minY;\n if (maxX > tile.maxX) tile.maxX = maxX;\n if (maxY > tile.maxY) tile.maxY = maxY;\n }\n return tile;\n}\n\nfunction addFeature(tile, feature, tolerance, options) {\n\n var geom = feature.geometry,\n type = feature.type,\n simplified = [];\n\n if (type === 'Point' || type === 'MultiPoint') {\n for (var i = 0; i < geom.length; i += 3) {\n simplified.push(geom[i]);\n simplified.push(geom[i + 1]);\n tile.numPoints++;\n tile.numSimplified++;\n }\n\n } else if (type === 'LineString') {\n addLine(simplified, geom, tile, tolerance, false, false);\n\n } else if (type === 'MultiLineString' || type === 'Polygon') {\n for (i = 0; i < geom.length; i++) {\n addLine(simplified, geom[i], tile, tolerance, type === 'Polygon', i === 0);\n }\n\n } else if (type === 'MultiPolygon') {\n\n for (var k = 0; k < geom.length; k++) {\n var polygon = geom[k];\n for (i = 0; i < polygon.length; i++) {\n addLine(simplified, polygon[i], tile, tolerance, true, i === 0);\n }\n }\n }\n\n if (simplified.length) {\n var tags = feature.tags || null;\n if (type === 'LineString' && options.lineMetrics) {\n tags = {};\n for (var key in feature.tags) tags[key] = feature.tags[key];\n tags['mapbox_clip_start'] = geom.start / geom.size;\n tags['mapbox_clip_end'] = geom.end / geom.size;\n }\n var tileFeature = {\n geometry: simplified,\n type: type === 'Polygon' || type === 'MultiPolygon' ? 3 :\n type === 'LineString' || type === 'MultiLineString' ? 2 : 1,\n tags: tags\n };\n if (feature.id !== null) {\n tileFeature.id = feature.id;\n }\n tile.features.push(tileFeature);\n }\n}\n\nfunction addLine(result, geom, tile, tolerance, isPolygon, isOuter) {\n var sqTolerance = tolerance * tolerance;\n\n if (tolerance > 0 && (geom.size < (isPolygon ? sqTolerance : tolerance))) {\n tile.numPoints += geom.length / 3;\n return;\n }\n\n var ring = [];\n\n for (var i = 0; i < geom.length; i += 3) {\n if (tolerance === 0 || geom[i + 2] > sqTolerance) {\n tile.numSimplified++;\n ring.push(geom[i]);\n ring.push(geom[i + 1]);\n }\n tile.numPoints++;\n }\n\n if (isPolygon) rewind(ring, isOuter);\n\n result.push(ring);\n}\n\nfunction rewind(ring, clockwise) {\n var area = 0;\n for (var i = 0, len = ring.length, j = len - 2; i < len; j = i, i += 2) {\n area += (ring[i] - ring[j]) * (ring[i + 1] + ring[j + 1]);\n }\n if (area > 0 === clockwise) {\n for (i = 0, len = ring.length; i < len / 2; i += 2) {\n var x = ring[i];\n var y = ring[i + 1];\n ring[i] = ring[len - 2 - i];\n ring[i + 1] = ring[len - 1 - i];\n ring[len - 2 - i] = x;\n ring[len - 1 - i] = y;\n }\n }\n}\n","\nimport convert from './convert'; // GeoJSON conversion and preprocessing\nimport clip from './clip'; // stripe clipping algorithm\nimport wrap from './wrap'; // date line processing\nimport transform from './transform'; // coordinate transformation\nimport createTile from './tile'; // final simplified tile generation\n\nexport default function geojsonvt(data, options) {\n return new GeoJSONVT(data, options);\n}\n\nfunction GeoJSONVT(data, options) {\n options = this.options = extend(Object.create(this.options), options);\n\n var debug = options.debug;\n\n if (debug) console.time('preprocess data');\n\n if (options.maxZoom < 0 || options.maxZoom > 24) throw new Error('maxZoom should be in the 0-24 range');\n if (options.promoteId && options.generateId) throw new Error('promoteId and generateId cannot be used together.');\n\n var features = convert(data, options);\n\n this.tiles = {};\n this.tileCoords = [];\n\n if (debug) {\n console.timeEnd('preprocess data');\n console.log('index: maxZoom: %d, maxPoints: %d', options.indexMaxZoom, options.indexMaxPoints);\n console.time('generate tiles');\n this.stats = {};\n this.total = 0;\n }\n\n features = wrap(features, options);\n\n // start slicing from the top tile down\n if (features.length) this.splitTile(features, 0, 0, 0);\n\n if (debug) {\n if (features.length) console.log('features: %d, points: %d', this.tiles[0].numFeatures, this.tiles[0].numPoints);\n console.timeEnd('generate tiles');\n console.log('tiles generated:', this.total, JSON.stringify(this.stats));\n }\n}\n\nGeoJSONVT.prototype.options = {\n maxZoom: 14, // max zoom to preserve detail on\n indexMaxZoom: 5, // max zoom in the tile index\n indexMaxPoints: 100000, // max number of points per tile in the tile index\n tolerance: 3, // simplification tolerance (higher means simpler)\n extent: 4096, // tile extent\n buffer: 64, // tile buffer on each side\n lineMetrics: false, // whether to calculate line metrics\n promoteId: null, // name of a feature property to be promoted to feature.id\n generateId: false, // whether to generate feature ids. Cannot be used with promoteId\n debug: 0 // logging level (0, 1 or 2)\n};\n\nGeoJSONVT.prototype.splitTile = function (features, z, x, y, cz, cx, cy) {\n\n var stack = [features, z, x, y],\n options = this.options,\n debug = options.debug;\n\n // avoid recursion by using a processing queue\n while (stack.length) {\n y = stack.pop();\n x = stack.pop();\n z = stack.pop();\n features = stack.pop();\n\n var z2 = 1 << z,\n id = toID(z, x, y),\n tile = this.tiles[id];\n\n if (!tile) {\n if (debug > 1) console.time('creation');\n\n tile = this.tiles[id] = createTile(features, z, x, y, options);\n this.tileCoords.push({z: z, x: x, y: y});\n\n if (debug) {\n if (debug > 1) {\n console.log('tile z%d-%d-%d (features: %d, points: %d, simplified: %d)',\n z, x, y, tile.numFeatures, tile.numPoints, tile.numSimplified);\n console.timeEnd('creation');\n }\n var key = 'z' + z;\n this.stats[key] = (this.stats[key] || 0) + 1;\n this.total++;\n }\n }\n\n // save reference to original geometry in tile so that we can drill down later if we stop now\n tile.source = features;\n\n // if it's the first-pass tiling\n if (!cz) {\n // stop tiling if we reached max zoom, or if the tile is too simple\n if (z === options.indexMaxZoom || tile.numPoints <= options.indexMaxPoints) continue;\n\n // if a drilldown to a specific tile\n } else {\n // stop tiling if we reached base zoom or our target tile zoom\n if (z === options.maxZoom || z === cz) continue;\n\n // stop tiling if it's not an ancestor of the target tile\n var m = 1 << (cz - z);\n if (x !== Math.floor(cx / m) || y !== Math.floor(cy / m)) continue;\n }\n\n // if we slice further down, no need to keep source geometry\n tile.source = null;\n\n if (features.length === 0) continue;\n\n if (debug > 1) console.time('clipping');\n\n // values we'll use for clipping\n var k1 = 0.5 * options.buffer / options.extent,\n k2 = 0.5 - k1,\n k3 = 0.5 + k1,\n k4 = 1 + k1,\n tl, bl, tr, br, left, right;\n\n tl = bl = tr = br = null;\n\n left = clip(features, z2, x - k1, x + k3, 0, tile.minX, tile.maxX, options);\n right = clip(features, z2, x + k2, x + k4, 0, tile.minX, tile.maxX, options);\n features = null;\n\n if (left) {\n tl = clip(left, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);\n bl = clip(left, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);\n left = null;\n }\n\n if (right) {\n tr = clip(right, z2, y - k1, y + k3, 1, tile.minY, tile.maxY, options);\n br = clip(right, z2, y + k2, y + k4, 1, tile.minY, tile.maxY, options);\n right = null;\n }\n\n if (debug > 1) console.timeEnd('clipping');\n\n stack.push(tl || [], z + 1, x * 2, y * 2);\n stack.push(bl || [], z + 1, x * 2, y * 2 + 1);\n stack.push(tr || [], z + 1, x * 2 + 1, y * 2);\n stack.push(br || [], z + 1, x * 2 + 1, y * 2 + 1);\n }\n};\n\nGeoJSONVT.prototype.getTile = function (z, x, y) {\n var options = this.options,\n extent = options.extent,\n debug = options.debug;\n\n if (z < 0 || z > 24) return null;\n\n var z2 = 1 << z;\n x = ((x % z2) + z2) % z2; // wrap tile x coordinate\n\n var id = toID(z, x, y);\n if (this.tiles[id]) return transform(this.tiles[id], extent);\n\n if (debug > 1) console.log('drilling down to z%d-%d-%d', z, x, y);\n\n var z0 = z,\n x0 = x,\n y0 = y,\n parent;\n\n while (!parent && z0 > 0) {\n z0--;\n x0 = Math.floor(x0 / 2);\n y0 = Math.floor(y0 / 2);\n parent = this.tiles[toID(z0, x0, y0)];\n }\n\n if (!parent || !parent.source) return null;\n\n // if we found a parent tile containing the original geometry, we can drill down from it\n if (debug > 1) console.log('found parent tile z%d-%d-%d', z0, x0, y0);\n\n if (debug > 1) console.time('drilling down');\n this.splitTile(parent.source, z0, x0, y0, z, x, y);\n if (debug > 1) console.timeEnd('drilling down');\n\n return this.tiles[id] ? transform(this.tiles[id], extent) : null;\n};\n\nfunction toID(z, x, y) {\n return (((1 << z) * y + x) * 32) + z;\n}\n\nfunction extend(dest, src) {\n for (var i in src) dest[i] = src[i];\n return dest;\n}\n","// @flow\n\nimport {getJSON} from '../util/ajax';\n\nimport {RequestPerformance} from '../util/performance';\nimport rewind from '@mapbox/geojson-rewind';\nimport GeoJSONWrapper from './geojson_wrapper';\nimport vtpbf from 'vt-pbf';\nimport Supercluster from 'supercluster';\nimport geojsonvt from 'geojson-vt';\nimport assert from 'assert';\nimport VectorTileWorkerSource from './vector_tile_worker_source';\nimport {createExpression} from '../style-spec/expression';\n\nimport type {\n RequestedTileParameters,\n WorkerTileParameters,\n WorkerTileCallback,\n} from '../source/worker_source';\n\nimport type Actor from '../util/actor';\nimport type StyleLayerIndex from '../style/style_layer_index';\n\nimport type {LoadVectorDataCallback} from './vector_tile_worker_source';\nimport type {RequestParameters, ResponseCallback} from '../util/ajax';\nimport type {Callback} from '../types/callback';\nimport type {GeoJSONFeature} from '@mapbox/geojson-types';\n\nexport type LoadGeoJSONParameters = {\n request?: RequestParameters,\n data?: string,\n source: string,\n cluster: boolean,\n superclusterOptions?: Object,\n geojsonVtOptions?: Object,\n clusterProperties?: Object,\n filter?: Array<mixed>\n};\n\nexport type LoadGeoJSON = (params: LoadGeoJSONParameters, callback: ResponseCallback<Object>) => void;\n\nexport interface GeoJSONIndex {\n getTile(z: number, x: number, y: number): Object;\n\n // supercluster methods\n getClusterExpansionZoom(clusterId: number): number;\n getChildren(clusterId: number): Array<GeoJSONFeature>;\n getLeaves(clusterId: number, limit: number, offset: number): Array<GeoJSONFeature>;\n}\n\nfunction loadGeoJSONTile(params: RequestedTileParameters, callback: LoadVectorDataCallback) {\n const canonical = params.tileID.canonical;\n\n if (!this._geoJSONIndex) {\n return callback(null, null); // we couldn't load the file\n }\n\n const geoJSONTile = this._geoJSONIndex.getTile(canonical.z, canonical.x, canonical.y);\n if (!geoJSONTile) {\n return callback(null, null); // nothing in the given tile\n }\n\n const geojsonWrapper = new GeoJSONWrapper(geoJSONTile.features);\n\n // Encode the geojson-vt tile into binary vector tile form. This\n // is a convenience that allows `FeatureIndex` to operate the same way\n // across `VectorTileSource` and `GeoJSONSource` data.\n let pbf = vtpbf(geojsonWrapper);\n if (pbf.byteOffset !== 0 || pbf.byteLength !== pbf.buffer.byteLength) {\n // Compatibility with node Buffer (https://github.com/mapbox/pbf/issues/35)\n pbf = new Uint8Array(pbf);\n }\n\n callback(null, {\n vectorTile: geojsonWrapper,\n rawData: pbf.buffer\n });\n}\n\nexport type SourceState =\n | 'Idle' // Source empty or data loaded\n | 'Coalescing' // Data finished loading, but discard 'loadData' messages until receiving 'coalesced'\n | 'NeedsLoadData'; // 'loadData' received while coalescing, trigger one more 'loadData' on receiving 'coalesced'\n\n/**\n * The {@link WorkerSource} implementation that supports {@link GeoJSONSource}.\n * This class is designed to be easily reused to support custom source types\n * for data formats that can be parsed/converted into an in-memory GeoJSON\n * representation. To do so, create it with\n * `new GeoJSONWorkerSource(actor, layerIndex, customLoadGeoJSONFunction)`.\n * For a full example, see [mapbox-gl-topojson](https://github.com/developmentseed/mapbox-gl-topojson).\n *\n * @private\n */\nclass GeoJSONWorkerSource extends VectorTileWorkerSource {\n loadGeoJSON: LoadGeoJSON;\n _state: SourceState;\n _pendingCallback: Callback<{\n resourceTiming?: {[_: string]: Array<PerformanceResourceTiming>},\n abandoned?: boolean }>;\n _pendingLoadDataParams: LoadGeoJSONParameters;\n _geoJSONIndex: GeoJSONIndex\n\n /**\n * @param [loadGeoJSON] Optional method for custom loading/parsing of\n * GeoJSON based on parameters passed from the main-thread Source.\n * See {@link GeoJSONWorkerSource#loadGeoJSON}.\n * @private\n */\n constructor(actor: Actor, layerIndex: StyleLayerIndex, availableImages: Array<string>, isSpriteLoaded: boolean, loadGeoJSON: ?LoadGeoJSON) {\n super(actor, layerIndex, availableImages, isSpriteLoaded, loadGeoJSONTile);\n if (loadGeoJSON) {\n this.loadGeoJSON = loadGeoJSON;\n }\n }\n\n /**\n * Fetches (if appropriate), parses, and index geojson data into tiles. This\n * preparatory method must be called before {@link GeoJSONWorkerSource#loadTile}\n * can correctly serve up tiles.\n *\n * Defers to {@link GeoJSONWorkerSource#loadGeoJSON} for the fetching/parsing,\n * expecting `callback(error, data)` to be called with either an error or a\n * parsed GeoJSON object.\n *\n * When `loadData` requests come in faster than they can be processed,\n * they are coalesced into a single request using the latest data.\n * See {@link GeoJSONWorkerSource#coalesce}\n *\n * @param params\n * @param callback\n * @private\n */\n loadData(params: LoadGeoJSONParameters, callback: Callback<{\n resourceTiming?: {[_: string]: Array<PerformanceResourceTiming>},\n abandoned?: boolean }>) {\n if (this._pendingCallback) {\n // Tell the foreground the previous call has been abandoned\n this._pendingCallback(null, {abandoned: true});\n }\n this._pendingCallback = callback;\n this._pendingLoadDataParams = params;\n\n if (this._state &&\n this._state !== 'Idle') {\n this._state = 'NeedsLoadData';\n } else {\n this._state = 'Coalescing';\n this._loadData();\n }\n }\n\n /**\n * Internal implementation: called directly by `loadData`\n * or by `coalesce` using stored parameters.\n */\n _loadData() {\n if (!this._pendingCallback || !this._pendingLoadDataParams) {\n assert(false);\n return;\n }\n const callback = this._pendingCallback;\n const params = this._pendingLoadDataParams;\n delete this._pendingCallback;\n delete this._pendingLoadDataParams;\n\n const perf = (params && params.request && params.request.collectResourceTiming) ?\n new RequestPerformance(params.request) : false;\n\n this.loadGeoJSON(params, (err: ?Error, data: ?Object) => {\n if (err || !data) {\n return callback(err);\n } else if (typeof data !== 'object') {\n return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`));\n } else {\n rewind(data, true);\n\n try {\n if (params.filter) {\n const compiled = createExpression(params.filter, {type: 'boolean', 'property-type': 'data-driven', overridable: false, transition: false});\n if (compiled.result === 'error')\n throw new Error(compiled.value.map(err => `${err.key}: ${err.message}`).join(', '));\n\n const features = data.features.filter(feature => compiled.value.evaluate({zoom: 0}, feature));\n data = {type: 'FeatureCollection', features};\n }\n\n this._geoJSONIndex = params.cluster ?\n new Supercluster(getSuperclusterOptions(params)).load(data.features) :\n geojsonvt(data, params.geojsonVtOptions);\n } catch (err) {\n return callback(err);\n }\n\n this.loaded = {};\n\n const result = {};\n if (perf) {\n const resourceTimingData = perf.finish();\n // it's necessary to eval the result of getEntriesByName() here via parse/stringify\n // late evaluation in the main thread causes TypeError: illegal invocation\n if (resourceTimingData) {\n result.resourceTiming = {};\n result.resourceTiming[params.source] = JSON.parse(JSON.stringify(resourceTimingData));\n }\n }\n callback(null, result);\n }\n });\n }\n\n /**\n * While processing `loadData`, we coalesce all further\n * `loadData` messages into a single call to _loadData\n * that will happen once we've finished processing the\n * first message. {@link GeoJSONSource#_updateWorkerData}\n * is responsible for sending us the `coalesce` message\n * at the time it receives a response from `loadData`\n *\n * State: Idle\n * ↑ |\n * 'coalesce' 'loadData'\n * | (triggers load)\n * | ↓\n * State: Coalescing\n * ↑ |\n * (triggers load) |\n * 'coalesce' 'loadData'\n * | ↓\n * State: NeedsLoadData\n */\n coalesce() {\n if (this._state === 'Coalescing') {\n this._state = 'Idle';\n } else if (this._state === 'NeedsLoadData') {\n this._state = 'Coalescing';\n this._loadData();\n }\n }\n\n /**\n * Implements {@link WorkerSource#reloadTile}.\n *\n * If the tile is loaded, uses the implementation in VectorTileWorkerSource.\n * Otherwise, such as after a setData() call, we load the tile fresh.\n *\n * @param params\n * @param params.uid The UID for this tile.\n * @private\n */\n reloadTile(params: WorkerTileParameters, callback: WorkerTileCallback) {\n const loaded = this.loaded,\n uid = params.uid;\n\n if (loaded && loaded[uid]) {\n return super.reloadTile(params, callback);\n } else {\n return this.loadTile(params, callback);\n }\n }\n\n /**\n * Fetch and parse GeoJSON according to the given params. Calls `callback`\n * with `(err, data)`, where `data` is a parsed GeoJSON object.\n *\n * GeoJSON is loaded and parsed from `params.url` if it exists, or else\n * expected as a literal (string or object) `params.data`.\n *\n * @param params\n * @param [params.url] A URL to the remote GeoJSON data.\n * @param [params.data] Literal GeoJSON data. Must be provided if `params.url` is not.\n * @private\n */\n loadGeoJSON(params: LoadGeoJSONParameters, callback: ResponseCallback<Object>) {\n // Because of same origin issues, urls must either include an explicit\n // origin or absolute path.\n // ie: /foo/bar.json or http://example.com/bar.json\n // but not ../foo/bar.json\n if (params.request) {\n getJSON(params.request, callback);\n } else if (typeof params.data === 'string') {\n try {\n return callback(null, JSON.parse(params.data));\n } catch (e) {\n return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`));\n }\n } else {\n return callback(new Error(`Input data given to '${params.source}' is not a valid GeoJSON object.`));\n }\n }\n\n removeSource(params: {source: string}, callback: Callback<mixed>) {\n if (this._pendingCallback) {\n // Don't leak callbacks\n this._pendingCallback(null, {abandoned: true});\n }\n callback();\n }\n\n getClusterExpansionZoom(params: {clusterId: number}, callback: Callback<number>) {\n try {\n callback(null, this._geoJSONIndex.getClusterExpansionZoom(params.clusterId));\n } catch (e) {\n callback(e);\n }\n }\n\n getClusterChildren(params: {clusterId: number}, callback: Callback<Array<GeoJSONFeature>>) {\n try {\n callback(null, this._geoJSONIndex.getChildren(params.clusterId));\n } catch (e) {\n callback(e);\n }\n }\n\n getClusterLeaves(params: {clusterId: number, limit: number, offset: number}, callback: Callback<Array<GeoJSONFeature>>) {\n try {\n callback(null, this._geoJSONIndex.getLeaves(params.clusterId, params.limit, params.offset));\n } catch (e) {\n callback(e);\n }\n }\n}\n\nfunction getSuperclusterOptions({superclusterOptions, clusterProperties}) {\n if (!clusterProperties || !superclusterOptions) return superclusterOptions;\n\n const mapExpressions = {};\n const reduceExpressions = {};\n const globals = {accumulated: null, zoom: 0};\n const feature = {properties: null};\n const propertyNames = Object.keys(clusterProperties);\n\n for (const key of propertyNames) {\n const [operator, mapExpression] = clusterProperties[key];\n\n const mapExpressionParsed = createExpression(mapExpression);\n const reduceExpressionParsed = createExpression(\n typeof operator === 'string' ? [operator, ['accumulated'], ['get', key]] : operator);\n\n assert(mapExpressionParsed.result === 'success');\n assert(reduceExpressionParsed.result === 'success');\n\n mapExpressions[key] = mapExpressionParsed.value;\n reduceExpressions[key] = reduceExpressionParsed.value;\n }\n\n superclusterOptions.map = (pointProperties) => {\n feature.properties = pointProperties;\n const properties = {};\n for (const key of propertyNames) {\n properties[key] = mapExpressions[key].evaluate(globals, feature);\n }\n return properties;\n };\n superclusterOptions.reduce = (accumulated, clusterProperties) => {\n feature.properties = clusterProperties;\n for (const key of propertyNames) {\n globals.accumulated = accumulated[key];\n accumulated[key] = reduceExpressions[key].evaluate(globals, feature);\n }\n };\n\n return superclusterOptions;\n}\n\nexport default GeoJSONWorkerSource;\n","// @flow\n\nimport Actor from '../util/actor';\n\nimport StyleLayerIndex from '../style/style_layer_index';\nimport VectorTileWorkerSource from './vector_tile_worker_source';\nimport RasterDEMTileWorkerSource from './raster_dem_tile_worker_source';\nimport GeoJSONWorkerSource from './geojson_worker_source';\nimport assert from 'assert';\nimport {plugin as globalRTLTextPlugin} from './rtl_text_plugin';\nimport {enforceCacheSizeLimit} from '../util/tile_request_cache';\nimport {extend} from '../util/util';\nimport {PerformanceUtils} from '../util/performance';\nimport {Event} from '../util/evented';\n\nimport type {\n WorkerSource,\n WorkerTileParameters,\n WorkerDEMTileParameters,\n WorkerTileCallback,\n WorkerDEMTileCallback,\n TileParameters\n} from '../source/worker_source';\n\nimport type {WorkerGlobalScopeInterface} from '../util/web_worker';\nimport type {Callback} from '../types/callback';\nimport type {LayerSpecification} from '../style-spec/types';\nimport type {PluginState} from './rtl_text_plugin';\n\n/**\n * @private\n */\nexport default class Worker {\n self: WorkerGlobalScopeInterface;\n actor: Actor;\n layerIndexes: {[_: string]: StyleLayerIndex };\n availableImages: {[_: string]: Array<string> };\n workerSourceTypes: {[_: string]: Class<WorkerSource> };\n workerSources: {[_: string]: {[_: string]: {[_: string]: WorkerSource } } };\n demWorkerSources: {[_: string]: {[_: string]: RasterDEMTileWorkerSource } };\n isSpriteLoaded: boolean;\n referrer: ?string;\n terrain: ?boolean;\n\n constructor(self: WorkerGlobalScopeInterface) {\n PerformanceUtils.measure('workerEvaluateScript');\n this.self = self;\n this.actor = new Actor(self, this);\n\n this.layerIndexes = {};\n this.availableImages = {};\n this.isSpriteLoaded = false;\n\n this.workerSourceTypes = {\n vector: VectorTileWorkerSource,\n geojson: GeoJSONWorkerSource\n };\n\n // [mapId][sourceType][sourceName] => worker source instance\n this.workerSources = {};\n this.demWorkerSources = {};\n\n this.self.registerWorkerSource = (name: string, WorkerSource: Class<WorkerSource>) => {\n if (this.workerSourceTypes[name]) {\n throw new Error(`Worker source with name \"${name}\" already registered.`);\n }\n this.workerSourceTypes[name] = WorkerSource;\n };\n\n // This is invoked by the RTL text plugin when the download via the `importScripts` call has finished, and the code has been parsed.\n this.self.registerRTLTextPlugin = (rtlTextPlugin: {applyArabicShaping: Function, processBidirectionalText: Function, processStyledBidirectionalText?: Function}) => {\n if (globalRTLTextPlugin.isParsed()) {\n throw new Error('RTL text plugin already registered.');\n }\n globalRTLTextPlugin['applyArabicShaping'] = rtlTextPlugin.applyArabicShaping;\n globalRTLTextPlugin['processBidirectionalText'] = rtlTextPlugin.processBidirectionalText;\n globalRTLTextPlugin['processStyledBidirectionalText'] = rtlTextPlugin.processStyledBidirectionalText;\n };\n }\n\n checkIfReady(mapID: string, unused: mixed, callback: WorkerTileCallback) {\n // noop, used to check if a worker is fully set up and ready to receive messages\n callback();\n }\n\n setReferrer(mapID: string, referrer: string) {\n this.referrer = referrer;\n }\n\n spriteLoaded(mapId: string, bool: boolean) {\n this.isSpriteLoaded = bool;\n for (const workerSource in this.workerSources[mapId]) {\n const ws = this.workerSources[mapId][workerSource];\n for (const source in ws) {\n if (ws[source] instanceof VectorTileWorkerSource) {\n ws[source].isSpriteLoaded = bool;\n ws[source].fire(new Event('isSpriteLoaded'));\n }\n }\n }\n }\n\n setImages(mapId: string, images: Array<string>, callback: WorkerTileCallback) {\n this.availableImages[mapId] = images;\n for (const workerSource in this.workerSources[mapId]) {\n const ws = this.workerSources[mapId][workerSource];\n for (const source in ws) {\n ws[source].availableImages = images;\n }\n }\n callback();\n }\n\n enableTerrain(mapId: string, enable: boolean, callback: WorkerTileCallback) {\n this.terrain = enable;\n callback();\n }\n\n setLayers(mapId: string, layers: Array<LayerSpecification>, callback: WorkerTileCallback) {\n this.getLayerIndex(mapId).replace(layers);\n callback();\n }\n\n updateLayers(mapId: string, params: {layers: Array<LayerSpecification>, removedIds: Array<string>}, callback: WorkerTileCallback) {\n this.getLayerIndex(mapId).update(params.layers, params.removedIds);\n callback();\n }\n\n loadTile(mapId: string, params: WorkerTileParameters & {type: string}, callback: WorkerTileCallback) {\n assert(params.type);\n const p = this.enableTerrain ? extend({enableTerrain: this.terrain}, params) : params;\n this.getWorkerSource(mapId, params.type, params.source).loadTile(p, callback);\n }\n\n loadDEMTile(mapId: string, params: WorkerDEMTileParameters, callback: WorkerDEMTileCallback) {\n const p = this.enableTerrain ? extend({buildQuadTree: this.terrain}, params) : params;\n this.getDEMWorkerSource(mapId, params.source).loadTile(p, callback);\n }\n\n reloadTile(mapId: string, params: WorkerTileParameters & {type: string}, callback: WorkerTileCallback) {\n assert(params.type);\n const p = this.enableTerrain ? extend({enableTerrain: this.terrain}, params) : params;\n this.getWorkerSource(mapId, params.type, params.source).reloadTile(p, callback);\n }\n\n abortTile(mapId: string, params: TileParameters & {type: string}, callback: WorkerTileCallback) {\n assert(params.type);\n this.getWorkerSource(mapId, params.type, params.source).abortTile(params, callback);\n }\n\n removeTile(mapId: string, params: TileParameters & {type: string}, callback: WorkerTileCallback) {\n assert(params.type);\n this.getWorkerSource(mapId, params.type, params.source).removeTile(params, callback);\n }\n\n removeSource(mapId: string, params: {source: string} & {type: string}, callback: WorkerTileCallback) {\n assert(params.type);\n assert(params.source);\n\n if (!this.workerSources[mapId] ||\n !this.workerSources[mapId][params.type] ||\n !this.workerSources[mapId][params.type][params.source]) {\n return;\n }\n\n const worker = this.workerSources[mapId][params.type][params.source];\n delete this.workerSources[mapId][params.type][params.source];\n\n if (worker.removeSource !== undefined) {\n worker.removeSource(params, callback);\n } else {\n callback();\n }\n }\n\n /**\n * Load a {@link WorkerSource} script at params.url. The script is run\n * (using importScripts) with `registerWorkerSource` in scope, which is a\n * function taking `(name, workerSourceObject)`.\n * @private\n */\n loadWorkerSource(map: string, params: { url: string }, callback: Callback<void>) {\n try {\n this.self.importScripts(params.url);\n callback();\n } catch (e) {\n callback(e.toString());\n }\n }\n\n syncRTLPluginState(map: string, state: PluginState, callback: Callback<boolean>) {\n try {\n globalRTLTextPlugin.setState(state);\n const pluginURL = globalRTLTextPlugin.getPluginURL();\n if (\n globalRTLTextPlugin.isLoaded() &&\n !globalRTLTextPlugin.isParsed() &&\n pluginURL != null // Not possible when `isLoaded` is true, but keeps flow happy\n ) {\n this.self.importScripts(pluginURL);\n const complete = globalRTLTextPlugin.isParsed();\n const error = complete ? undefined : new Error(`RTL Text Plugin failed to import scripts from ${pluginURL}`);\n callback(error, complete);\n }\n } catch (e) {\n callback(e.toString());\n }\n }\n\n getAvailableImages(mapId: string) {\n let availableImages = this.availableImages[mapId];\n\n if (!availableImages) {\n availableImages = [];\n }\n\n return availableImages;\n }\n\n getLayerIndex(mapId: string) {\n let layerIndexes = this.layerIndexes[mapId];\n if (!layerIndexes) {\n layerIndexes = this.layerIndexes[mapId] = new StyleLayerIndex();\n }\n return layerIndexes;\n }\n\n getWorkerSource(mapId: string, type: string, source: string) {\n if (!this.workerSources[mapId])\n this.workerSources[mapId] = {};\n if (!this.workerSources[mapId][type])\n this.workerSources[mapId][type] = {};\n\n if (!this.workerSources[mapId][type][source]) {\n // use a wrapped actor so that we can attach a target mapId param\n // to any messages invoked by the WorkerSource\n const actor = {\n send: (type, data, callback, mustQueue, _, metadata) => {\n this.actor.send(type, data, callback, mapId, mustQueue, metadata);\n },\n scheduler: this.actor.scheduler\n };\n this.workerSources[mapId][type][source] = new (this.workerSourceTypes[type]: any)((actor: any), this.getLayerIndex(mapId), this.getAvailableImages(mapId), this.isSpriteLoaded);\n }\n\n return this.workerSources[mapId][type][source];\n }\n\n getDEMWorkerSource(mapId: string, source: string) {\n if (!this.demWorkerSources[mapId])\n this.demWorkerSources[mapId] = {};\n\n if (!this.demWorkerSources[mapId][source]) {\n this.demWorkerSources[mapId][source] = new RasterDEMTileWorkerSource();\n }\n\n return this.demWorkerSources[mapId][source];\n }\n\n enforceCacheSizeLimit(mapId: string, limit: number) {\n enforceCacheSizeLimit(limit);\n }\n\n getWorkerPerformanceMetrics(mapId: string, params: any, callback: (error: ?Error, result: ?Object) => void) {\n callback(undefined, PerformanceUtils.getWorkerPerformanceMetrics());\n }\n}\n\n/* global self, WorkerGlobalScope */\nif (typeof WorkerGlobalScope !== 'undefined' &&\n typeof self !== 'undefined' &&\n self instanceof WorkerGlobalScope) {\n self.worker = new Worker(self);\n}\n","'use strict';\n\nexports.supported = isSupported;\nexports.notSupportedReason = notSupportedReason;\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 if (!isNotIE()) return 'insufficient ECMAScript 6 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 var canvas = document.createElement('canvas');\n canvas.width = canvas.height = 1;\n var context = canvas.getContext('2d');\n if (!context) {\n return false;\n }\n var 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 return (\n canvas.getContext('webgl', attributes) ||\n canvas.getContext('experimental-webgl', attributes)\n );\n}\n\nfunction isWebGLSupported(failIfMajorPerformanceCaveat) {\n var 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 var shader;\n try {\n shader = gl.createShader(gl.VERTEX_SHADER);\n } catch (e) {\n // some older browsers throw an exception that `createShader` is not defined\n // so handle this separately from the case where browsers block `createShader`\n // for security reasons\n return false;\n }\n\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\nfunction isNotIE() {\n return !document.documentMode;\n}\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;\nconst selectProp = docStyle && docStyle.userSelect !== undefined ? 'userSelect' : 'WebkitUserSelect';\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\nDOM.setTransform = function(el: HTMLElement, value: string) {\n el.style.transform = 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\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<string>, 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<string> {\n return Object.keys(this.images);\n }\n\n getImages(ids: Array<string>, 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<string>, 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<string>) {\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","// @flow\n\nimport styleSpec from '../style-spec/reference/latest';\n\nimport {endsWith, extend, degToRad} 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\nexport type LightPosition = {\n x: number,\n y: number,\n z: number,\n azimuthal: number,\n polar: number,\n};\n\n/**\n * Converts spherical coordinates to cartesian LightPosition coordinates.\n *\n * @private\n * @param spherical Spherical coordinates, in [radial, azimuthal, polar]\n * @return LightPosition cartesian coordinates\n */\nexport function sphericalToCartesian([r, azimuthal, polar]: [number, number, number]): LightPosition {\n // We abstract \"north\"/\"up\" (compass-wise) to be 0° when really this is 90° (π/2):\n // correct for that here\n const a = degToRad(azimuthal + 90), p = degToRad(polar);\n\n return {\n x: r * Math.cos(a) * Math.sin(p),\n y: r * Math.sin(a) * Math.sin(p),\n z: r * Math.cos(p),\n azimuthal, polar\n };\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 azimuthal: interpolate(a.azimuthal, b.azimuthal, t),\n polar: interpolate(a.polar, b.polar, t),\n };\n }\n}\n\ntype Props = {|\n \"anchor\": DataConstantProperty<\"map\" | \"viewport\">,\n \"position\": LightPositionProperty,\n \"color\": DataConstantProperty<Color>,\n \"intensity\": DataConstantProperty<number>,\n|};\n\nconst properties: Properties<Props> = 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<Props>;\n _transitioning: Transitioning<Props>;\n properties: PossiblyEvaluated<Props>;\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 styleSpec from '../style-spec/reference/latest';\nimport {endsWith} from '../util/util';\nimport {Evented} from '../util/evented';\nimport {Properties, Transitionable, Transitioning, PossiblyEvaluated, DataConstantProperty} from './properties';\n\nimport type EvaluationParameters from './evaluation_parameters';\nimport type {TransitionParameters} from './properties';\nimport type {TerrainSpecification} from '../style-spec/types';\n\ntype Props = {|\n \"source\": DataConstantProperty<string>,\n \"exaggeration\": DataConstantProperty<number>,\n|};\n\nconst properties: Properties<Props> = new Properties({\n \"source\": new DataConstantProperty(styleSpec.terrain.source),\n \"exaggeration\": new DataConstantProperty(styleSpec.terrain.exaggeration),\n});\n\nconst TRANSITION_SUFFIX = '-transition';\n\nclass Terrain extends Evented {\n _transitionable: Transitionable<Props>;\n _transitioning: Transitioning<Props>;\n properties: PossiblyEvaluated<Props>;\n\n constructor(terrainOptions: TerrainSpecification) {\n super();\n this._transitionable = new Transitionable(properties);\n this.set(terrainOptions);\n this._transitioning = this._transitionable.untransitioned();\n }\n\n get() {\n return this._transitionable.serialize();\n }\n\n set(terrain: TerrainSpecification) {\n for (const name in terrain) {\n const value = terrain[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\nexport default Terrain;\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<number>} 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<number>, 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<number>, 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<number>, 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 // dasharray is empty, draws a full line (no dash or no gap length represented, default behavior)\n if (dasharray.length === 0) {\n // insert a single dash range in order to draw a full line\n dasharray.push(1);\n }\n\n let length = 0;\n for (let i = 0; i < dasharray.length; i++) {\n if (dasharray[i] < 0) {\n warnOnce('Negative value is found in line dasharray, replacing values with 0');\n dasharray[i] = 0;\n }\n length += dasharray[i];\n }\n\n if (length !== 0) {\n const stretch = this.width / length;\n const ranges = this.getDashRanges(dasharray, this.width, stretch);\n\n if (round) {\n this.addRoundDash(ranges, stretch, n);\n } else {\n 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\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<Actor>;\n currentActor: number;\n id: number;\n ready: boolean;\n\n // exposed to allow stubbing in unit tests\n static Actor: Class<Actor>;\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 // track whether all workers are instantiated and ready to receive messages;\n // used for optimizations on initial map load\n this.ready = false;\n this.broadcast('checkIfReady', null, () => { this.ready = true; });\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","// @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';\nimport {getBounds, clamp, polygonizeBounds, bufferConvexPolygon} from '../util/util';\nimport {polygonIntersectsBox} from '../util/intersection_tests';\nimport EXTENT from '../data/extent';\nimport type {PointLike} from '@mapbox/point-geometry';\nimport type Transform from '../geo/transform';\nimport type Tile from '../source/tile';\nimport pixelsToTileUnits from '../source/pixels_to_tile_units';\nimport {vec3} from 'gl-matrix';\nimport {Ray} from '../util/primitives';\nimport MercatorCoordinate from '../geo/mercator_coordinate';\nimport type {OverscaledTileID} from '../source/tile_id';\n\n/**\n * A data-class that represents a screenspace query from `Map#queryRenderedFeatures`.\n * All the internal geometries and data are intented to be immutable and read-only.\n * Its lifetime is only for the duration of the query and fixed state of the map while the query is being processed.\n *\n * @class QueryGeometry\n */\nexport class QueryGeometry {\n screenBounds: Point[];\n cameraPoint: Point;\n screenGeometry: Point[];\n screenGeometryMercator: MercatorCoordinate[];\n cameraGeometry: Point[];\n\n _screenRaycastCache: { [_: number]: MercatorCoordinate[]};\n _cameraRaycastCache: { [_: number]: MercatorCoordinate[]};\n\n isAboveHorizon: boolean;\n\n constructor(screenBounds: Point[], cameraPoint: Point, aboveHorizon: boolean, transform: Transform) {\n this.screenBounds = screenBounds;\n this.cameraPoint = cameraPoint;\n this._screenRaycastCache = {};\n this._cameraRaycastCache = {};\n this.isAboveHorizon = aboveHorizon;\n\n this.screenGeometry = this.bufferedScreenGeometry(0);\n this.screenGeometryMercator = this.screenGeometry.map((p) => transform.pointCoordinate3D(p));\n this.cameraGeometry = this.bufferedCameraGeometry(0);\n }\n\n /**\n * Factory method to help contruct an instance while accounting for current map state.\n *\n * @static\n * @param {(PointLike | [PointLike, PointLike])} geometry The query geometry.\n * @param {Transform} transform The current map transform.\n * @returns {QueryGeometry} An instance of the QueryGeometry class.\n */\n static createFromScreenPoints(geometry: PointLike | [PointLike, PointLike], transform: Transform): QueryGeometry {\n let screenGeometry;\n let aboveHorizon;\n if (geometry instanceof Point || typeof geometry[0] === 'number') {\n const pt = Point.convert(geometry);\n screenGeometry = [Point.convert(geometry)];\n aboveHorizon = transform.isPointAboveHorizon(pt);\n } else {\n const tl = Point.convert(geometry[0]);\n const br = Point.convert(geometry[1]);\n screenGeometry = [tl, br];\n aboveHorizon = polygonizeBounds(tl, br).every((p) => transform.isPointAboveHorizon(p));\n }\n\n return new QueryGeometry(screenGeometry, transform.getCameraPoint(), aboveHorizon, transform);\n }\n\n /**\n * Returns true if the initial query by the user was a single point\n *\n * @returns {boolean}\n */\n isPointQuery(): boolean {\n return this.screenBounds.length === 1;\n }\n\n /**\n * Due to data-driven styling features do not uniform size(eg `circle-radius`) and can be offset differntly\n * from their original location(for eg. with `*-translate`). This means we have to expand our query region for\n * each tile to account for variation in these properties.\n * Each tile calculates a tile level max padding value (in screenspace pixels) when its parsed, this function\n * lets us calculate a buffered version of the screenspace query geometry for each tile.\n *\n * @param {number} buffer The tile padding in screenspace pixels.\n * @returns {Point[]} The buffered query geometry.\n */\n bufferedScreenGeometry(buffer: number): Point[] {\n return polygonizeBounds(\n this.screenBounds[0],\n this.screenBounds.length === 1 ? this.screenBounds[0] : this.screenBounds[1],\n buffer\n );\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 thats a convex polygon that encomapasses the query frustum and the point underneath the camera.\n * Similar to `bufferedScreenGeometry`, buffering is added to account for variation in paint properties.\n *\n *\n * Case 1: point underneath camera is exactly behind query volume\n * +----------+\n * | |\n * | |\n * | |\n * + +\n * X X\n * X X\n * X X\n * X X\n * XX\n *\n *\n *\n *\n * Case 2: point is behind and to the right\n * +----------+\n * | X\n * | X\n * | XX\n * + X\n * XXX XX\n * XXXX X\n * XXX XX\n * XX X\n * XXX\n *\n *\n *\n * Case 3: point is behind and to the left\n * +----------+\n * X |\n * X |\n * XX |\n * X +\n * X XXXX\n * XX XXX\n * X XXXX\n * X XXXX\n * XXX\n *\n *\n *\n * @param {number} buffer The tile padding in screenspace pixels.\n * @returns {Point[]} The buffered query geometry.\n */\n bufferedCameraGeometry(buffer: number): Point[] {\n const min = this.screenBounds[0];\n const max = this.screenBounds.length === 1 ? this.screenBounds[0].add(new Point(1, 1)) : this.screenBounds[1];\n const cameraPolygon = polygonizeBounds(min, max, 0, false);\n\n // Only need to account for point underneath camera if its behind query volume\n if (this.cameraPoint.y > max.y) {\n //case 1: insert point in the middle\n if (this.cameraPoint.x > min.x && this.cameraPoint.x < max.x) {\n cameraPolygon.splice(3, 0, this.cameraPoint);\n //case 2: replace btm right point\n } else if (this.cameraPoint.x >= max.x) {\n cameraPolygon[2] = this.cameraPoint;\n //case 3: replace btm left point\n } else if (this.cameraPoint.x <= min.x) {\n cameraPolygon[3] = this.cameraPoint;\n }\n }\n\n return bufferConvexPolygon(cameraPolygon, buffer);\n }\n\n /**\n * Checks if a tile is contained within this query geometry.\n *\n * @param {Tile} tile The tile to check.\n * @param {Transform} transform The current map transform.\n * @param {boolean} use3D A boolean indicating whether to query 3D features.\n * @returns {?TilespaceQueryGeometry} Returns undefined if the tile does not intersect\n */\n containsTile(tile: Tile, transform: Transform, use3D: boolean): ?TilespaceQueryGeometry {\n // The buffer around the query geometry is applied in screen-space.\n // Floating point errors when projecting into tilespace could leave a feature\n // outside the query volume even if it looks like it overlaps visually, a 1px bias value overcomes that.\n const bias = 1;\n const padding = tile.queryPadding + bias;\n\n const geometryForTileCheck = use3D ?\n this._bufferedCameraMercator(padding, transform).map((p) => tile.tileID.getTilePoint(p)) :\n this._bufferedScreenMercator(padding, transform).map((p) => tile.tileID.getTilePoint(p));\n const tilespaceVec3s = this.screenGeometryMercator.map((p) => tile.tileID.getTileVec3(p));\n const tilespaceGeometry = tilespaceVec3s.map((v) => new Point(v[0], v[1]));\n\n const cameraMercator = transform.getFreeCameraOptions().position || new MercatorCoordinate(0, 0, 0);\n const tilespaceCameraPosition = tile.tileID.getTileVec3(cameraMercator);\n const tilespaceRays = tilespaceVec3s.map((tileVec) => {\n const dir = vec3.sub(tileVec, tileVec, tilespaceCameraPosition);\n vec3.normalize(dir, dir);\n return new Ray(tilespaceCameraPosition, dir);\n });\n const pixelToTileUnitsFactor = pixelsToTileUnits(tile, 1, transform.zoom);\n\n if (polygonIntersectsBox(geometryForTileCheck, 0, 0, EXTENT, EXTENT)) {\n return {\n queryGeometry: this,\n tilespaceGeometry,\n tilespaceRays,\n bufferedTilespaceGeometry: geometryForTileCheck,\n bufferedTilespaceBounds: clampBoundsToTileExtents(getBounds(geometryForTileCheck)),\n tile,\n tileID: tile.tileID,\n pixelToTileUnitsFactor\n };\n }\n }\n\n /**\n * These methods add caching on top of the terrain raycasting provided by `Transform#pointCoordinate3d`.\n * Tiles come with different values of padding, however its very likely that multiple tiles share the same value of padding\n * based on the style. In that case we want to reuse the result from a previously computed terrain raycast.\n */\n\n _bufferedScreenMercator(padding: number, transform: Transform): MercatorCoordinate[] {\n const key = cacheKey(padding);\n if (this._screenRaycastCache[key]) {\n return this._screenRaycastCache[key];\n } else {\n const poly = this.bufferedScreenGeometry(padding).map((p) => transform.pointCoordinate3D(p));\n this._screenRaycastCache[key] = poly;\n return poly;\n }\n }\n\n _bufferedCameraMercator(padding: number, transform: Transform): MercatorCoordinate[] {\n const key = cacheKey(padding);\n if (this._cameraRaycastCache[key]) {\n return this._cameraRaycastCache[key];\n } else {\n const poly = this.bufferedCameraGeometry(padding).map((p) => transform.pointCoordinate3D(p));\n this._cameraRaycastCache[key] = poly;\n return poly;\n }\n }\n}\n\n//Padding is in screen pixels and is only used as a coarse check, so 2 decimal places of precision should be good enough for a cache.\nfunction cacheKey(padding: number): number {\n return (padding * 100) | 0;\n}\n\nexport type TilespaceQueryGeometry = {\n queryGeometry: QueryGeometry,\n tilespaceGeometry: Point[],\n tilespaceRays: Ray[],\n bufferedTilespaceGeometry: Point[],\n bufferedTilespaceBounds: { min: Point, max: Point},\n tile: Tile,\n tileID: OverscaledTileID,\n pixelToTileUnitsFactor: number\n};\n\nfunction clampBoundsToTileExtents(bounds: {min: Point, max: Point}): {min: Point, max: Point} {\n bounds.min.x = clamp(bounds.min.x, 0, EXTENT);\n bounds.min.y = clamp(bounds.min.y, 0, EXTENT);\n\n bounds.max.x = clamp(bounds.max.x, 0, EXTENT);\n bounds.max.y = clamp(bounds.max.y, 0, EXTENT);\n return bounds;\n}\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<TileJSON>): 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 {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} from '../util/mapbox';\nimport TileBounds from './tile_bounds';\nimport Texture from '../render/texture';\nimport browser from '../util/browser';\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<string>;\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\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<void>) {\n const use2x = browser.devicePixelRatio >= 2;\n const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), use2x, 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<void>) {\n if (tile.request) {\n tile.request.cancel();\n delete tile.request;\n }\n callback();\n }\n\n unloadTile(tile: Tile, callback: Callback<void>) {\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 {createLayout} from '../util/struct_array';\n\nexport default createLayout([\n {name: 'a_pos', type: 'Int16', components: 2},\n {name: 'a_texture_pos', type: 'Int16', components: 2}\n]);\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<Array<number>>} [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<Array<number>>} 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<void>) {\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<MercatorCoordinate>) {\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 {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<string>,\n\n hasTransition(): boolean;\n loaded(): boolean;\n\n fire(event: Event): mixed;\n on(type: *, listener: (Object) => any): Evented;\n\n +onAdd?: (map: Map) => void;\n +onRemove?: (map: Map) => void;\n\n loadTile(tile: Tile, callback: Callback<void>, tileWorkers?: {[string]: Actor}): void;\n +hasTile?: (tileID: OverscaledTileID) => boolean;\n +abortTile?: (tile: Tile, callback: Callback<void>) => void;\n +unloadTile?: (tile: Tile, callback: Callback<void>) => 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 +afterUpdate?: () => 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<Source> & 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<Source>) {\n sourceTypes[name] = type;\n};\n\nexport interface Actor {\n send(type: string, data: Object, callback: Callback<any>): void;\n}\n","// @flow\n\nimport {Event, ErrorEvent, Evented} from '../util/evented';\n\nimport {extend, pick} from '../util/util';\nimport loadTileJSON from './load_tilejson';\nimport {postTurnstileEvent} 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';\nimport {DedupedRequest, loadVectorTile} from './vector_tile_worker_source';\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';\nimport type Actor from '../util/actor';\nimport type {LoadVectorTileResult} from './vector_tile_worker_source';\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<string>;\n tileBounds: TileBounds;\n reparseOverscaled: boolean;\n isTileClipped: boolean;\n _tileJSONRequest: ?Cancelable;\n _loaded: boolean;\n _tileWorkers: {[string]: Actor};\n _deduped: DedupedRequest;\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 this._tileWorkers = {};\n this._deduped = new DedupedRequest();\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\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 sourceCaches = this.map.style._getSourceCaches(this.id);\n for (const sourceCache of sourceCaches) {\n sourceCache.clearTiles();\n }\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<string>) {\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://<Tileset ID>`.\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<void>) {\n const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme));\n const request = this.map._requestManager.transformRequest(url, ResourceType.Tile);\n\n const params = {\n request,\n data: undefined,\n uid: tile.uid,\n tileID: tile.tileID,\n tileZoom: tile.tileZoom,\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 isSymbolTile: tile.isSymbolTile\n };\n params.request.collectResourceTiming = this._collectResourceTiming;\n\n if (!tile.actor || tile.state === 'expired') {\n tile.actor = this._tileWorkers[url] = this._tileWorkers[url] || this.dispatcher.getActor();\n\n // if workers are not ready to receive messages yet, use the idle time to preemptively\n // load tiles on the main thread and pass the result instead of requesting a worker to do so\n if (!this.dispatcher.ready) {\n const cancel = loadVectorTile.call({deduped: this._deduped}, params, (err: ?Error, data: ?LoadVectorTileResult) => {\n if (err || !data) {\n done.call(this, err);\n } else {\n // the worker will skip the network request if the data is already there\n params.data = {\n cacheControl: data.cacheControl,\n expires: data.expires,\n rawData: data.rawData.slice(0)\n };\n if (tile.actor) tile.actor.send('loadTile', params, done.bind(this));\n }\n }, true);\n tile.request = {cancel};\n\n } else {\n tile.request = tile.actor.send('loadTile', params, done.bind(this));\n }\n\n } else if (tile.state === 'loading') {\n // schedule tile reloading after it has been loaded\n tile.reloadCallback = callback;\n\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 afterUpdate() {\n this._tileWorkers = {};\n }\n}\n\nexport default VectorTileSource;\n","// @flow\n\nimport {getImage, ResourceType} from '../util/ajax';\nimport {extend, prevPowerOfTwo} 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<void>) {\n const url = this.map._requestManager.normalizeTileURL(tile.tileID.canonical.url(this.tiles, this.scheme), false, this.tileSize);\n tile.request = getImage(this.map._requestManager.transformRequest(url, ResourceType.Tile), imageLoaded.bind(this));\n\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 // DEMData uses 1px padding. Handle cases with image buffer of 1 and 2 pxs, the rest assume default buffer 0\n // in order to keep the previous implementation working (no validation against tileSize).\n const buffer = (img.width - prevPowerOfTwo(img.width)) / 2;\n // padding is used in getImageData. As DEMData has 1px padding, if DEM tile buffer is 2px, discard outermost pixels.\n const padding = 1 - buffer;\n const borderReady = padding < 1;\n if (!borderReady && !tile.neighboringTiles) {\n tile.neighboringTiles = this._getNeighboringTiles(tile.tileID);\n }\n const rawImageData = transfer ? img : browser.getImageData(img, padding);\n const params = {\n uid: tile.uid,\n coord: tile.tileID,\n source: this.id,\n rawImageData,\n encoding: this.encoding,\n padding\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.dem.onDeserialize();\n tile.needsHillshadePrepare = true;\n tile.needsDEMTextureUpload = 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 }\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<PerformanceResourceTiming>;\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 ? options.clusterMaxZoom : 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<number>) {\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<Array<GeoJSONFeature>>) {\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<Array<GeoJSONFeature>>) {\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<void>) {\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<void>) {\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 tileZoom: tile.tileZoom,\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 {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<string>;\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 // 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<Array<number>>} 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<Array<number>>} 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\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 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 type {QueryGeometry} from '../style/query_geometry';\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.scale(t, t, [transform.width * 0.5, -transform.height * 0.5, 1]);\n mat4.translate(t, t, [1, -1, 0]);\n return mat4.multiply(t, t, transform.calculatePosMatrix(tileID.toUnwrapped()));\n}\n\nexport function queryRenderedFeatures(sourceCache: SourceCache,\n styleLayers: {[_: string]: StyleLayer},\n serializedLayers: {[_: string]: Object},\n queryGeometry: QueryGeometry,\n params: { filter: FilterSpecification, layers: Array<string>, availableImages: Array<string> },\n transform: Transform,\n use3DQuery: boolean,\n visualizeQueryGeometry: boolean = false) {\n const tileResults = sourceCache.tilesIn(queryGeometry, use3DQuery, visualizeQueryGeometry);\n tileResults.sort(sortTilesIn);\n const renderedFeatureLayers = [];\n for (const tileResult of tileResults) {\n renderedFeatureLayers.push({\n wrappedTileID: tileResult.tile.tileID.wrapped().key,\n queryResults: tileResult.tile.queryRenderedFeatures(\n styleLayers,\n serializedLayers,\n sourceCache._state,\n tileResult,\n params,\n transform,\n getPixelPosMatrix(sourceCache.transform, tileResult.tile.tileID),\n visualizeQueryGeometry)\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 getLayerSourceCache: (layer: StyleLayer) => SourceCache,\n queryGeometry: Array<Point>,\n params: { filter: FilterSpecification, layers: Array<string>, availableImages: Array<string> },\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 = getLayerSourceCache(layer);\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\n\nimport window from '../window';\nimport mapboxgl from '../../';\n\nimport type {WorkerInterface} from '../web_worker';\n\nexport default function (): WorkerInterface {\n return (mapboxgl.workerClass != null) ? new mapboxgl.workerClass() : (new window.Worker(mapboxgl.workerUrl): any); // eslint-disable-line new-cap\n}\n","// @flow\n\nimport WebWorker from './web_worker';\nimport type {WorkerInterface} from './web_worker';\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<WorkerInterface>;\n\n constructor() {\n this.active = {};\n }\n\n acquire(mapId: number | string): Array<WorkerInterface> {\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\n// extensive benchmarking showed 2 to be the best default for both desktop and mobile devices;\n// we can't rely on hardwareConcurrency because of wild inconsistency of reported numbers between browsers\nWorkerPool.workerCount = 2;\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","\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<Layer>} layers\n * @returns {Array<Layer>}\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 * { command: 'setTerrain', args: [terrainProperties] }\n */\n setTerrain: 'setTerrain'\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\n // Remove the terrain if the source for that terrain is being removed\n let beforeTerrain = before.terrain;\n if (beforeTerrain) {\n if (sourcesRemoved[beforeTerrain.source]) {\n commands.push({command: operations.setTerrain, args: [undefined]});\n beforeTerrain = undefined;\n }\n }\n\n commands = commands.concat(removeOrAddSourceCommands);\n\n // Even though terrain is a top-level property\n // Its like a layer in the sense that it depends on a source being present.\n if (!isEqual(beforeTerrain, after.terrain)) {\n commands.push({command: operations.setTerrain, args: [after.terrain]});\n }\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<Point>;\n length: number;\n paddedLength: number;\n padding: number;\n _distances: Array<number>;\n\n constructor(points_: ?Array<Point>, padding_: ?number) {\n this.reset(points_, padding_);\n }\n\n reset(points_: ?Array<Point>, 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<any>;\n boxKeys: Array<any>;\n boxCells: Array<Array<number>>;\n circleCells: Array<Array<number>>;\n bboxes: Array<number>;\n circles: Array<number>;\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<any> {\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, elevation: number = 0) {\n const pos = [point.x, point.y, elevation, 1];\n if (elevation) {\n vec4.transformMat4(pos, pos, matrix);\n } else {\n xyTransformMat4(pos, pos, matrix);\n }\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 Math.min(0.5 + 0.5 * (cameraToCenterDistance / signedDistanceFromCamera), 1.5);\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 getElevation: ?((p: Point) => number)) {\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 elevation = getElevation ? getElevation({x: symbol.anchorX, y: symbol.anchorY}) : 0;\n const anchorPos = [symbol.anchorX, symbol.anchorY, elevation, 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 transformedTileAnchor = project(tileAnchorPoint, labelPlaneMatrix, elevation);\n\n // Skip labels behind the camera\n if (transformedTileAnchor.signedDistanceFromCamera <= 0.0) {\n hideGlyphs(symbol.numGlyphs, dynamicLayoutVertexArray);\n continue;\n }\n\n const anchorPoint = transformedTileAnchor.point;\n let projectionCache = {};\n\n const getElevationForPlacement = pitchWithMap ? null : getElevation; // When pitchWithMap, we're projecting to scaled tile coordinate space: there is no need to get elevation as it doesn't affect projection.\n const placeUnflipped: any = placeGlyphsAlongLine(symbol, pitchScaledFontSize, false /*unflipped*/, keepUpright, posMatrix, labelPlaneMatrix, glCoordMatrix,\n bucket.glyphOffsetArray, lineVertexArray, dynamicLayoutVertexArray, anchorPoint, tileAnchorPoint, projectionCache, aspectRatio, getElevationForPlacement);\n\n useVertical = placeUnflipped.useVertical;\n\n if (getElevationForPlacement && placeUnflipped.needsFlipping) projectionCache = {}; // Truncated points should be recalculated.\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, getElevationForPlacement).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, getElevation: ?((p: Point) => number), returnPathInTileCoords: ?boolean) {\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, getElevation, returnPathInTileCoords, true);\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, getElevation, returnPathInTileCoords, true);\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, getElevation) {\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, getElevation);\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, getElevation));\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, getElevation);\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, getElevation: ?((p: Point) => number)) {\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 unitVertex = previousTilePoint.add(previousTilePoint.sub(currentTilePoint)._unit());\n const projectedUnitVertex = project(unitVertex, projectionMatrix, getElevation ? getElevation(unitVertex) : 0).point;\n const projectedUnitSegment = previousProjectedPoint.sub(projectedUnitVertex);\n\n return previousProjectedPoint.add(projectedUnitSegment._mult(minimumLength / projectedUnitSegment.mag()));\n}\n\nfunction interpolate(p1, p2, a) {\n const b = 1 - a;\n return new Point(p1.x * b + p2.x * a, p1.y * b + p2.y * a);\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 getElevation: ?((p: Point) => number),\n returnPathInTileCoords: ?boolean,\n endGlyph: ?boolean) {\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 const tilePath = [];\n let currentVertex = tileAnchorPoint;\n\n const previousTilePoint = () => {\n const previousLineVertexIndex = currentIndex - dir;\n return distanceToPrev === 0 ?\n tileAnchorPoint :\n new Point(lineVertexArray.getx(previousLineVertexIndex), lineVertexArray.gety(previousLineVertexIndex));\n };\n\n const getTruncatedLineSegment = () => {\n return projectTruncatedLineSegment(previousTilePoint(), currentVertex, prev, absOffsetX - distanceToPrev + 1, labelPlaneMatrix, getElevation);\n };\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 if (returnPathInTileCoords) tilePath.push(currentVertex || previousTilePoint());\n\n current = projectionCache[currentIndex];\n if (current === undefined) {\n currentVertex = new Point(lineVertexArray.getx(currentIndex), lineVertexArray.gety(currentIndex));\n const projection = project(currentVertex, labelPlaneMatrix, getElevation ? getElevation(currentVertex) : 0);\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 // Don't cache because the new vertex might not be far enough out for future glyphs on the same segment\n current = getTruncatedLineSegment();\n }\n } else {\n currentVertex = null; // null stale data\n }\n\n distanceToPrev += currentSegmentDistance;\n currentSegmentDistance = prev.dist(current);\n }\n\n if (endGlyph && getElevation) {\n // For terrain, always truncate end points in order to handle terrain curvature.\n // If previously truncated, on signedDistanceFromCamera < 0, don't do it.\n // Cache as end point. The cache is cleared if there is need for flipping in updateLineLabels.\n currentVertex = currentVertex || new Point(lineVertexArray.getx(currentIndex), lineVertexArray.gety(currentIndex));\n projectionCache[currentIndex] = current = (projectionCache[currentIndex] === undefined) ? current : getTruncatedLineSegment();\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 if (lineOffsetY) 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 if (returnPathInTileCoords) {\n currentVertex = currentVertex || new Point(lineVertexArray.getx(currentIndex), lineVertexArray.gety(currentIndex));\n const prevVertex = tilePath.length > 0 ? tilePath[tilePath.length - 1] : currentVertex;\n tilePath.push(interpolate(prevVertex, currentVertex, segmentInterpolationT));\n }\n\n return {\n point: p,\n angle: segmentAngle,\n path: pathVertices,\n tilePath\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, vec4} from 'gl-matrix';\nimport ONE_EM from '../symbol/one_em';\nimport assert from 'assert';\n\nimport * as projection from '../symbol/projection';\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';\nimport {OverscaledTileID} from '../source/tile_id';\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(scale: number, collisionBox: SingleCollisionBox, shift: Point, allowOverlap: boolean, textPixelRatio: number, posMatrix: mat4, collisionGroupPredicate?: any): { box: Array<number>, offscreen: boolean } {\n assert(!this.transform.elevation || collisionBox.elevation !== undefined);\n const projectedPoint = this.projectAndGetPerspectiveRatio(posMatrix, collisionBox.anchorPointX, collisionBox.anchorPointY, collisionBox.elevation);\n const tileToViewport = textPixelRatio * projectedPoint.perspectiveRatio;\n const tlX = (collisionBox.x1 * scale + shift.x - collisionBox.padding) * tileToViewport + projectedPoint.point.x;\n const tlY = (collisionBox.y1 * scale + shift.y - collisionBox.padding) * tileToViewport + projectedPoint.point.y;\n const brX = (collisionBox.x2 * scale + shift.x + collisionBox.padding) * tileToViewport + projectedPoint.point.x;\n const brY = (collisionBox.y2 * scale + shift.y + collisionBox.padding) * tileToViewport + projectedPoint.point.y;\n // Clip at 10 times the distance of the map center or, said otherwise, when the label\n // would be drawn at 10% the size of the features around it without scaling. Refer:\n // https://github.com/mapbox/mapbox-gl-native/wiki/Text-Rendering#perspective-scaling\n // 0.55 === projection.getPerspectiveRatio(camera_to_center, camera_to_center * 10)\n const minPerspectiveRatio = 0.55;\n const isClipped = projectedPoint.perspectiveRatio <= minPerspectiveRatio || projectedPoint.aboveHorizon;\n\n if (!this.isInsideGrid(tlX, tlY, brX, brY) ||\n (!allowOverlap && this.grid.hitTest(tlX, tlY, brX, brY, collisionGroupPredicate)) ||\n isClipped) {\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,\n tileID: OverscaledTileID): { circles: Array<number>, offscreen: boolean, collisionDetected: boolean } {\n const placedCollisionCircles = [];\n const elevation = this.transform.elevation;\n const getElevation = elevation ? (p => elevation.getAtTileOffset(tileID, p.x, p.y)) : (_ => 0);\n\n const tileUnitAnchorPoint = new Point(symbol.anchorX, symbol.anchorY);\n const anchorElevation = getElevation(tileUnitAnchorPoint);\n const screenAnchorPoint = this.projectAndGetPerspectiveRatio(posMatrix, tileUnitAnchorPoint.x, tileUnitAnchorPoint.y, anchorElevation);\n const {perspectiveRatio} = screenAnchorPoint;\n const labelPlaneFontSize = pitchWithMap ? fontSize / perspectiveRatio : fontSize * perspectiveRatio;\n const labelPlaneFontScale = labelPlaneFontSize / ONE_EM;\n\n const labelPlaneAnchorPoint = projection.project(tileUnitAnchorPoint, labelPlaneMatrix, anchorElevation).point;\n\n const projectionCache = {};\n const lineOffsetX = symbol.lineOffsetX * labelPlaneFontScale;\n const lineOffsetY = symbol.lineOffsetY * labelPlaneFontScale;\n\n const firstAndLastGlyph = screenAnchorPoint.signedDistanceFromCamera > 0 ? 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 elevation && !pitchWithMap ? getElevation : null, // pitchWithMap: no need to sample elevation as it has no effect when projecting using scale/rotate to tile space labelPlaneMatrix.\n pitchWithMap && !!elevation\n ) : null;\n\n let collisionDetected = false;\n let inGrid = false;\n let entirelyOffscreen = true;\n\n if (firstAndLastGlyph && !screenAnchorPoint.aboveHorizon) {\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 assert(pitchWithMap);\n const screenSpacePath = elevation ?\n projectedPath.map((p, index) => {\n const z = getElevation(index < first.path.length - 1 ? first.tilePath[first.path.length - 1 - index] : last.tilePath[index - first.path.length + 2]);\n return projection.project(p, labelToScreenMatrix, z);\n }) :\n 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<Point>) {\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<number>, 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<number>, 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, elevation?: number) {\n const p = [x, y, elevation || 0, 1];\n let aboveHorizon = false;\n if (elevation || this.transform.pitch > 0) {\n vec4.transformMat4(p, p, posMatrix);\n aboveHorizon = p[2] > p[3];\n } else {\n projection.xyTransformMat4(p, p, posMatrix);\n }\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: Math.min(0.5 + 0.5 * (this.transform.cameraToCenterDistance / p[3]), 1.5),\n signedDistanceFromCamera: p[3],\n aboveHorizon\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 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';\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<number>;\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<number>\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 offsetShift(shiftX: number, shiftY: number, rotateWithMap: boolean, pitchWithMap: boolean, angle: number): Point {\n const shift = new Point(shiftX, shiftY);\n if (rotateWithMap) {\n shift._rotate(pitchWithMap ? angle : -angle);\n }\n return shift;\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<BucketPart>, 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 partiallyEvaluatedIconSize: symbolSize.evaluateSizeForZoom(symbolBucket.iconSizeData, 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, pitchWithMap: boolean, textPixelRatio: number,\n posMatrix: mat4, collisionGroup: CollisionGroup, textAllowOverlap: boolean,\n symbolInstance: SymbolInstance, symbolIndex: number, bucket: SymbolBucket,\n orientation: number, iconBox: ?SingleCollisionBox, textSize: any, iconSize: any): ?{ shift: Point, placedGlyphBoxes: { box: Array<number>, offscreen: boolean } } {\n\n const textOffset = [symbolInstance.textOffset0, symbolInstance.textOffset1];\n const textScale = bucket.getSymbolInstanceTextSize(textSize, symbolInstance, this.transform.zoom, symbolIndex);\n const shift = calculateVariableLayoutShift(anchor, width, height, textOffset, textBoxScale);\n\n const placedGlyphBoxes = this.collisionIndex.placeCollisionBox(\n textScale, textBox, offsetShift(shift.x, shift.y, rotateWithMap, pitchWithMap, this.transform.angle),\n textAllowOverlap, textPixelRatio, posMatrix, collisionGroup.predicate);\n\n if (iconBox) {\n const placedIconBoxes = this.collisionIndex.placeCollisionBox(\n bucket.getSymbolInstanceIconSize(iconSize, this.transform.zoom, symbolIndex),\n iconBox, offsetShift(shift.x, shift.y, 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 partiallyEvaluatedIconSize,\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 if (showCollisionBoxes) {\n bucket.updateCollisionDebugBuffers(this.transform.zoom, collisionBoxArray);\n }\n\n const placeSymbol = (symbolInstance: SymbolInstance, symbolIndex: number, 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 updateElevation = (box: SingleCollisionBox) => {\n if (!this.transform.elevation && !box.elevation) return;\n box.elevation = this.transform.elevation ? this.transform.elevation.getAtTileOffset(\n this.retainedQueryData[bucket.bucketInstanceId].tileID,\n box.anchorPointX, box.anchorPointY) : 0;\n };\n\n const textBox = collisionArrays.textBox;\n if (textBox) {\n updateElevation(textBox);\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 textScale = bucket.getSymbolInstanceTextSize(partiallyEvaluatedTextSize, symbolInstance, this.transform.zoom, symbolIndex);\n const placedFeature = this.collisionIndex.placeCollisionBox(textScale, collisionTextBox,\n new Point(0, 0), textAllowOverlap, 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 updateElevation(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 textBoxScale = symbolInstance.textBoxScale;\n const width = (collisionTextBox.x2 - collisionTextBox.x1) * textBoxScale + 2.0 * collisionTextBox.padding;\n const height = (collisionTextBox.y2 - collisionTextBox.y1) * textBoxScale + 2.0 * collisionTextBox.padding;\n\n const variableIconBox = hasIconTextFit && !iconAllowOverlap ? collisionIconBox : null;\n if (variableIconBox) updateElevation(variableIconBox);\n\n let placedBox: ?{ box: Array<number>, 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, textBoxScale, rotateWithMap,\n pitchWithMap, textPixelRatio, posMatrix, collisionGroup, allowOverlap,\n symbolInstance, symbolIndex, bucket, orientation, variableIconBox,\n partiallyEvaluatedTextSize, partiallyEvaluatedIconSize);\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 if (verticalTextBox) updateElevation(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 this.retainedQueryData[bucket.bucketInstanceId].tileID);\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 updateElevation(iconBox);\n const shiftPoint: Point = hasIconTextFit && shift ?\n offsetShift(shift.x, shift.y, rotateWithMap, pitchWithMap, this.transform.angle) :\n new Point(0, 0);\n\n const iconScale = bucket.getSymbolInstanceIconSize(partiallyEvaluatedIconSize, this.transform.zoom, symbolIndex);\n return this.collisionIndex.placeCollisionBox(iconScale, iconBox, shiftPoint,\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), symbolIndex, bucket.collisionArrays[symbolIndex]);\n }\n } else {\n for (let i = bucketPart.symbolInstanceStart; i < bucketPart.symbolInstanceEnd; i++) {\n placeSymbol(bucket.symbolInstances.get(i), 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<Tile>) {\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<BucketPart>;\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<Tile>, 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<string>,\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<string>, layers: {[_: string]: StyleLayer}, layerTiles: {[_: string]: Array<Tile>}) {\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<Tile>, 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<string>) {\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, {LocalGlyphMode} from '../render/glyph_manager';\nimport Light from './light';\nimport Terrain from './terrain';\nimport LineAtlas from '../render/line_atlas';\nimport {pick, clone, extend, deepEqual, filterObject} 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 {QueryGeometry} from '../style/query_geometry';\nimport {\n create as createSource,\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 TerrainSpecification\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';\nimport type {PointLike} from '@mapbox/point-geometry';\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 'setTerrain'\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 localFontFamily?: string,\n localIdeographFontFamily?: string\n};\n\nexport type StyleSetterOptions = {\n validate?: boolean\n};\n\n// Symbols are draped only for specific cases: see isLayerDraped\nconst drapedLayers = {'fill': true, 'line': true, 'background': true, \"hillshade\": true, \"raster\": true};\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 terrain: ?Terrain;\n\n _request: ?Cancelable;\n _spriteRequest: ?Cancelable;\n _layers: {[_: string]: StyleLayer};\n _num3DLayers: number;\n _numSymbolLayers: number;\n _numCircleLayers: number;\n _serializedLayers: {[_: string]: Object};\n _order: Array<string>;\n _drapedFirstOrder: Array<string>;\n _sourceCaches: {[_: string]: SourceCache};\n _otherSourceCaches: {[_: string]: SourceCache};\n _symbolSourceCaches: {[_: 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<string>;\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,\n options.localFontFamily ?\n LocalGlyphMode.all :\n (options.localIdeographFontFamily ? LocalGlyphMode.ideographs : LocalGlyphMode.none),\n options.localFontFamily || options.localIdeographFontFamily);\n this.lineAtlas = new LineAtlas(256, 512);\n this.crossTileSymbolIndex = new CrossTileSymbolIndex();\n\n this._layers = {};\n this._num3DLayers = 0;\n this._numSymbolLayers = 0;\n this._numCircleLayers = 0;\n this._serializedLayers = {};\n this._sourceCaches = {};\n this._otherSourceCaches = {};\n this._symbolSourceCaches = {};\n this.zoomHistory = new ZoomHistory();\n this._loaded = false;\n this._availableImages = [];\n this._order = [];\n this._drapedFirstOrder = [];\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 const sourceCache = self._sourceCaches[id];\n const sourceCacheType = sourceCache.getSource().type;\n if (sourceCacheType === 'vector' || sourceCacheType === 'geojson') {\n sourceCache.reload(); // Should be a no-op if the plugin loads before any tiles load\n }\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 source = this.getSource(event.sourceId);\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 _updateLayerCount(layer: StyleLayer, add: boolean) {\n // Typed layer bookkeeping\n const count = add ? 1 : -1;\n if (layer.is3D()) {\n this._num3DLayers += count;\n }\n if (layer.type === 'circle') {\n this._numCircleLayers += count;\n }\n if (layer.type === 'symbol') {\n this._numSymbolLayers += count;\n }\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 this._changed = false; // avoid triggering redundant style update after adding initial sources\n if (json.sprite) {\n this._loadSprite(json.sprite);\n } else {\n this.imageManager.setLoaded(true);\n this.dispatcher.broadcast('spriteLoaded', 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 this._updateLayerCount(layer, true);\n }\n this.dispatcher.broadcast('setLayers', this._serializeLayers(this._order));\n\n this.light = new Light(this.stylesheet.light);\n if (this.stylesheet.terrain) {\n this._createTerrain(this.stylesheet.terrain);\n }\n this._updateDrapeFirstLayers();\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.dispatcher.broadcast('spriteLoaded', true);\n this.fire(new Event('data', {dataType: 'style'}));\n });\n }\n\n _validateLayer(layer: StyleLayer) {\n const source = this.getSource(layer.source);\n if (!source) {\n return;\n }\n\n const sourceLayer = layer.sourceLayer;\n if (!sourceLayer) {\n return;\n }\n\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<string>): Array<Object> {\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 get order(): Array<string> {\n if (this.map._optimizeForTerrain && this.terrain) {\n assert(this._drapedFirstOrder.length === this._order.length);\n return this._drapedFirstOrder;\n }\n return this._order;\n }\n\n isLayerDraped(layer: StyleLayer): boolean {\n if (!this.terrain) return false;\n return drapedLayers[layer.type];\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)) {\n const sourceCache = this._getLayerSourceCache(layer);\n if (sourceCache) sourceCache.used = true;\n }\n\n const painter = this.map.painter;\n if (painter) {\n const programIds = layer.getProgramIds();\n if (!programIds) continue;\n\n const programConfiguration = layer.getProgramConfiguration(parameters.zoom);\n\n for (const programId of programIds) {\n painter.useProgram(programId, programConfiguration);\n }\n }\n }\n\n for (const sourceId in sourcesUsedBefore) {\n const sourceCache = this._sourceCaches[sourceId];\n if (sourcesUsedBefore[sourceId] !== sourceCache.used) {\n sourceCache.getSource().fire(new Event('data', {sourceDataType: 'visibility', dataType:'source', sourceId: sourceCache.getSource().id}));\n }\n }\n\n this.light.recalculate(parameters);\n if (this.terrain) {\n this.terrain.recalculate(parameters);\n }\n this.z = parameters.zoom;\n\n if (changed) {\n this.fire(new Event('data', {dataType: 'style'}));\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<string>, removedIds: Array<string>) {\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.getSource(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\n const sourceInstance = createSource(id, source, this.dispatcher, this);\n\n sourceInstance.setEventedParent(this, () => ({\n isSourceLoaded: this.loaded(),\n source: sourceInstance.serialize(),\n sourceId: id\n }));\n\n const addSourceCache = (onlySymbols) => {\n const sourceCacheId = (onlySymbols ? 'symbol:' : 'other:') + id;\n const sourceCache = this._sourceCaches[sourceCacheId] = new SourceCache(sourceCacheId, sourceInstance, onlySymbols);\n (onlySymbols ? this._symbolSourceCaches : this._otherSourceCaches)[id] = sourceCache;\n sourceCache.style = this;\n\n sourceCache.onAdd(this.map);\n };\n\n addSourceCache(false);\n if (source.type === 'vector' || source.type === 'geojson') {\n addSourceCache(true);\n }\n\n if (sourceInstance.onAdd) sourceInstance.onAdd(this.map);\n\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 const source = this.getSource(id);\n if (source === 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 if (this.terrain && this.terrain.get().source === id) {\n return this.fire(new ErrorEvent(new Error(`Source \"${id}\" cannot be removed while terrain is using it.`)));\n }\n\n const sourceCaches = this._getSourceCaches(id);\n for (const sourceCache of sourceCaches) {\n delete this._sourceCaches[sourceCache.id];\n delete this._updatedSources[sourceCache.id];\n sourceCache.fire(new Event('data', {sourceDataType: 'metadata', dataType:'source', sourceId: sourceCache.getSource().id}));\n sourceCache.setEventedParent(null);\n sourceCache.clearTiles();\n }\n delete this._otherSourceCaches[id];\n delete this._symbolSourceCaches[id];\n\n source.setEventedParent(null);\n if (source.onRemove) {\n source.onRemove(this.map);\n }\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.getSource(id) !== undefined, 'There is no source with this ID');\n const geojsonSource: GeoJSONSource = (this.getSource(id): 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 const sourceCache = this._getSourceCache(id);\n return sourceCache && sourceCache.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 this._updateLayerCount(layer, true);\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 const sourceCache = this._getLayerSourceCache(layer);\n if (this._removedLayers[id] && layer.source && sourceCache && 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 sourceCache.pause();\n }\n }\n this._updateLayer(layer);\n\n if (layer.onAdd) {\n layer.onAdd(this.map);\n }\n\n this._updateDrapeFirstLayers();\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 this._updateDrapeFirstLayers();\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 this._updateLayerCount(layer, false);\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 this._updateDrapeFirstLayers();\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 /**\n * checks if a specific layer type is present within the style.\n *\n * @param {string} type - type of the desired layer\n * @returns {boolean} a boolean specifying if the given layer type is present\n */\n hasLayerType(type: string): boolean {\n for (const layerId in this._layers) {\n const layer = this._layers[layerId];\n if (layer.type === type) {\n return true;\n }\n }\n return false;\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 source = this.getSource(sourceId);\n\n if (source === 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 = source.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 const sourceCaches = this._getSourceCaches(sourceId);\n for (const sourceCache of sourceCaches) {\n sourceCache.setFeatureState(sourceLayer, target.id, state);\n }\n }\n\n removeFeatureState(target: { source: string; sourceLayer?: string; id?: string | number; }, key?: string) {\n this._checkLoaded();\n const sourceId = target.source;\n const source = this.getSource(sourceId);\n\n if (source === 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 = source.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 const sourceCaches = this._getSourceCaches(sourceId);\n for (const sourceCache of sourceCaches) {\n sourceCache.removeFeatureState(sourceLayer, target.id, key);\n }\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 source = this.getSource(sourceId);\n\n if (source === 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 = source.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 const sourceCaches = this._getSourceCaches(sourceId);\n return sourceCaches[0].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 const sources = {};\n for (const cacheId in this._sourceCaches) {\n const source = this._sourceCaches[cacheId].getSource();\n if (!sources[source.id]) {\n sources[source.id] = source.serialize();\n }\n }\n return filterObject({\n version: this.stylesheet.version,\n name: this.stylesheet.name,\n metadata: this.stylesheet.metadata,\n light: this.stylesheet.light,\n terrain: this.stylesheet.terrain,\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,\n layers: this._serializeLayers(this._order)\n }, (value) => { return value !== undefined; });\n }\n\n _updateLayer(layer: StyleLayer) {\n this._updatedLayers[layer.id] = true;\n const sourceCache = this._getLayerSourceCache(layer);\n if (layer.source && !this._updatedSources[layer.source] &&\n //Skip for raster layers (https://github.com/mapbox/mapbox-gl-js/issues/7865)\n sourceCache &&\n sourceCache.getSource().type !== 'raster') {\n this._updatedSources[layer.source] = 'reload';\n sourceCache.pause();\n }\n this._changed = true;\n }\n\n _flattenAndSortRenderedFeatures(sourceResults: Array<any>) {\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: PointLike | [PointLike, PointLike], 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 const has3DLayer = (params && params.layers) ?\n params.layers.some((layerId) => {\n const layer = this.getLayer(layerId);\n return layer && layer.is3D();\n }) :\n this.has3DLayers();\n const queryGeometryStruct = QueryGeometry.createFromScreenPoints(queryGeometry, transform);\n\n for (const id in this._sourceCaches) {\n const sourceId = this._sourceCaches[id].getSource().id;\n if (params.layers && !includedSources[sourceId]) continue;\n sourceResults.push(\n queryRenderedFeatures(\n this._sourceCaches[id],\n this._layers,\n this._serializedLayers,\n queryGeometryStruct,\n params,\n transform,\n has3DLayer,\n !!this.map._showQueryGeometry)\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._getLayerSourceCache.bind(this),\n queryGeometryStruct.screenGeometry,\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<any>, validate?: boolean}) {\n if (params && params.filter) {\n this._validate(validateStyle.filter, 'querySourceFeatures.filter', params.filter, null, params);\n }\n const sourceCaches = this._getSourceCaches(sourceID);\n let results = [];\n for (const sourceCache of sourceCaches) {\n results = results.concat(querySourceFeatures(sourceCache, params));\n }\n return results;\n }\n\n addSourceType(name: string, SourceType: SourceClass, callback: Callback<void>) {\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 // eslint-disable-next-line no-warning-comments\n // TODO: generic approach for root level property: light, terrain, skybox.\n // It is not done here to prevent rebasing issues.\n setTerrain(terrainOptions: TerrainSpecification) {\n this._checkLoaded();\n\n //Disabling\n if (!terrainOptions) {\n delete this.terrain;\n delete this.stylesheet.terrain;\n this.dispatcher.broadcast('enableTerrain', false);\n this._force3DLayerUpdate();\n return;\n }\n\n // Input validation and source object unrolling\n if (typeof terrainOptions.source === 'object') {\n const id = 'terrain-dem-src';\n this.addSource(id, ((terrainOptions.source): any));\n terrainOptions = clone(terrainOptions);\n terrainOptions = (extend(terrainOptions, {source: id}): any);\n }\n if (this._validate(validateStyle.terrain, 'terrain', terrainOptions)) return;\n\n // Enabling\n if (!this.terrain) {\n this._createTerrain(terrainOptions);\n } else { // Updating\n const terrain = this.terrain;\n const currSpec = terrain.get();\n for (const key in terrainOptions) {\n if (!deepEqual(terrainOptions[key], currSpec[key])) {\n terrain.set(terrainOptions);\n this.stylesheet.terrain = terrainOptions;\n const parameters = {\n now: browser.now(),\n transition: extend({\n duration: 0\n }, this.stylesheet.transition)\n };\n\n terrain.updateTransitions(parameters);\n break;\n }\n }\n }\n\n this._updateDrapeFirstLayers();\n }\n\n _updateDrapeFirstLayers() {\n if (!this.map._optimizeForTerrain || !this.terrain) {\n return;\n }\n\n const draped = this._order.filter((id) => {\n return this.isLayerDraped(this._layers[id]);\n });\n\n const nonDraped = this._order.filter((id) => {\n return !this.isLayerDraped(this._layers[id]);\n });\n this._drapedFirstOrder = [];\n this._drapedFirstOrder.push(...draped);\n this._drapedFirstOrder.push(...nonDraped);\n }\n\n _createTerrain(terrainOptions: TerrainSpecification) {\n const terrain = this.terrain = new Terrain(terrainOptions);\n this.stylesheet.terrain = terrainOptions;\n this.dispatcher.broadcast('enableTerrain', true);\n this._force3DLayerUpdate();\n const parameters = {\n now: browser.now(),\n transition: extend({\n duration: 0\n }, this.stylesheet.transition)\n };\n\n terrain.updateTransitions(parameters);\n }\n\n _force3DLayerUpdate() {\n for (const layerId in this._layers) {\n const layer = this._layers[layerId];\n if (layer.type === 'fill-extrusion') {\n this._updateLayer(layer);\n }\n }\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 const sourceCaches = this._getSourceCaches(id);\n for (const sourceCache of sourceCaches) {\n sourceCache.clearTiles();\n }\n }\n\n _reloadSource(id: string) {\n const sourceCaches = this._getSourceCaches(id);\n for (const sourceCache of sourceCaches) {\n sourceCache.resume();\n sourceCache.reload();\n }\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 const sourceCache = this._sourceCaches[id];\n sourceCache.resume();\n sourceCache.reload();\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._getLayerSourceCache(styleLayer);\n if (!sourceCache) continue;\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 (this._layerOrderChanged) {\n this.fire(new Event('neworder'));\n }\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<string>, 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 setDependencies = (sourceCache: SourceCache) => {\n if (sourceCache) {\n sourceCache.setDependencies(params.tileID.key, params.type, params.icons);\n }\n };\n setDependencies(this._otherSourceCaches[params.source]);\n setDependencies(this._symbolSourceCaches[params.source]);\n }\n\n getGlyphs(mapId: string, params: {stacks: {[_: string]: Array<number>}}, callback: Callback<{[_: string]: {[_: number]: ?StyleGlyph}}>) {\n this.glyphManager.getGlyphs(params.stacks, callback);\n }\n\n getResource(mapId: string, params: RequestParameters, callback: ResponseCallback<any>): Cancelable {\n return makeRequest(params, callback);\n }\n\n _getSourceCache(source: string): SourceCache | void {\n return this._otherSourceCaches[source];\n }\n\n _getLayerSourceCache(layer: StyleLayer): SourceCache | void {\n return layer.type === 'symbol' ?\n this._symbolSourceCaches[layer.source] :\n this._otherSourceCaches[layer.source];\n }\n\n _getSourceCaches(source: string): Array<SourceCache> {\n const sourceCaches = [];\n if (this._otherSourceCaches[source]) {\n sourceCaches.push(this._otherSourceCaches[source]);\n }\n if (this._symbolSourceCaches[source]) {\n sourceCaches.push(this._symbolSourceCaches[source]);\n }\n return sourceCaches;\n }\n\n has3DLayers(): boolean {\n return this._num3DLayers > 0;\n }\n\n hasSymbolLayers(): boolean {\n return this._numSymbolLayers > 0;\n }\n\n hasCircleLayers(): boolean {\n return this._numCircleLayers > 0;\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","\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';\nimport skyboxFrag from './skybox.fragment.glsl';\nimport skyboxGradientFrag from './skybox_gradient.fragment.glsl';\nimport skyboxVert from './skybox.vertex.glsl';\nimport terrainRasterFrag from './terrain_raster.fragment.glsl';\nimport terrainRasterVert from './terrain_raster.vertex.glsl';\nimport terrainDepthFrag from './terrain_depth.fragment.glsl';\nimport terrainDepthVert from './terrain_depth.vertex.glsl';\nimport preludeTerrainVert from './_prelude_terrain.vertex.glsl';\nimport skyboxCaptureFrag from './skybox_capture.fragment.glsl';\nimport skyboxCaptureVert from './skybox_capture.vertex.glsl';\n\nexport let preludeTerrain = {};\npreludeTerrain = compile('', preludeTerrainVert, true);\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);\nexport const terrainRaster = compile(terrainRasterFrag, terrainRasterVert);\nexport const terrainDepth = compile(terrainDepthFrag, terrainDepthVert);\nexport const skybox = compile(skyboxFrag, skyboxVert);\nexport const skyboxGradient = compile(skyboxGradientFrag, skyboxVert);\nexport const skyboxCapture = compile(skyboxCaptureFrag, skyboxCaptureVert);\n\n// Expand #pragmas to #ifdefs.\n\nfunction compile(fragmentSource, vertexSource, isPreludeTerrainShader) {\n const re = /#pragma mapbox: ([\\w]+) ([\\w]+) ([\\w]+) ([\\w]+)/g;\n\n const staticAttributes = vertexSource.match(/attribute (highp |mediump |lowp )?([\\w]+) ([\\w]+)/g);\n const fragmentUniforms = fragmentSource.match(/uniform (highp |mediump |lowp )?([\\w]+) ([\\w]+)([\\s]*)([\\w]*)/g);\n const vertexUniforms = vertexSource.match(/uniform (highp |mediump |lowp )?([\\w]+) ([\\w]+)([\\s]*)([\\w]*)/g);\n let staticUniforms = vertexUniforms ? vertexUniforms.concat(fragmentUniforms) : fragmentUniforms;\n if (!isPreludeTerrainShader) {\n staticUniforms = preludeTerrain.staticUniforms.concat(staticUniforms);\n }\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<VertexBuffer>;\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<VertexBuffer>,\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<VertexBuffer>,\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 {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 matrix: ?Float32Array\n): UniformValues<HillshadeUniformsType> => {\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': matrix ? 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<HillshadePrepareUniformsType> => {\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.unpackVector\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 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 Tile from '../source/tile';\nimport type HillshadeStyleLayer from '../style/style_layer/hillshade_style_layer';\nimport type {OverscaledTileID} from '../source/tile_id';\nimport assert from 'assert';\nimport DEMData from '../data/dem_data';\n\nexport default drawHillshade;\n\nfunction drawHillshade(painter: Painter, sourceCache: SourceCache, layer: HillshadeStyleLayer, tileIDs: Array<OverscaledTileID>) {\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 // When rendering to texture, coordinates are already sorted: primary by\n // proxy id and secondary sort is by Z.\n const renderingToTexture = painter.terrain && painter.terrain.renderingToTexture;\n const [stencilModes, coords] = painter.renderPass === 'translucent' && !renderingToTexture ?\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 const stencilMode = renderingToTexture && painter.terrain ?\n painter.terrain.stencilModeForRTTOverlap(coord) : stencilModes[coord.overscaledZ];\n renderHillshade(painter, coord, tile, layer, depthMode, stencilMode, colorMode);\n }\n }\n\n context.viewport.set([0, 0, painter.width, painter.height]);\n}\n\nfunction renderHillshade(painter, coord, 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 painter.prepareDrawTile(coord);\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, painter.terrain ? coord.posMatrix : null);\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\nexport function prepareDEMTexture(painter: Painter, tile: Tile, dem: DEMData) {\n if (!tile.needsDEMTextureUpload) return;\n\n const context = painter.context;\n const gl = context.gl;\n\n context.pixelStoreUnpackPremultiplyAlpha.set(false);\n const textureStride = dem.stride;\n tile.demTexture = tile.demTexture || painter.getTileTexture(textureStride);\n const pixelData = dem.getPixels();\n if (tile.demTexture) {\n tile.demTexture.update(pixelData, {premultiply: false});\n } else {\n tile.demTexture = new Texture(context, pixelData, gl.RGBA, {premultiply: false});\n }\n tile.needsDEMTextureUpload = false;\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 if (!tile.dem) return;\n const dem: DEMData = tile.dem;\n\n context.activeTexture.set(gl.TEXTURE1);\n prepareDEMTexture(painter, tile, dem);\n assert(tile.demTexture);\n if (!tile.demTexture) return; // Silence flow.\n tile.demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);\n const tileSize = dem.dim;\n\n context.activeTexture.set(gl.TEXTURE0);\n let fbo = tile.fbo;\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","// @flow\n\nimport {\n Uniform1i,\n Uniform1f,\n UniformMatrix4f\n} from '../render/uniform_binding';\n\nimport type Context from '../gl/context';\nimport type {UniformValues, UniformLocations} from '../render/uniform_binding';\n\nexport type TerrainRasterUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_image0': Uniform1i,\n 'u_skirt_height': Uniform1f\n|};\n\nconst terrainRasterUniforms = (context: Context, locations: UniformLocations): TerrainRasterUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_image0': new Uniform1i(context, locations.u_image0),\n 'u_skirt_height': new Uniform1f(context, locations.u_skirt_height)\n});\n\nconst terrainRasterUniformValues = (\n matrix: Float32Array,\n skirtHeight: number\n): UniformValues<TerrainRasterUniformsType> => ({\n 'u_matrix': matrix,\n 'u_image0': 0,\n 'u_skirt_height': skirtHeight\n});\n\nexport {terrainRasterUniforms, terrainRasterUniformValues};\n","// @flow\n\nimport DepthMode from '../gl/depth_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport {terrainRasterUniformValues} from './terrain_raster_program';\nimport {Terrain} from './terrain';\nimport Tile from '../source/tile';\nimport assert from 'assert';\nimport {easeCubicInOut} from '../util/util';\n\nimport type Painter from '../render/painter';\nimport type SourceCache from '../source/source_cache';\nimport type {OverscaledTileID, CanonicalTileID} from '../source/tile_id';\nimport StencilMode from '../gl/stencil_mode';\nimport ColorMode from '../gl/color_mode';\n\nexport {\n drawTerrainRaster,\n drawTerrainDepth\n};\n\ntype DEMChain = {\n startTime: number,\n phase: number,\n duration: number, // Interpolation duration in milliseconds\n from: Tile,\n to: Tile,\n queued: ?Tile\n};\n\nclass VertexMorphing {\n operations: {[string | number]: DEMChain };\n\n constructor() {\n this.operations = {};\n }\n\n newMorphing(key: number, from: Tile, to: Tile, now: number, duration: number) {\n assert(from.demTexture && to.demTexture);\n assert(from.tileID.key !== to.tileID.key);\n\n if (key in this.operations) {\n const op = this.operations[key];\n assert(op.from && op.to);\n // Queue the target tile unless it's being morphed to already\n if (op.to.tileID.key !== to.tileID.key)\n op.queued = to;\n } else {\n this.operations[key] = {\n startTime: now,\n phase: 0.0,\n duration,\n from,\n to,\n queued: null\n };\n }\n }\n\n getMorphValuesForProxy(key: number): ?{from: Tile, to: Tile, phase: number} {\n if (!(key in this.operations))\n return null;\n\n const op = this.operations[key];\n const from = op.from;\n const to = op.to;\n assert(from && to);\n\n return {from, to, phase: op.phase};\n }\n\n update(now: number) {\n for (const key in this.operations) {\n const op = this.operations[key];\n assert(op.from && op.to);\n\n op.phase = (now - op.startTime) / op.duration;\n\n // Start the queued operation if the current one is finished or the data has expired\n while (op.phase >= 1.0 || !this._validOp(op)) {\n if (!this._nextOp(op, now)) {\n delete this.operations[key];\n break;\n }\n }\n }\n }\n\n _nextOp(op: DEMChain, now: number): boolean {\n if (!op.queued)\n return false;\n op.from = op.to;\n op.to = op.queued;\n op.queued = null;\n op.phase = 0.0;\n op.startTime = now;\n return true;\n }\n\n _validOp(op: DEMChain): boolean {\n return op.from.hasData() && op.to.hasData();\n }\n}\n\nfunction demTileChanged(prev: ?Tile, next: ?Tile): boolean {\n if (prev == null || next == null)\n return false;\n if (!prev.hasData() || !next.hasData())\n return false;\n if (prev.demTexture == null || next.demTexture == null)\n return false;\n return prev.tileID.key !== next.tileID.key;\n}\n\nconst vertexMorphing = new VertexMorphing();\nconst SHADER_DEFAULT = 0;\nconst SHADER_MORPHING = 1;\nconst defaultDuration = 250;\n\nconst shaderDefines = {\n \"0\": null,\n \"1\": 'TERRAIN_VERTEX_MORPHING'\n};\n\nfunction drawTerrainRaster(painter: Painter, terrain: Terrain, sourceCache: SourceCache, tileIDs: Array<OverscaledTileID>, now: number) {\n const context = painter.context;\n const gl = context.gl;\n\n let program = painter.useProgram('terrainRaster');\n let programMode = SHADER_DEFAULT;\n\n const setShaderMode = (mode) => {\n if (programMode === mode)\n return;\n program = painter.useProgram('terrainRaster', null, shaderDefines[mode]);\n programMode = mode;\n };\n\n const colorMode = painter.colorModeForRenderPass();\n const depthMode = new DepthMode(gl.LEQUAL, DepthMode.ReadWrite, painter.depthRangeFor3D);\n vertexMorphing.update(now);\n const tr = painter.transform;\n const skirt = skirtHeight(tr.zoom) * terrain.exaggeration();\n\n for (const coord of tileIDs) {\n const tile = sourceCache.getTile(coord);\n const stencilMode = StencilMode.disabled;\n\n const prevDemTile = terrain.prevTerrainTileForTile[coord.key];\n const nextDemTile = terrain.terrainTileForTile[coord.key];\n\n if (demTileChanged(prevDemTile, nextDemTile)) {\n vertexMorphing.newMorphing(coord.key, prevDemTile, nextDemTile, now, defaultDuration);\n }\n\n // Bind the main draped texture\n context.activeTexture.set(gl.TEXTURE0);\n tile.texture.bind(gl.LINEAR, gl.CLAMP_TO_EDGE, gl.LINEAR_MIPMAP_NEAREST);\n\n const morph = vertexMorphing.getMorphValuesForProxy(coord.key);\n const shaderMode = morph ? SHADER_MORPHING : SHADER_DEFAULT;\n let elevationOptions;\n\n if (morph) {\n elevationOptions = {morphing: {srcDemTile: morph.from, dstDemTile: morph.to, phase: easeCubicInOut(morph.phase)}};\n }\n const uniformValues = terrainRasterUniformValues(coord.posMatrix, isEdgeTile(coord.canonical, tr.renderWorldCopies) ? skirt / 10 : skirt);\n\n setShaderMode(shaderMode);\n terrain.setupElevationDraw(tile, program, elevationOptions);\n program.draw(context, gl.TRIANGLES, depthMode, stencilMode, colorMode, CullFaceMode.backCCW,\n uniformValues, \"terrain_raster\", terrain.gridBuffer, terrain.gridIndexBuffer, terrain.gridSegments);\n }\n}\n\nfunction drawTerrainDepth(painter: Painter, terrain: Terrain, sourceCache: SourceCache, tileIDs: Array<OverscaledTileID>) {\n assert(painter.renderPass === 'offscreen');\n\n const context = painter.context;\n const gl = context.gl;\n context.clear({depth: 1});\n const program = painter.useProgram('terrainDepth');\n const depthMode = new DepthMode(gl.LESS, DepthMode.ReadWrite, painter.depthRangeFor3D);\n\n for (const coord of tileIDs) {\n const tile = sourceCache.getTile(coord);\n const uniformValues = terrainRasterUniformValues(coord.posMatrix, 0);\n terrain.setupElevationDraw(tile, program);\n program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled, ColorMode.unblended, CullFaceMode.backCCW,\n uniformValues, \"terrain_depth\", terrain.gridBuffer, terrain.gridIndexBuffer, terrain.gridNoSkirtSegments);\n }\n}\n\nfunction skirtHeight(zoom) {\n // Skirt height calculation is heuristic: provided value hides\n // seams between tiles and it is not too large: 9 at zoom 22, ~20000m at zoom 0.\n return 6 * Math.pow(1.5, 22 - zoom);\n}\n\nfunction isEdgeTile(cid: CanonicalTileID, renderWorldCopies: boolean): boolean {\n const numTiles = 1 << cid.z;\n return (!renderWorldCopies && (cid.x === 0 || cid.x === numTiles - 1)) || cid.y === 0 || cid.y === numTiles - 1;\n}\n\nexport {\n VertexMorphing\n};\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<ClippingMaskUniformsType> => ({\n 'u_matrix': matrix\n});\n\nexport {clippingMaskUniforms, clippingMaskUniformValues};\n","// @flow\n\nimport type SourceCache from '../source/source_cache';\nimport {clamp} from '../util/util';\nimport browser from '../util/browser';\nimport Tile from '../source/tile';\nimport type Transform from '../geo/transform';\n\nexport type RasterFade = {|\n opacity: number,\n mix: number,\n|};\n\nfunction rasterFade(tile: Tile, parentTile: ?Tile, sourceCache: SourceCache, transform: Transform, fadeDuration: number): RasterFade {\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\nexport default rasterFade;\n","// @flow\n\nimport Point from '@mapbox/point-geometry';\nimport SourceCache from '../source/source_cache';\nimport {OverscaledTileID} from '../source/tile_id';\nimport Tile from '../source/tile';\nimport rasterBoundsAttributes from '../data/raster_bounds_attributes';\nimport {RasterBoundsArray, TriangleIndexArray} from '../data/array_types';\nimport SegmentVector from '../data/segment';\nimport Texture from '../render/texture';\nimport Program from '../render/program';\nimport {Uniform1i, Uniform1f, Uniform2f, Uniform4f, UniformMatrix4f} from '../render/uniform_binding';\nimport {prepareDEMTexture} from '../render/draw_hillshade';\nimport EXTENT from '../data/extent';\nimport {clamp, warnOnce} from '../util/util';\nimport assert from 'assert';\nimport {vec3, mat4, vec4} from 'gl-matrix';\nimport getWorkerPool from '../util/global_worker_pool';\nimport Dispatcher from '../util/dispatcher';\nimport GeoJSONSource from '../source/geojson_source';\nimport ImageSource from '../source/image_source';\nimport RasterDEMTileSource from '../source/raster_dem_tile_source';\nimport RasterTileSource from '../source/raster_tile_source';\nimport Color from '../style-spec/util/color';\nimport StencilMode from '../gl/stencil_mode';\nimport {DepthStencilAttachment} from '../gl/value';\nimport {drawTerrainRaster, drawTerrainDepth} from './draw_terrain_raster';\nimport type RasterStyleLayer from '../style/style_layer/raster_style_layer';\nimport {Elevation} from './elevation';\nimport Framebuffer from '../gl/framebuffer';\nimport ColorMode from '../gl/color_mode';\nimport DepthMode from '../gl/depth_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport {clippingMaskUniformValues} from '../render/program/clipping_mask_program';\nimport MercatorCoordinate, {mercatorZfromAltitude} from '../geo/mercator_coordinate';\nimport browser from '../util/browser';\nimport DEMData from '../data/dem_data';\nimport rasterFade from '../render/raster_fade';\nimport {create as createSource} from '../source/source';\n\nimport type Map from '../ui/map';\nimport type Painter from '../render/painter';\nimport type Style from '../style/style';\nimport type StyleLayer from '../style/style_layer';\nimport type VertexBuffer from '../gl/vertex_buffer';\nimport type IndexBuffer from '../gl/index_buffer';\nimport type Context from '../gl/context';\nimport type {UniformLocations, UniformValues} from '../render/uniform_binding';\nimport type Transform from '../geo/transform';\nimport type {DEMEncoding} from '../data/dem_data';\n\nexport const GRID_DIM = 128;\n\nconst FBO_POOL_SIZE = 5;\nconst RENDER_CACHE_MAX_SIZE = 50;\n\ntype RenderBatch = {\n start: number;\n end: number;\n}\n\n/**\n * Proxy source cache gets ideal screen tile cover coordinates. All the other\n * source caches's coordinates get mapped to subrects of proxy coordinates (or\n * vice versa, subrects of larger tiles from all source caches get mapped to\n * full proxy tile). This happens on every draw call in Terrain.updateTileBinding.\n * Approach is used here for terrain : all the visible source tiles of all the\n * source caches get rendered to proxy source cache textures and then draped over\n * terrain. It is in future reusable for handling overscalling as buckets could be\n * constructed only for proxy tile content, not for full overscalled vector tile.\n */\nclass ProxySourceCache extends SourceCache {\n renderCache: Array<FBO>;\n renderCachePool: Array<number>;\n proxyCachedFBO: {[string | number]: {[string | number]: number}};\n\n constructor(map: Map) {\n\n const source = createSource('proxy', {\n type: 'geojson',\n maxzoom: map.transform.maxZoom\n }, new Dispatcher(getWorkerPool(), null), map.style);\n\n super('proxy', source, false);\n\n source.setEventedParent(this);\n\n // This source is not to be added as a map source: we use it's tile management.\n // For that, initialize internal structures used for tile cover update.\n this.map = ((this.getSource(): any): GeoJSONSource).map = map;\n this.used = this._sourceLoaded = true;\n this.renderCache = [];\n this.renderCachePool = [];\n this.proxyCachedFBO = {};\n }\n\n // Override for transient nature of cover here: don't cache and retain.\n /* eslint-disable no-unused-vars */\n update(transform: Transform, tileSize?: number, updateForTerrain?: boolean) {\n if (transform.freezeTileCoverage) { return; }\n this.transform = transform;\n const 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 useElevationData: true\n });\n\n const incoming: {[string]: string} = idealTileIDs.reduce((acc, tileID) => {\n acc[tileID.key] = '';\n if (!this._tiles[tileID.key]) {\n const tile = new Tile(tileID, this._source.tileSize * tileID.overscaleFactor(), transform.tileZoom);\n tile.state = 'loaded';\n this._tiles[tileID.key] = tile;\n }\n return acc;\n }, {});\n\n for (const id in this._tiles) {\n if (!(id in incoming)) {\n this.freeFBO(id);\n this._tiles[id].state = 'unloaded';\n delete this._tiles[id];\n }\n }\n }\n\n freeFBO(id: string) {\n const fbos = this.proxyCachedFBO[id];\n if (fbos !== undefined) {\n const fboIds = ((Object.values(fbos): any): Array<number>);\n this.renderCachePool.push(...fboIds);\n delete this.proxyCachedFBO[id];\n }\n }\n\n deallocRenderCache() {\n this.renderCache.forEach(fbo => fbo.fb.destroy());\n this.renderCache = [];\n this.renderCachePool = [];\n this.proxyCachedFBO = {};\n }\n}\n\n/**\n * Canonical, wrap and overscaledZ contain information of original source cache tile.\n * This tile gets ortho-rendered to proxy tile (defined by proxyTileKey).\n * posMatrix holds orthographic, scaling and translation information that is used\n * for rendering original tile content to a proxy tile. Proxy tile covers whole\n * or sub-rectangle of the original tile.\n */\nclass ProxiedTileID extends OverscaledTileID {\n proxyTileKey: number;\n\n constructor(tileID: OverscaledTileID, proxyTileKey: number, posMatrix: Float32Array) {\n super(tileID.overscaledZ, tileID.wrap, tileID.canonical.z, tileID.canonical.x, tileID.canonical.y);\n this.proxyTileKey = proxyTileKey;\n this.posMatrix = posMatrix;\n }\n}\n\ntype OverlapStencilType = false | 'Clip' | 'Mask';\ntype FBO = {fb: Framebuffer, tex: Texture, dirty: boolean, ref: number};\n\nexport class Terrain extends Elevation {\n terrainTileForTile: {[number | string]: Tile};\n prevTerrainTileForTile: {[number | string]: Tile};\n painter: Painter;\n sourceCache: SourceCache;\n gridBuffer: VertexBuffer;\n gridIndexBuffer: IndexBuffer;\n gridSegments: SegmentVector;\n gridNoSkirtSegments: SegmentVector;\n proxiedCoords: {[string]: Array<ProxiedTileID>};\n proxyCoords: Array<OverscaledTileID>;\n proxyToSource: {[number]: {[string]: Array<ProxiedTileID>}};\n proxySourceCache: ProxySourceCache;\n renderingToTexture: boolean;\n _style: Style;\n orthoMatrix: mat4;\n enabled: boolean;\n\n renderCached: boolean;\n forceRenderCached: boolean; // debugging purpose.\n\n _visibleDemTiles: Array<Tile>;\n _sourceTilesOverlap: {[string]: boolean};\n _overlapStencilMode: StencilMode;\n _overlapStencilType: OverlapStencilType;\n\n _exaggeration: number;\n _depthFBO: Framebuffer;\n _depthTexture: Texture;\n _previousZoom: number;\n _updateTimestamp: number;\n _useVertexMorphing: boolean;\n pool: Array<FBO>;\n currentFBO: FBO;\n renderedToTile: boolean;\n _drapedRenderBatches: Array<RenderBatch>;\n\n _findCoveringTileCache: {[string]: {[number]: ?number}};\n\n _tilesDirty: {[string]: {[number]: boolean}};\n _invalidateRenderCache: boolean;\n\n _emptyDEMTexture: ?Texture;\n _initializing: ?boolean;\n _emptyDEMTextureDirty: ?boolean;\n\n constructor(painter: Painter, style: Style) {\n super();\n this.painter = painter;\n this.terrainTileForTile = {};\n this.prevTerrainTileForTile = {};\n\n // Terrain rendering grid is 129x129 cell grid, made by 130x130 points.\n // 130 vertices map to 128 DEM data + 1px padding on both sides.\n // DEM texture is padded (1, 1, 1, 1) and padding pixels are backfilled\n // by neighboring tile edges. This way we achieve tile stitching as\n // edge vertices from neighboring tiles evaluate to the same 3D point.\n const [triangleGridArray, triangleGridIndices, skirtIndicesOffset] = createGrid(GRID_DIM + 1);\n const context = painter.context;\n this.gridBuffer = context.createVertexBuffer(triangleGridArray, rasterBoundsAttributes.members);\n this.gridIndexBuffer = context.createIndexBuffer(triangleGridIndices);\n this.gridSegments = SegmentVector.simpleSegment(0, 0, triangleGridArray.length, triangleGridIndices.length);\n this.gridNoSkirtSegments = SegmentVector.simpleSegment(0, 0, triangleGridArray.length, skirtIndicesOffset);\n this.proxyCoords = [];\n this.proxiedCoords = {};\n this._visibleDemTiles = [];\n this._drapedRenderBatches = [];\n this._sourceTilesOverlap = {};\n this.proxySourceCache = new ProxySourceCache(style.map);\n this.orthoMatrix = mat4.create();\n mat4.ortho(this.orthoMatrix, 0, EXTENT, 0, EXTENT, 0, 1);\n const gl = context.gl;\n this._overlapStencilMode = new StencilMode({func: gl.GEQUAL, mask: 0xFF}, 0, 0xFF, gl.KEEP, gl.KEEP, gl.REPLACE);\n this._previousZoom = painter.transform.zoom;\n this.pool = [];\n this._findCoveringTileCache = {};\n this._tilesDirty = {};\n this.style = style;\n this._useVertexMorphing = true;\n }\n\n set style(style: Style) {\n style.on('data', this._onStyleDataEvent.bind(this));\n style.on('neworder', this._checkRenderCacheEfficiency.bind(this));\n this._style = style;\n this._checkRenderCacheEfficiency();\n }\n\n /*\n * Validate terrain and update source cache used for elevation.\n * Explicitly pass transform to update elevation (Transform.updateElevation)\n * before using transform for source cache update.\n * cameraChanging is true when camera is zooming, panning or orbiting.\n */\n update(style: Style, transform: Transform, cameraChanging: boolean) {\n if (style && style.terrain) {\n if (this._style !== style) {\n this.style = style;\n }\n this.enabled = true;\n const terrainProps = style.terrain.properties;\n this.sourceCache = ((style._getSourceCache(terrainProps.get('source')): any): SourceCache);\n this._exaggeration = terrainProps.get('exaggeration');\n\n const updateSourceCache = () => {\n if (this.sourceCache.used) {\n warnOnce(`Raster DEM source '${this.sourceCache.id}' is used both for terrain and as layer source.\\n` +\n 'This leads to lower resolution of hillshade. For full hillshade resolution but higher memory consumption, define another raster DEM source.');\n }\n // Lower tile zoom is sufficient for terrain, given the size of terrain grid.\n const demScale = this.sourceCache.getSource().tileSize / GRID_DIM;\n const proxyTileSize = this.proxySourceCache.getSource().tileSize;\n // Dem tile needs to be parent or at least of the same zoom level as proxy tile.\n // Tile cover roundZoom behavior is set to the same as for proxy (false) in SourceCache.update().\n this.sourceCache.update(transform, demScale * proxyTileSize, true);\n // As a result of update, we get new set of tiles: reset lookup cache.\n this._findCoveringTileCache[this.sourceCache.id] = {};\n };\n\n if (!this.sourceCache.usedForTerrain) {\n // Init cache entry.\n this._findCoveringTileCache[this.sourceCache.id] = {};\n // When toggling terrain on/off load available terrain tiles from cache\n // before reading elevation at center.\n this.sourceCache.usedForTerrain = true;\n updateSourceCache();\n this._initializing = true;\n }\n\n updateSourceCache();\n // Camera, when changing, gets constrained over terrain. Issue constrainCameraOverTerrain = true\n // here to cover potential under terrain situation on data or style change.\n transform.updateElevation(!cameraChanging);\n\n // Reset tile lookup cache and update draped tiles coordinates.\n this._findCoveringTileCache[this.proxySourceCache.id] = {};\n this.proxySourceCache.update(transform);\n\n this._emptyDEMTextureDirty = true;\n } else {\n this._disable();\n }\n }\n\n _checkRenderCacheEfficiency() {\n const renderCacheInfo = this.renderCacheEfficiency(this._style);\n if (this._style.map._optimizeForTerrain) {\n assert(renderCacheInfo.efficiency === 100);\n } else if (renderCacheInfo.efficiency !== 100) {\n warnOnce(`Terrain render cache efficiency is not optimal (${renderCacheInfo.efficiency}%) and performance\n may be affected negatively, consider placing all background, fill and line layers before layer\n with id '${renderCacheInfo.firstUndrapedLayer}' or create a map using optimizeForTerrain: true option.`);\n }\n }\n\n _onStyleDataEvent(event: any) {\n if (event.coord && event.dataType === 'source') {\n this._clearRenderCacheForTile(event.sourceCacheId, event.coord);\n } else if (event.dataType === 'style') {\n this._invalidateRenderCache = true;\n }\n }\n\n // Terrain\n _disable() {\n if (!this.enabled) return;\n this.enabled = false;\n this.proxySourceCache.deallocRenderCache();\n if (this._style) {\n for (const id in this._style._sourceCaches) {\n this._style._sourceCaches[id].usedForTerrain = false;\n }\n }\n }\n\n destroy() {\n this._disable();\n if (this._emptyDEMTexture) this._emptyDEMTexture.destroy();\n this.pool.forEach(fbo => fbo.fb.destroy());\n this.pool = [];\n if (this._depthFBO) {\n this._depthFBO.destroy();\n delete this._depthFBO;\n delete this._depthTexture;\n }\n }\n\n // Implements Elevation::_source.\n _source(): ?SourceCache {\n return this.enabled ? this.sourceCache : null;\n }\n\n // Implements Elevation::exaggeration.\n exaggeration(): number {\n return this._exaggeration;\n }\n\n get visibleDemTiles(): Array<Tile> {\n return this._visibleDemTiles;\n }\n\n get drapeBufferSize(): [number, number] {\n const extent = this.proxySourceCache.getSource().tileSize * 2; // *2 is to avoid upscaling bitmap on zoom.\n return [extent, extent];\n }\n\n set useVertexMorphing(enable: boolean) {\n this._useVertexMorphing = enable;\n }\n\n // For every renderable coordinate in every source cache, assign one proxy\n // tile (see _setupProxiedCoordsForOrtho). Mapping of source tile to proxy\n // tile is modeled by ProxiedTileID. In general case, source and proxy tile\n // are of different zoom: ProxiedTileID.posMatrix models ortho, scale and\n // translate from source to proxy. This matrix is used when rendering source\n // tile to proxy tile's texture.\n // One proxy tile can have multiple source tiles, or pieces of source tiles,\n // that get rendered to it.\n // For each proxy tile we assign one terrain tile (_assignTerrainTiles). The\n // terrain tile provides elevation data when rendering (draping) proxy tile\n // texture over terrain grid.\n updateTileBinding(sourcesCoords: {[string]: Array<OverscaledTileID>}) {\n if (!this.enabled) return;\n this.prevTerrainTileForTile = this.terrainTileForTile;\n\n const psc = this.proxySourceCache;\n const tr = this.painter.transform;\n if (this._initializing) {\n // Don't activate terrain until center tile gets loaded.\n this._initializing = tr._centerAltitude === 0 && this.getAtPoint(MercatorCoordinate.fromLngLat(tr.center), -1) === -1;\n this._emptyDEMTextureDirty = !this._initializing;\n }\n\n const options = this.painter.options;\n this.renderCached = (options.zooming || options.moving || options.rotating || !!this.forceRenderCached) && !this._invalidateRenderCache;\n\n this._invalidateRenderCache = false;\n const coords = this.proxyCoords = psc.getIds().map((id) => {\n const tileID = psc.getTileByID(id).tileID;\n tileID.posMatrix = tr.calculatePosMatrix(tileID.toUnwrapped());\n return tileID;\n });\n sortByDistanceToCamera(coords, this.painter);\n this._previousZoom = tr.zoom;\n\n const previousProxyToSource = this.proxyToSource || {};\n this.proxyToSource = {};\n coords.forEach((tileID) => {\n this.proxyToSource[tileID.key] = {};\n });\n\n this.terrainTileForTile = {};\n const sourceCaches = this._style._sourceCaches;\n for (const id in sourceCaches) {\n const sourceCache = sourceCaches[id];\n if (!sourceCache.used) continue;\n if (sourceCache !== this.sourceCache) this._findCoveringTileCache[sourceCache.id] = {};\n this._setupProxiedCoordsForOrtho(sourceCache, sourcesCoords[id], previousProxyToSource);\n if (sourceCache.usedForTerrain) continue;\n const coordinates = sourcesCoords[id];\n if (sourceCache.getSource().reparseOverscaled) {\n // Do this for layers that are not rasterized to proxy tile.\n this._assignTerrainTiles(coordinates);\n }\n }\n\n // Background has no source. Using proxy coords with 1-1 ortho (this.proxiedCoords[psc.id])\n // when rendering background to proxy tiles.\n this.proxiedCoords[psc.id] = coords.map(tileID => new ProxiedTileID(tileID, tileID.key, this.orthoMatrix));\n this._assignTerrainTiles(coords);\n this._prepareDEMTextures();\n this._setupDrapedRenderBatches();\n this._setupRenderCache(previousProxyToSource);\n\n this.renderingToTexture = false;\n this._initFBOPool();\n this._updateTimestamp = browser.now();\n\n // Gather all dem tiles that are assigned to proxy tiles\n const visibleKeys = {};\n this._visibleDemTiles = [];\n\n for (const id of this.proxyCoords) {\n const demTile = this.terrainTileForTile[id.key];\n if (!demTile)\n continue;\n const key = demTile.tileID.key;\n if (key in visibleKeys)\n continue;\n this._visibleDemTiles.push(demTile);\n visibleKeys[key] = key;\n }\n\n }\n\n _assignTerrainTiles(coords: Array<OverscaledTileID>) {\n if (this._initializing) return;\n coords.forEach((tileID) => {\n if (this.terrainTileForTile[tileID.key]) return;\n const demTile = this._findTileCoveringTileID(tileID, this.sourceCache);\n if (demTile) this.terrainTileForTile[tileID.key] = demTile;\n });\n }\n\n _prepareDEMTextures() {\n const context = this.painter.context;\n const gl = context.gl;\n for (const key in this.terrainTileForTile) {\n const tile = this.terrainTileForTile[key];\n const dem = tile.dem;\n if (dem && (!tile.demTexture || tile.needsDEMTextureUpload)) {\n context.activeTexture.set(gl.TEXTURE1);\n prepareDEMTexture(this.painter, tile, dem);\n }\n }\n }\n\n _prepareDemTileUniforms(proxyTile: Tile, demTile: ?Tile, uniforms: UniformValues<TerrainUniformsType>, uniformSuffix: ?string): boolean {\n if (!demTile || demTile.demTexture == null)\n return false;\n\n assert(demTile.dem);\n const proxyId = proxyTile.tileID.canonical;\n const demId = demTile.tileID.canonical;\n const demScaleBy = Math.pow(2, demId.z - proxyId.z);\n const suffix = uniformSuffix || \"\";\n uniforms[`u_dem_tl${suffix}`] = [proxyId.x * demScaleBy % 1, proxyId.y * demScaleBy % 1];\n uniforms[`u_dem_scale${suffix}`] = demScaleBy;\n return true;\n }\n\n get emptyDEMTexture(): Texture {\n return !this._emptyDEMTextureDirty && this._emptyDEMTexture ?\n this._emptyDEMTexture : this._updateEmptyDEMTexture();\n }\n\n _getLoadedAreaMinimum(): number {\n let nonzero = 0;\n const min = this._visibleDemTiles.reduce((acc, tile) => {\n if (!tile.dem) return acc;\n const m = tile.dem.tree.minimums[0];\n acc += m;\n if (m > 0) nonzero++;\n return acc;\n }, 0);\n return nonzero ? min / nonzero : 0;\n }\n\n _updateEmptyDEMTexture(): Texture {\n const context = this.painter.context;\n const gl = context.gl;\n context.activeTexture.set(gl.TEXTURE2);\n\n const min = this._getLoadedAreaMinimum();\n const image = {\n width: 1, height: 1,\n data: new Uint8Array(DEMData.pack(min, ((this.sourceCache.getSource(): any): RasterDEMTileSource).encoding))\n };\n\n this._emptyDEMTextureDirty = false;\n let texture = this._emptyDEMTexture;\n if (!texture) {\n texture = this._emptyDEMTexture = new Texture(context, image, gl.RGBA, {premultiply: false});\n } else {\n texture.update(image, {premultiply: false});\n }\n return texture;\n }\n\n // useDepthForOcclusion: Pre-rendered depth to texture (this._depthTexture) is\n // used to hide (actually moves all object's vertices out of viewport).\n // useMeterToDem: u_meter_to_dem uniform is not used for all terrain programs,\n // optimization to avoid unnecessary computation and upload.\n setupElevationDraw(tile: Tile, program: Program<*>,\n options?: {\n useDepthForOcclusion?: boolean,\n useMeterToDem?: boolean,\n labelPlaneMatrixInv?: ?Float32Array,\n morphing?: { srcDemTile: Tile, dstDemTile: Tile, phase: number }\n }) {\n const context = this.painter.context;\n const gl = context.gl;\n const uniforms = defaultTerrainUniforms(((this.sourceCache.getSource(): any): RasterDEMTileSource).encoding);\n uniforms['u_dem_size'] = this.sourceCache.getSource().tileSize;\n uniforms['u_exaggeration'] = this.exaggeration();\n\n let demTile = null;\n let prevDemTile = null;\n let morphingPhase = 1.0;\n\n if (options && options.morphing && this._useVertexMorphing) {\n const srcTile = options.morphing.srcDemTile;\n const dstTile = options.morphing.dstDemTile;\n morphingPhase = options.morphing.phase;\n\n if (srcTile && dstTile) {\n if (this._prepareDemTileUniforms(tile, srcTile, uniforms, \"_prev\"))\n prevDemTile = srcTile;\n if (this._prepareDemTileUniforms(tile, dstTile, uniforms))\n demTile = dstTile;\n }\n }\n\n if (prevDemTile && demTile) {\n // Both DEM textures are expected to be correctly set if geomorphing is enabled\n context.activeTexture.set(gl.TEXTURE2);\n (demTile.demTexture: any).bind(gl.NEAREST, gl.CLAMP_TO_EDGE, gl.NEAREST);\n context.activeTexture.set(gl.TEXTURE4);\n (prevDemTile.demTexture: any).bind(gl.NEAREST, gl.CLAMP_TO_EDGE, gl.NEAREST);\n uniforms[\"u_dem_lerp\"] = morphingPhase;\n } else {\n demTile = this.terrainTileForTile[tile.tileID.key];\n context.activeTexture.set(gl.TEXTURE2);\n const demTexture = this._prepareDemTileUniforms(tile, demTile, uniforms) ?\n (demTile.demTexture: any) : this.emptyDEMTexture;\n demTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE, gl.NEAREST);\n }\n\n if (options && options.useDepthForOcclusion) {\n context.activeTexture.set(gl.TEXTURE3);\n this._depthTexture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE, gl.NEAREST);\n uniforms['u_depth_size_inv'] = [1 / this._depthFBO.width, 1 / this._depthFBO.height];\n }\n\n if (options && options.useMeterToDem && demTile) {\n const meterToDEM = (1 << demTile.tileID.canonical.z) * mercatorZfromAltitude(1, this.painter.transform.center.lat) * this.sourceCache.getSource().tileSize;\n uniforms['u_meter_to_dem'] = meterToDEM;\n }\n if (options && options.labelPlaneMatrixInv) {\n uniforms['u_label_plane_matrix_inv'] = options.labelPlaneMatrixInv;\n }\n program.setTerrainUniformValues(context, uniforms);\n }\n\n // For each proxy tile, render all layers until the non-draped layer (and\n // render the tile to the screen) before advancing to the next proxy tile.\n // Returns the last drawn index that is used as a start\n // layer for interleaved draped rendering.\n // Apart to layer-by-layer rendering used in 2D, here we have proxy-tile-by-proxy-tile\n // rendering.\n renderBatch(startLayerIndex: number): number {\n if (this._drapedRenderBatches.length === 0) {\n return startLayerIndex + 1;\n }\n\n this.renderingToTexture = true;\n const painter = this.painter;\n const context = this.painter.context;\n const psc = this.proxySourceCache;\n const proxies = this.proxiedCoords[psc.id];\n const setupRenderToScreen = () => {\n context.bindFramebuffer.set(null);\n context.viewport.set([0, 0, painter.width, painter.height]);\n this.renderingToTexture = false;\n };\n\n // Consume batch of sequential drape layers and move next\n const drapedLayerBatch = this._drapedRenderBatches.shift();\n assert(drapedLayerBatch.start === startLayerIndex);\n\n let drawAsRasterCoords = [];\n const layerIds = painter.style.order;\n\n let poolIndex = 0;\n for (let i = 0; i < proxies.length; i++) {\n const proxy = proxies[i];\n\n // bind framebuffer and assign texture to the tile (texture used in drawTerrainRaster).\n const tile = psc.getTileByID(proxy.proxyTileKey);\n const renderCacheIndex = psc.proxyCachedFBO[proxy.key] ? psc.proxyCachedFBO[proxy.key][startLayerIndex] : undefined;\n\n let fbo;\n if (renderCacheIndex !== undefined) {\n fbo = this.currentFBO = psc.renderCache[renderCacheIndex];\n } else {\n fbo = this.currentFBO = this.pool[poolIndex++];\n }\n tile.texture = fbo.tex;\n\n if (renderCacheIndex !== undefined && !fbo.dirty) {\n // Use cached render from previous pass, no need to render again.\n drawAsRasterCoords.push(tile.tileID);\n continue;\n }\n\n context.bindFramebuffer.set(fbo.fb.framebuffer);\n this.renderedToTile = false; // reset flag.\n if (fbo.dirty) {\n // Clear on start.\n context.clear({color: Color.transparent});\n fbo.dirty = false;\n }\n\n let currentStencilSource; // There is no need to setup stencil for the same source for consecutive layers.\n for (let j = drapedLayerBatch.start; j <= drapedLayerBatch.end; ++j) {\n const layer = painter.style._layers[layerIds[j]];\n const hidden = layer.isHidden(painter.transform.zoom);\n assert(this._style.isLayerDraped(layer) || hidden);\n if (hidden) continue;\n\n const sourceCache = painter.style._getLayerSourceCache(layer);\n const proxiedCoords = sourceCache ? this.proxyToSource[proxy.key][sourceCache.id] : [proxy];\n if (!proxiedCoords) continue; // when tile is not loaded yet for the source cache.\n\n const coords = ((proxiedCoords: any): Array<OverscaledTileID>);\n context.viewport.set([0, 0, fbo.fb.width, fbo.fb.height]);\n if (currentStencilSource !== (sourceCache ? sourceCache.id : null)) {\n this._setupStencil(proxiedCoords, layer, sourceCache);\n currentStencilSource = sourceCache ? sourceCache.id : null;\n }\n painter.renderLayer(painter, sourceCache, layer, coords);\n }\n\n fbo.dirty = this.renderedToTile;\n if (this.renderedToTile) drawAsRasterCoords.push(tile.tileID);\n\n if (poolIndex === FBO_POOL_SIZE) {\n poolIndex = 0;\n if (drawAsRasterCoords.length > 0) {\n setupRenderToScreen();\n drawTerrainRaster(painter, this, psc, drawAsRasterCoords, this._updateTimestamp);\n this.renderingToTexture = true;\n drawAsRasterCoords = [];\n }\n }\n }\n\n setupRenderToScreen();\n if (drawAsRasterCoords.length > 0) {\n drawTerrainRaster(painter, this, psc, drawAsRasterCoords, this._updateTimestamp);\n }\n\n return drapedLayerBatch.end + 1;\n }\n\n postRender() {\n // Make sure we consumed all the draped terrain batches at this point\n assert(this._drapedRenderBatches.length === 0);\n }\n\n renderCacheEfficiency(style: Style): Object {\n const layerCount = style.order.length;\n\n if (layerCount === 0) {\n return {efficiency: 100.0};\n }\n\n let uncacheableLayerCount = 0;\n let drapedLayerCount = 0;\n let reachedUndrapedLayer = false;\n let firstUndrapedLayer;\n\n for (let i = 0; i < layerCount; ++i) {\n const layer = style._layers[style.order[i]];\n if (!this._style.isLayerDraped(layer)) {\n if (!reachedUndrapedLayer) {\n reachedUndrapedLayer = true;\n firstUndrapedLayer = layer.id;\n }\n } else {\n if (reachedUndrapedLayer) {\n ++uncacheableLayerCount;\n }\n ++drapedLayerCount;\n }\n }\n\n if (drapedLayerCount === 0) {\n return {efficiency: 100.0};\n }\n\n return {efficiency: (1.0 - uncacheableLayerCount / drapedLayerCount) * 100.0, firstUndrapedLayer};\n }\n\n // Performs raycast against visible DEM tiles on the screen and returns the distance travelled along the ray.\n // x & y components of the position are expected to be in normalized mercator coordinates [0, 1] and z in meters.\n raycast(pos: vec3, dir: vec3, exaggeration: number): ?number {\n if (!this._visibleDemTiles)\n return null;\n\n // Perform initial raycasts against root nodes of the available dem tiles\n // and use this information to sort them from closest to furthest.\n const preparedTiles = this._visibleDemTiles.filter(tile => tile.dem).map(tile => {\n const id = tile.tileID;\n const tiles = Math.pow(2.0, id.overscaledZ);\n const {x, y} = id.canonical;\n\n // Compute tile boundaries in mercator coordinates\n const minx = x / tiles;\n const maxx = (x + 1) / tiles;\n const miny = y / tiles;\n const maxy = (y + 1) / tiles;\n const tree = (tile.dem: any).tree;\n\n return {\n minx, miny, maxx, maxy,\n t: tree.raycastRoot(minx, miny, maxx, maxy, pos, dir, exaggeration),\n tile\n };\n });\n\n preparedTiles.sort((a, b) => {\n const at = a.t !== null ? a.t : Number.MAX_VALUE;\n const bt = b.t !== null ? b.t : Number.MAX_VALUE;\n return at - bt;\n });\n\n for (const obj of preparedTiles) {\n if (obj.t == null)\n return null;\n\n // Perform more accurate raycast against the dem tree. First intersection is the closest on\n // as all tiles are sorted from closest to furthest\n const tree = (obj.tile.dem: any).tree;\n const t = tree.raycast(obj.minx, obj.miny, obj.maxx, obj.maxy, pos, dir, exaggeration);\n\n if (t != null)\n return t;\n }\n\n return null;\n }\n\n _createFBO(): FBO {\n const painter = this.painter;\n const context = painter.context;\n const gl = context.gl;\n const bufferSize = this.drapeBufferSize;\n context.activeTexture.set(gl.TEXTURE0);\n const tex = new Texture(context, {width: bufferSize[0], height: bufferSize[1], data: null}, gl.RGBA);\n tex.bind(gl.LINEAR, gl.CLAMP_TO_EDGE);\n const fb = context.createFramebuffer(bufferSize[0], bufferSize[1], false);\n fb.colorAttachment.set(tex.texture);\n\n if (context.extTextureFilterAnisotropic && !context.extTextureFilterAnisotropicForceOff) {\n gl.texParameterf(gl.TEXTURE_2D,\n context.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,\n context.extTextureFilterAnisotropicMax);\n }\n\n return {fb, tex, dirty: false, ref: 1};\n }\n\n _initFBOPool() {\n while (this.pool.length < Math.min(FBO_POOL_SIZE, this.proxyCoords.length)) {\n this.pool.push(this._createFBO());\n }\n }\n\n _shouldDisableRenderCache(): boolean {\n // Disable render caches on dynamic events due to fading.\n const isCrossFading = id => {\n const layer = this._style._layers[id];\n const isHidden = !layer.isHidden(this.painter.transform.zoom);\n const crossFade = layer.getCrossfadeParameters();\n const isFading = !!crossFade && crossFade.t !== 1;\n return layer.type !== 'custom' && !isHidden && isFading;\n };\n return !this.renderCached || this._style.order.some(isCrossFading);\n }\n\n _clearRasterFadeFromRenderCache() {\n let hasRasterSource = false;\n for (const id in this._style._sourceCaches) {\n if (this._style._sourceCaches[id]._source instanceof RasterTileSource) {\n hasRasterSource = true;\n break;\n }\n }\n if (!hasRasterSource) {\n return;\n }\n\n // Check if any raster tile is in a fading state\n for (let i = 0; i < this._style.order.length; ++i) {\n const layer = this._style._layers[this._style.order[i]];\n const isHidden = layer.isHidden(this.painter.transform.zoom);\n const sourceCache = this._style._getLayerSourceCache(layer);\n if (layer.type !== 'raster' || isHidden || !sourceCache) { continue; }\n\n const rasterLayer = ((layer: any): RasterStyleLayer);\n const fadeDuration = rasterLayer.paint.get('raster-fade-duration');\n for (const proxy of this.proxyCoords) {\n const proxiedCoords = this.proxyToSource[proxy.key][sourceCache.id];\n const coords = ((proxiedCoords: any): Array<OverscaledTileID>);\n if (!coords) { continue; }\n\n for (const coord of coords) {\n const tile = sourceCache.getTile(coord);\n const parent = sourceCache.findLoadedParent(coord, 0);\n const fade = rasterFade(tile, parent, sourceCache, this.painter.transform, fadeDuration);\n const isFading = fade.opacity !== 1 || fade.mix !== 0;\n if (isFading) {\n this._clearRenderCacheForTile(sourceCache.id, coord);\n }\n }\n }\n }\n }\n\n _setupDrapedRenderBatches() {\n const layerIds = this._style.order;\n const layerCount = layerIds.length;\n if (layerCount === 0) {\n return;\n }\n\n const batches = [];\n\n let currentLayer = 0;\n let layer = this._style._layers[layerIds[currentLayer]];\n while (!this._style.isLayerDraped(layer) && layer.isHidden(this.painter.transform.zoom) && ++currentLayer < layerCount) {\n layer = this._style._layers[layerIds[currentLayer]];\n }\n\n let batchStart;\n for (; currentLayer < layerCount; ++currentLayer) {\n const layer = this._style._layers[layerIds[currentLayer]];\n if (layer.isHidden(this.painter.transform.zoom)) {\n continue;\n }\n if (!this._style.isLayerDraped(layer)) {\n if (batchStart !== undefined) {\n batches.push({start: batchStart, end: currentLayer - 1});\n batchStart = undefined;\n }\n continue;\n }\n if (batchStart === undefined) {\n batchStart = currentLayer;\n }\n }\n\n if (batchStart !== undefined) {\n batches.push({start: batchStart, end: currentLayer - 1});\n }\n\n if (this._style.map._optimizeForTerrain) {\n // Draped first approach should result in a single or no batch\n assert(batches.length === 1 || batches.length === 0);\n }\n\n this._drapedRenderBatches = batches;\n }\n\n _setupRenderCache(previousProxyToSource: {[number]: {[string]: Array<ProxiedTileID>}}) {\n const psc = this.proxySourceCache;\n if (this._shouldDisableRenderCache()) {\n if (psc.renderCache.length > psc.renderCachePool.length) {\n const used = ((Object.values(psc.proxyCachedFBO): any): Array<{[string | number]: number}>);\n psc.proxyCachedFBO = {};\n for (let i = 0; i < used.length; ++i) {\n const fbos = ((Object.values(used[i]): any): Array<number>);\n psc.renderCachePool.push(...fbos);\n }\n assert(psc.renderCache.length === psc.renderCachePool.length);\n }\n return;\n }\n\n this._clearRasterFadeFromRenderCache();\n\n const coords = this.proxyCoords;\n const dirty = this._tilesDirty;\n for (let i = coords.length - 1; i >= 0; i--) {\n const proxy = coords[i];\n const tile = psc.getTileByID(proxy.key);\n\n if (psc.proxyCachedFBO[proxy.key] !== undefined) {\n assert(tile.texture);\n const prev = previousProxyToSource[proxy.key];\n assert(prev);\n // Reuse previous render from cache if there was no change of\n // content that was used to render proxy tile.\n const current = this.proxyToSource[proxy.key];\n let equal = 0;\n for (const source in current) {\n const tiles = current[source];\n const prevTiles = prev[source];\n if (!prevTiles || prevTiles.length !== tiles.length ||\n tiles.some((t, index) => (t !== prevTiles[index] || (dirty[source] && dirty[source].hasOwnProperty(t.key))))) {\n equal = -1;\n break;\n }\n ++equal;\n }\n // dirty === false: doesn't need to be rendered to, just use cached render.\n for (const proxyFBO in psc.proxyCachedFBO[proxy.key]) {\n psc.renderCache[psc.proxyCachedFBO[proxy.key][proxyFBO]].dirty = equal < 0 || equal !== Object.values(prev).length;\n }\n } else {\n for (let j = 0; j < this._drapedRenderBatches.length; ++j) {\n const batch = this._drapedRenderBatches[j];\n // Assign renderCache FBO if there are available FBOs in pool.\n let index = psc.renderCachePool.pop();\n if (index === undefined && psc.renderCache.length < RENDER_CACHE_MAX_SIZE) {\n index = psc.renderCache.length;\n psc.renderCache.push(this._createFBO());\n // assert(psc.renderCache.length <= coords.length);\n }\n if (index !== undefined) {\n if (psc.proxyCachedFBO[proxy.key] === undefined)\n psc.proxyCachedFBO[proxy.key] = {};\n psc.proxyCachedFBO[proxy.key][batch.start] = index;\n psc.renderCache[index].dirty = true; // needs to be rendered to.\n }\n }\n }\n }\n this._tilesDirty = {};\n }\n\n _setupStencil(proxiedCoords: Array<ProxiedTileID>, layer: StyleLayer, sourceCache?: SourceCache) {\n if (!sourceCache || !this._sourceTilesOverlap[sourceCache.id]) {\n if (this._overlapStencilType) this._overlapStencilType = false;\n return;\n }\n const context = this.painter.context;\n const gl = context.gl;\n\n // If needed, setup stencilling. Don't bother to remove when there is no\n // more need: in such case, if there is no overlap, stencilling is disabled.\n if (proxiedCoords.length <= 1) { this._overlapStencilType = false; return; }\n\n const fbo = this.currentFBO;\n const fb = fbo.fb;\n let stencilRange;\n if (layer.isTileClipped()) {\n stencilRange = proxiedCoords.length;\n this._overlapStencilMode.test = {func: gl.EQUAL, mask: 0xFF};\n this._overlapStencilType = 'Clip';\n } else if (proxiedCoords[0].overscaledZ > proxiedCoords[proxiedCoords.length - 1].overscaledZ) {\n stencilRange = 1;\n this._overlapStencilMode.test = {func: gl.GREATER, mask: 0xFF};\n this._overlapStencilType = 'Mask';\n } else {\n this._overlapStencilType = false;\n return;\n }\n if (!fb.depthAttachment) {\n const renderbuffer = context.createRenderbuffer(context.gl.DEPTH_STENCIL, fb.width, fb.height);\n fb.depthAttachment = new DepthStencilAttachment(context, fb.framebuffer);\n fb.depthAttachment.set(renderbuffer);\n context.clear({stencil: 0});\n }\n if (fbo.ref + stencilRange > 255) {\n context.clear({stencil: 0});\n fbo.ref = 0;\n }\n fbo.ref += stencilRange;\n this._overlapStencilMode.ref = fbo.ref;\n if (layer.isTileClipped()) {\n this._renderTileClippingMasks(proxiedCoords, this._overlapStencilMode.ref);\n }\n }\n\n stencilModeForRTTOverlap(id: OverscaledTileID) {\n if (!this.renderingToTexture || !this._overlapStencilType) {\n return StencilMode.disabled;\n }\n // All source tiles contributing to the same proxy are processed in sequence, in zoom descending order.\n // For raster / hillshade overlap masking, ref is based on zoom dif.\n // For vector layer clipping, every tile gets dedicated stencil ref.\n if (this._overlapStencilType === 'Clip') {\n // In immediate 2D mode, we render rects to mark clipping area and handle behavior on tile borders.\n // Here, there is no need for now for this:\n // 1. overlap is handled by proxy render to texture tiles (there is no overlap there)\n // 2. here we handle only brief zoom out semi-transparent color intensity flickering\n // and that is avoided fine by stenciling primitives as part of drawing (instead of additional tile quad step).\n this._overlapStencilMode.ref = this.painter._tileClippingMaskIDs[id.key];\n } // else this._overlapStencilMode.ref is set to a single value used per proxy tile, in _setupStencil.\n return this._overlapStencilMode;\n }\n\n _renderTileClippingMasks(proxiedCoords: Array<ProxiedTileID>, ref: number) {\n const painter = this.painter;\n const context = this.painter.context;\n const gl = context.gl;\n painter._tileClippingMaskIDs = {};\n context.setColorMode(ColorMode.disabled);\n context.setDepthMode(DepthMode.disabled);\n\n const program = painter.useProgram('clippingMask');\n\n for (const tileID of proxiedCoords) {\n const id = painter._tileClippingMaskIDs[tileID.key] = --ref;\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', painter.tileExtentBuffer,\n painter.quadTriangleIndexBuffer, painter.tileExtentSegments);\n }\n }\n\n // Casts a ray from a point on screen and returns the intersection point with the terrain.\n // The returned point contains the mercator coordinates in its first 3 components, and elevation\n // in meter in its 4th coordinate.\n pointCoordinate(screenPoint: Point): ?vec4 {\n const transform = this.painter.transform;\n if (screenPoint.x < 0 || screenPoint.x > transform.width ||\n screenPoint.y < 0 || screenPoint.y > transform.height) {\n return null;\n }\n\n const far = [screenPoint.x, screenPoint.y, 1, 1];\n vec4.transformMat4(far, far, transform.pixelMatrixInverse);\n vec4.scale(far, far, 1.0 / far[3]);\n // x & y in pixel coordinates, z is altitude in meters\n far[0] /= transform.worldSize;\n far[1] /= transform.worldSize;\n const camera = transform._camera.position;\n const mercatorZScale = mercatorZfromAltitude(1, transform.center.lat);\n const p = [camera[0], camera[1], camera[2] / mercatorZScale, 0.0];\n const dir = vec3.subtract([], far.slice(0, 3), p);\n vec3.normalize(dir, dir);\n const distanceAlongRay = this.raycast(p, dir, this._exaggeration);\n\n if (distanceAlongRay === null || !distanceAlongRay) return null;\n vec3.scaleAndAdd(p, p, dir, distanceAlongRay);\n p[3] = p[2];\n p[2] *= mercatorZScale;\n return p;\n }\n\n drawDepth() {\n const painter = this.painter;\n const context = painter.context;\n const psc = this.proxySourceCache;\n\n const width = Math.ceil(painter.width), height = Math.ceil(painter.height);\n if (this._depthFBO && (this._depthFBO.width !== width || this._depthFBO.height !== height)) {\n this._depthFBO.destroy();\n delete this._depthFBO;\n delete this._depthTexture;\n }\n if (!this._depthFBO) {\n const gl = context.gl;\n const fbo = context.createFramebuffer(width, height, true);\n context.activeTexture.set(gl.TEXTURE0);\n const texture = new Texture(context, {width, height, data: null}, gl.RGBA);\n texture.bind(gl.NEAREST, gl.CLAMP_TO_EDGE);\n fbo.colorAttachment.set(texture.texture);\n const renderbuffer = context.createRenderbuffer(context.gl.DEPTH_COMPONENT16, width, height);\n fbo.depthAttachment.set(renderbuffer);\n this._depthFBO = fbo;\n this._depthTexture = texture;\n }\n context.bindFramebuffer.set(this._depthFBO.framebuffer);\n context.viewport.set([0, 0, width, height]);\n\n drawTerrainDepth(painter, this, psc, this.proxyCoords);\n }\n\n _setupProxiedCoordsForOrtho(sourceCache: SourceCache, sourceCoords: Array<OverscaledTileID>, previousProxyToSource: {[number]: {[string]: Array<ProxiedTileID>}}) {\n if (sourceCache.getSource() instanceof ImageSource) {\n return this._setupProxiedCoordsForImageSource(sourceCache, sourceCoords, previousProxyToSource);\n }\n this._findCoveringTileCache[sourceCache.id] = this._findCoveringTileCache[sourceCache.id] || {};\n const coords = this.proxiedCoords[sourceCache.id] = [];\n const proxys = this.proxyCoords;\n for (let i = 0; i < proxys.length; i++) {\n const proxyTileID = proxys[i];\n const proxied = this._findTileCoveringTileID(proxyTileID, sourceCache);\n if (proxied) {\n assert(proxied.hasData());\n const id = this._createProxiedId(proxyTileID, proxied, previousProxyToSource[proxyTileID.key] && previousProxyToSource[proxyTileID.key][sourceCache.id]);\n coords.push(id);\n this.proxyToSource[proxyTileID.key][sourceCache.id] = [id];\n }\n }\n let hasOverlap = false;\n for (let i = 0; i < sourceCoords.length; i++) {\n const tile = sourceCache.getTile(sourceCoords[i]);\n if (!tile || !tile.hasData()) continue;\n const proxy = this._findTileCoveringTileID(tile.tileID, this.proxySourceCache);\n // Don't add the tile if already added in loop above.\n if (proxy && proxy.tileID.canonical.z !== tile.tileID.canonical.z) {\n const array = this.proxyToSource[proxy.tileID.key][sourceCache.id];\n const id = this._createProxiedId(proxy.tileID, tile, previousProxyToSource[proxy.tileID.key] && previousProxyToSource[proxy.tileID.key][sourceCache.id]);\n if (!array) {\n this.proxyToSource[proxy.tileID.key][sourceCache.id] = [id];\n } else {\n // The last element is parent added in loop above. This way we get\n // a list in Z descending order which is needed for stencil masking.\n array.splice(array.length - 1, 0, id);\n }\n coords.push(id);\n hasOverlap = true;\n }\n }\n this._sourceTilesOverlap[sourceCache.id] = hasOverlap;\n }\n\n _setupProxiedCoordsForImageSource(sourceCache: SourceCache, sourceCoords: Array<OverscaledTileID>, previousProxyToSource: {[number]: {[string]: Array<ProxiedTileID>}}) {\n if (!sourceCache.getSource().loaded()) return;\n\n const coords = this.proxiedCoords[sourceCache.id] = [];\n const proxys = this.proxyCoords;\n const imageSource: ImageSource = ((sourceCache.getSource(): any): ImageSource);\n\n const anchor = new Point(imageSource.tileID.x, imageSource.tileID.y)._div(1 << imageSource.tileID.z);\n const aabb = imageSource.coordinates.map(MercatorCoordinate.fromLngLat).reduce((acc, coord) => {\n acc.min.x = Math.min(acc.min.x, coord.x - anchor.x);\n acc.min.y = Math.min(acc.min.y, coord.y - anchor.y);\n acc.max.x = Math.max(acc.max.x, coord.x - anchor.x);\n acc.max.y = Math.max(acc.max.y, coord.y - anchor.y);\n return acc;\n }, {min: new Point(Number.MAX_VALUE, Number.MAX_VALUE), max: new Point(-Number.MAX_VALUE, -Number.MAX_VALUE)});\n\n // Fast conservative check using aabb: content outside proxy tile gets clipped out by on render, anyway.\n const tileOutsideImage = (tileID, imageTileID) => {\n const x = tileID.wrap + tileID.canonical.x / (1 << tileID.canonical.z);\n const y = tileID.canonical.y / (1 << tileID.canonical.z);\n const d = EXTENT / (1 << tileID.canonical.z);\n\n const ix = imageTileID.wrap + imageTileID.canonical.x / (1 << imageTileID.canonical.z);\n const iy = imageTileID.canonical.y / (1 << imageTileID.canonical.z);\n\n return x + d < ix + aabb.min.x || x > ix + aabb.max.x || y + d < iy + aabb.min.y || y > iy + aabb.max.y;\n };\n\n for (let i = 0; i < proxys.length; i++) {\n const proxyTileID = proxys[i];\n for (let j = 0; j < sourceCoords.length; j++) {\n const tile = sourceCache.getTile(sourceCoords[j]);\n if (!tile || !tile.hasData()) continue;\n\n // Setup proxied -> proxy mapping only if image on given tile wrap intersects the proxy tile.\n if (tileOutsideImage(proxyTileID, tile.tileID)) continue;\n\n const id = this._createProxiedId(proxyTileID, tile, previousProxyToSource[proxyTileID.key] && previousProxyToSource[proxyTileID.key][sourceCache.id]);\n const array = this.proxyToSource[proxyTileID.key][sourceCache.id];\n if (!array) {\n this.proxyToSource[proxyTileID.key][sourceCache.id] = [id];\n } else {\n array.push(id);\n }\n coords.push(id);\n }\n }\n }\n\n // recycle is previous pass content that likely contains proxied ID combining proxy and source tile.\n _createProxiedId(proxyTileID: OverscaledTileID, tile: Tile, recycle: Array<ProxiedTileID>): ProxiedTileID {\n let matrix = this.orthoMatrix;\n if (recycle) {\n const recycled = recycle.find(proxied => (proxied.key === tile.tileID.key));\n if (recycled) return recycled;\n }\n if (tile.tileID.key !== proxyTileID.key) {\n const scale = proxyTileID.canonical.z - tile.tileID.canonical.z;\n matrix = mat4.create();\n let size, xOffset, yOffset;\n const wrap = (tile.tileID.wrap - proxyTileID.wrap) << proxyTileID.overscaledZ;\n if (scale > 0) {\n size = EXTENT >> scale;\n xOffset = size * ((tile.tileID.canonical.x << scale) - proxyTileID.canonical.x + wrap);\n yOffset = size * ((tile.tileID.canonical.y << scale) - proxyTileID.canonical.y);\n } else {\n size = EXTENT << -scale;\n xOffset = EXTENT * (tile.tileID.canonical.x - ((proxyTileID.canonical.x + wrap) << -scale));\n yOffset = EXTENT * (tile.tileID.canonical.y - (proxyTileID.canonical.y << -scale));\n }\n mat4.ortho(matrix, 0, size, 0, size, 0, 1);\n mat4.translate(matrix, matrix, [xOffset, yOffset, 0]);\n }\n return new ProxiedTileID(tile.tileID, proxyTileID.key, matrix);\n }\n\n // A variant of SourceCache.findLoadedParent that considers only visible\n // tiles (and doesn't check SourceCache._cache). Another difference is in\n // caching \"not found\" results along the lookup, to leave the lookup early.\n // Not found is cached by this._findCoveringTileCache[key] = null;\n _findTileCoveringTileID(tileID: OverscaledTileID, sourceCache: SourceCache): ?Tile {\n let tile = sourceCache.getTile(tileID);\n if (tile && tile.hasData()) return tile;\n\n const lookup = this._findCoveringTileCache[sourceCache.id];\n const key = lookup[tileID.key];\n tile = key ? sourceCache.getTileByID(key) : null;\n if ((tile && tile.hasData()) || key === null) return tile;\n\n assert(!key || tile);\n let sourceTileID = tile ? tile.tileID : tileID;\n let z = sourceTileID.overscaledZ;\n const minzoom = sourceCache.getSource().minzoom;\n const path = [];\n if (!key) {\n const maxzoom = sourceCache.getSource().maxzoom;\n if (tileID.canonical.z >= maxzoom) {\n const downscale = tileID.canonical.z - maxzoom;\n if (sourceCache.getSource().reparseOverscaled) {\n z = Math.max(tileID.canonical.z + 2, sourceCache.transform.tileZoom);\n sourceTileID = new OverscaledTileID(z, tileID.wrap, maxzoom,\n tileID.canonical.x >> downscale, tileID.canonical.y >> downscale);\n } else if (downscale !== 0) {\n z = maxzoom;\n sourceTileID = new OverscaledTileID(z, tileID.wrap, maxzoom,\n tileID.canonical.x >> downscale, tileID.canonical.y >> downscale);\n }\n }\n if (sourceTileID.key !== tileID.key) {\n path.push(sourceTileID.key);\n tile = sourceCache.getTile(sourceTileID);\n }\n }\n\n const pathToLookup = (key) => {\n path.forEach(id => { lookup[id] = key; });\n path.length = 0;\n };\n\n for (z = z - 1; z >= minzoom && !(tile && tile.hasData()); z--) {\n if (tile) {\n pathToLookup(tile.tileID.key); // Store lookup to parents not loaded (yet).\n }\n const id = sourceTileID.calculateScaledKey(z);\n tile = sourceCache.getTileByID(id);\n if (tile && tile.hasData()) break;\n const key = lookup[id];\n if (key === null) {\n break; // There's no tile loaded and no point searching further.\n } else if (key !== undefined) {\n tile = sourceCache.getTileByID(key);\n assert(tile);\n continue;\n }\n path.push(id);\n }\n\n pathToLookup(tile ? tile.tileID.key : null);\n return tile && tile.hasData() ? tile : null;\n }\n\n findDEMTileFor(tileID: OverscaledTileID): ?Tile {\n return this.enabled ? this._findTileCoveringTileID(tileID, this.sourceCache) : null;\n }\n\n /*\n * Bookkeeping if something gets rendered to the tile.\n */\n prepareDrawTile(coord: OverscaledTileID) {\n if (!this.renderedToTile) {\n this.renderedToTile = true;\n }\n }\n\n _clearRenderCacheForTile(source: string, coord: OverscaledTileID) {\n let sourceTiles = this._tilesDirty[source];\n if (!sourceTiles) sourceTiles = this._tilesDirty[source] = {};\n sourceTiles[coord.key] = true;\n }\n}\n\nfunction sortByDistanceToCamera(tileIDs, painter) {\n const cameraCoordinate = painter.transform.pointCoordinate(painter.transform.getCameraPoint());\n const cameraPoint = new Point(cameraCoordinate.x, cameraCoordinate.y);\n tileIDs.sort((a, b) => {\n if (b.overscaledZ - a.overscaledZ) return b.overscaledZ - a.overscaledZ;\n const aPoint = new Point(a.canonical.x + (1 << a.canonical.z) * a.wrap, a.canonical.y);\n const bPoint = new Point(b.canonical.x + (1 << b.canonical.z) * b.wrap, b.canonical.y);\n const cameraScaled = cameraPoint.mult(1 << a.canonical.z);\n cameraScaled.x -= 0.5;\n cameraScaled.y -= 0.5;\n return cameraScaled.distSqr(aPoint) - cameraScaled.distSqr(bPoint);\n });\n}\n\n/**\n * Creates uniform grid of triangles, covering EXTENT x EXTENT square, with two\n * adjustent traigles forming a quad, so that there are |count| columns and rows\n * of these quads in EXTENT x EXTENT square.\n * e.g. for count of 2:\n * -------------\n * | /| /|\n * | / | / |\n * |/ |/ |\n * -------------\n * | /| /|\n * | / | / |\n * |/ |/ |\n * -------------\n * @param {number} count Count of rows and columns\n * @private\n */\nfunction createGrid(count: number): [RasterBoundsArray, TriangleIndexArray, number] {\n const boundsArray = new RasterBoundsArray();\n // Around the grid, add one more row/column padding for \"skirt\".\n const indexArray = new TriangleIndexArray();\n const size = count + 2;\n boundsArray.reserve(size * size);\n indexArray.reserve((size - 1) * (size - 1) * 2);\n const step = EXTENT / (count - 1);\n const gridBound = EXTENT + step / 2;\n const bound = gridBound + step;\n\n // Skirt offset of 0x5FFF is chosen randomly to encode boolean value (skirt\n // on/off) with x position (max value EXTENT = 4096) to 16-bit signed integer.\n const skirtOffset = 24575; // 0x5FFF\n for (let y = -step; y < bound; y += step) {\n for (let x = -step; x < bound; x += step) {\n const offset = (x < 0 || x > gridBound || y < 0 || y > gridBound) ? skirtOffset : 0;\n const xi = clamp(Math.round(x), 0, EXTENT);\n const yi = clamp(Math.round(y), 0, EXTENT);\n boundsArray.emplaceBack(xi + offset, yi, xi, yi);\n }\n }\n\n // For cases when there's no need to render \"skirt\", the \"inner\" grid indices\n // are followed by skirt indices.\n const skirtIndicesOffset = (size - 3) * (size - 3) * 2;\n const quad = (i, j) => {\n const index = j * size + i;\n indexArray.emplaceBack(index + 1, index, index + size);\n indexArray.emplaceBack(index + size, index + size + 1, index + 1);\n };\n for (let j = 1; j < size - 2; j++) {\n for (let i = 1; i < size - 2; i++) {\n quad(i, j);\n }\n }\n // Padding (skirt) indices:\n [0, size - 2].forEach(j => {\n for (let i = 0; i < size - 1; i++) {\n quad(i, j);\n quad(j, i);\n }\n });\n return [boundsArray, indexArray, skirtIndicesOffset];\n}\n\nexport type TerrainUniformsType = {|\n 'u_dem': Uniform1i,\n 'u_dem_prev': Uniform1i,\n 'u_dem_unpack': Uniform4f,\n 'u_dem_tl': Uniform2f,\n 'u_dem_scale': Uniform1f,\n 'u_dem_tl_prev': Uniform2f,\n 'u_dem_scale_prev': Uniform1f,\n 'u_dem_size': Uniform1f,\n 'u_dem_lerp': Uniform1f,\n \"u_exaggeration\": Uniform1f,\n 'u_depth': Uniform1i,\n 'u_depth_size_inv': Uniform2f,\n 'u_meter_to_dem'?: Uniform1f,\n 'u_label_plane_matrix_inv'?: UniformMatrix4f\n|};\n\nexport const terrainUniforms = (context: Context, locations: UniformLocations): TerrainUniformsType => ({\n 'u_dem': new Uniform1i(context, locations.u_dem),\n 'u_dem_prev': new Uniform1i(context, locations.u_dem_prev),\n 'u_dem_unpack': new Uniform4f(context, locations.u_dem_unpack),\n 'u_dem_tl': new Uniform2f(context, locations.u_dem_tl),\n 'u_dem_scale': new Uniform1f(context, locations.u_dem_scale),\n 'u_dem_tl_prev': new Uniform2f(context, locations.u_dem_tl_prev),\n 'u_dem_scale_prev': new Uniform1f(context, locations.u_dem_scale_prev),\n 'u_dem_size': new Uniform1f(context, locations.u_dem_size),\n 'u_dem_lerp': new Uniform1f(context, locations.u_dem_lerp),\n 'u_exaggeration': new Uniform1f(context, locations.u_exaggeration),\n 'u_depth': new Uniform1i(context, locations.u_depth),\n 'u_depth_size_inv': new Uniform2f(context, locations.u_depth_size_inv),\n 'u_meter_to_dem': new Uniform1f(context, locations.u_meter_to_dem),\n 'u_label_plane_matrix_inv': new UniformMatrix4f(context, locations.u_label_plane_matrix_inv)\n});\n\nfunction defaultTerrainUniforms(encoding: DEMEncoding): UniformValues<TerrainUniformsType> {\n return {\n 'u_dem': 2,\n 'u_dem_prev': 4,\n 'u_dem_unpack': DEMData.getUnpackVector(encoding),\n 'u_dem_tl': [0, 0],\n 'u_dem_tl_prev': [0, 0],\n 'u_dem_scale': 0,\n 'u_dem_scale_prev': 0,\n 'u_dem_size': 0,\n 'u_dem_lerp': 1.0,\n 'u_depth': 3,\n 'u_depth_size_inv': [0, 0],\n 'u_exaggeration': 0\n };\n}\n","// @flow\n\nimport {prelude, preludeTerrain} from '../shaders';\nimport assert from 'assert';\nimport ProgramConfiguration from '../data/program_configuration';\nimport VertexArrayObject from './vertex_array_object';\nimport Context from '../gl/context';\nimport {terrainUniforms} from '../terrain/terrain';\nimport type {TerrainUniformsType} from '../terrain/terrain';\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<WebGLRenderingContext, 'LINES'>\n | $PropertyType<WebGLRenderingContext, 'TRIANGLES'>\n | $PropertyType<WebGLRenderingContext, 'LINE_STRIP'>;\n\nfunction getTokenizedAttributesAndUniforms (array: Array<string>): Array<string> {\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<Us: UniformBindings> {\n program: WebGLProgram;\n attributes: {[_: string]: number};\n numAttributes: number;\n fixedUniforms: Us;\n binderUniforms: Array<BinderUniform>;\n failedToCreate: boolean;\n terrainUniforms: ?TerrainUniformsType;\n\n static cacheKey(name: string, defines: string[], programConfiguration: ?ProgramConfiguration): string {\n let key = `${name}${programConfiguration ? programConfiguration.cacheKey : ''}`;\n for (const define of defines) {\n key += `/${define}`;\n }\n return key;\n }\n\n constructor(context: Context,\n name: string,\n source: {fragmentSource: string, vertexSource: string, staticAttributes: Array<string>, staticUniforms: Array<string>},\n configuration: ?ProgramConfiguration,\n fixedUniforms: (Context, UniformLocations) => Us,\n fixedDefines: string[]) {\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 let defines = configuration ? configuration.defines() : [];\n defines = defines.concat(fixedDefines.map((define) => `#define ${define}`));\n\n const fragmentSource = defines.concat(prelude.fragmentSource, source.fragmentSource).join('\\n');\n const vertexSource = defines.concat(prelude.vertexSource, preludeTerrain.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 if (fixedDefines.indexOf('TERRAIN') !== -1) { this.terrainUniforms = terrainUniforms(context, uniformLocations); }\n }\n\n setTerrainUniformValues(context: Context, terrainUnformValues: UniformValues<TerrainUniformsType>) {\n if (!this.terrainUniforms) return;\n const uniforms: TerrainUniformsType = this.terrainUniforms;\n\n if (this.failedToCreate) return;\n context.program.set(this.program);\n\n for (const name in terrainUnformValues) {\n uniforms[name].set(terrainUnformValues[name]);\n }\n }\n\n draw(context: Context,\n drawMode: DrawMode,\n depthMode: $ReadOnly<DepthMode>,\n stencilMode: $ReadOnly<StencilMode>,\n colorMode: $ReadOnly<ColorMode>,\n cullFaceMode: $ReadOnly<CullFaceMode>,\n uniformValues: UniformValues<Us>,\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<PatternUniformsType> {\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<ResolvedImage>, crossfade: CrossfadeParameters, painter: Painter,\n tile: {tileID: OverscaledTileID, tileSize: number}\n): UniformValues<BackgroundPatternUniformsType> {\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<FillExtrusionUniformsType> => {\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 const anchor = light.properties.get('anchor');\n if (anchor === 'viewport') {\n mat3.fromRotation(lightMat, -painter.transform.angle);\n vec3.transformMat3(lightPos, lightPos, lightMat);\n }\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<FillExtrusionPatternUniformsType> => {\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","// @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<FillUniformsType> => ({\n 'u_matrix': matrix\n});\n\nconst fillPatternUniformValues = (\n matrix: Float32Array,\n painter: Painter,\n crossfade: CrossfadeParameters,\n tile: Tile\n): UniformValues<FillPatternUniformsType> => extend(\n fillUniformValues(matrix),\n patternUniformValues(crossfade, painter, tile)\n);\n\nconst fillOutlineUniformValues = (\n matrix: Float32Array,\n drawingBufferSize: [number, number]\n): UniformValues<FillOutlineUniformsType> => ({\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<FillOutlinePatternUniformsType> => 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 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_extrude_scale': Uniform2f,\n 'u_device_pixel_ratio': Uniform1f,\n 'u_matrix': UniformMatrix4f\n|};\n\nexport type CircleDefinesType = 'PITCH_WITH_MAP' | 'SCALE_WITH_MAP';\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_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<CircleUniformsType> => {\n const transform = painter.transform;\n\n let extrudeScale: [number, number];\n if (layer.paint.get('circle-pitch-alignment') === 'map') {\n const pixelRatio = pixelsToTileUnits(tile, 1, transform.zoom);\n extrudeScale = [pixelRatio, pixelRatio];\n } else {\n extrudeScale = transform.pixelsToGLUnits;\n }\n\n return {\n 'u_camera_to_center_distance': transform.cameraToCenterDistance,\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_device_pixel_ratio': browser.devicePixelRatio,\n 'u_extrude_scale': extrudeScale\n };\n};\n\nconst circleDefinesValues = (layer: CircleStyleLayer): CircleDefinesType[] => {\n const values = [];\n if (layer.paint.get('circle-pitch-alignment') === 'map') values.push('PITCH_WITH_MAP');\n if (layer.paint.get('circle-pitch-scale') === 'map') values.push('SCALE_WITH_MAP');\n\n return values;\n};\n\nexport {circleUniforms, circleUniformValues, circleDefinesValues};\n","// @flow\n\nimport {\n Uniform1f,\n Uniform2f,\n UniformMatrix4f\n} from '../uniform_binding';\nimport EXTENT from '../../data/extent';\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_extrude_scale': Uniform2f\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_extrude_scale': new Uniform2f(context, locations.u_extrude_scale)\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<CollisionUniformsType> => {\n const pixelRatio = EXTENT / tile.tileSize;\n return {\n 'u_matrix': matrix,\n 'u_camera_to_center_distance': transform.cameraToCenterDistance,\n 'u_extrude_scale': [transform.pixelsToGLUnits[0] / pixelRatio,\n transform.pixelsToGLUnits[1] / pixelRatio]\n };\n};\n\nconst collisionCircleUniformValues = (\n matrix: Float32Array,\n invMatrix: Float32Array,\n transform: Transform\n): UniformValues<CollisionCircleUniformsType> => {\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<DebugUniformsType> => ({\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 {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<HeatmapUniformsType> => ({\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<HeatmapTextureUniformsType> => {\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 matrix: ?Float32Array\n): UniformValues<LineUniformsType> => {\n const transform = painter.transform;\n\n return {\n 'u_matrix': calculateMatrix(painter, tile, layer, matrix),\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 matrix: ?Float32Array,\n imageHeight: number\n): UniformValues<LineGradientUniformsType> => {\n return extend(lineUniformValues(painter, tile, layer, matrix), {\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 matrix: ?Float32Array\n): UniformValues<LinePatternUniformsType> => {\n const transform = painter.transform;\n const tileZoomRatio = calculateTileRatio(tile, transform);\n return {\n 'u_matrix': calculateMatrix(painter, tile, layer, matrix),\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<Array<number>>,\n crossfade: CrossfadeParameters,\n matrix: ?Float32Array\n): UniformValues<LineSDFUniformsType> => {\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, matrix), {\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, matrix) {\n return painter.translatePosMatrix(\n matrix ? matrix : 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<RasterUniformsType> => ({\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\nexport type SymbolDefinesType = 'PITCH_WITH_MAP_TERRAIN';\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<SymbolIconUniformsType> => {\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<SymbolSDFUniformsType> => {\n const {cameraToCenterDistance, _pitch} = painter.transform;\n\n return extend(symbolIconUniformValues(functionType, size,\n rotateInShader, pitchWithMap, painter, matrix, labelPlaneMatrix,\n glCoordMatrix, isText, texSize), {\n 'u_gamma_scale': pitchWithMap ? cameraToCenterDistance * Math.cos(painter.terrain ? 0 : _pitch) : 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<SymbolIconUniformsType> => {\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 {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<BackgroundUniformsType> => ({\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<ResolvedImage>,\n tile: {tileID: OverscaledTileID, tileSize: number},\n crossfade: CrossfadeParameters\n): UniformValues<BackgroundPatternUniformsType> => 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 type {CircleDefinesType} from './circle_program';\nimport type {SymbolDefinesType} from './symbol_program';\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';\nimport {terrainRasterUniforms} from '../../terrain/terrain_raster_program';\nimport {skyboxUniforms, skyboxGradientUniforms} from './skybox_program';\nimport {skyboxCaptureUniforms} from './skybox_capture_program';\n\nexport type DynamicDefinesType = CircleDefinesType | SymbolDefinesType;\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 terrainRaster: terrainRasterUniforms,\n terrainDepth: terrainRasterUniforms,\n skybox: skyboxUniforms,\n skyboxGradient: skyboxGradientUniforms,\n skyboxCapture: skyboxCaptureUniforms\n};\n","// @flow\n\nimport {\n UniformMatrix4f,\n Uniform1i,\n Uniform3f,\n Uniform1f\n} from '../uniform_binding';\nimport {vec3} from 'gl-matrix';\nimport {degToRad} from '../../util/util';\n\nimport type {UniformValues, UniformLocations} from '../uniform_binding';\nimport type Context from '../../gl/context';\n\nexport type SkyboxUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_sun_direction': Uniform3f,\n 'u_cubemap': Uniform1i,\n 'u_opacity': Uniform1f,\n 'u_temporal_offset': Uniform1f\n|};\n\nexport type SkyboxGradientlUniformsType = {|\n 'u_matrix': UniformMatrix4f,\n 'u_color_ramp': Uniform1i,\n 'u_center_direction': Uniform3f,\n 'u_radius': Uniform1f,\n 'u_opacity': Uniform1f,\n 'u_temporal_offset': Uniform1f,\n|};\n\nconst skyboxUniforms = (context: Context, locations: UniformLocations): SkyboxUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_sun_direction': new Uniform3f(context, locations.u_sun_direction),\n 'u_cubemap': new Uniform1i(context, locations.u_cubemap),\n 'u_opacity': new Uniform1f(context, locations.u_opacity),\n 'u_temporal_offset': new Uniform1f(context, locations.u_temporal_offset)\n\n});\n\nconst skyboxUniformValues = (\n matrix: Float32Array,\n sunDirection: vec3,\n cubemap: number,\n opacity: number,\n temporalOffset: number\n): UniformValues<SkyboxUniformsType> => ({\n 'u_matrix': matrix,\n 'u_sun_direction': sunDirection,\n 'u_cubemap': cubemap,\n 'u_opacity': opacity,\n 'u_temporal_offset': temporalOffset\n});\n\nconst skyboxGradientUniforms = (context: Context, locations: UniformLocations): SkyboxGradientlUniformsType => ({\n 'u_matrix': new UniformMatrix4f(context, locations.u_matrix),\n 'u_color_ramp': new Uniform1i(context, locations.u_color_ramp),\n // radial gradient uniforms\n 'u_center_direction': new Uniform3f(context, locations.u_center_direction),\n 'u_radius': new Uniform1f(context, locations.u_radius),\n 'u_opacity': new Uniform1f(context, locations.u_opacity),\n 'u_temporal_offset': new Uniform1f(context, locations.u_temporal_offset)\n});\n\nconst skyboxGradientUniformValues = (\n matrix: Float32Array,\n centerDirection: vec3,\n radius: number, //degrees\n opacity: number,\n temporalOffset: number\n): UniformValues<SkyboxGradientlUniformsType> => {\n return {\n 'u_matrix': matrix,\n 'u_color_ramp': 0,\n 'u_center_direction': centerDirection,\n 'u_radius': degToRad(radius),\n 'u_opacity': opacity,\n 'u_temporal_offset': temporalOffset\n };\n};\n\nexport {\n skyboxUniforms,\n skyboxUniformValues,\n skyboxGradientUniforms,\n skyboxGradientUniformValues\n};\n","// @flow\n\nimport {vec3} from 'gl-matrix';\nimport type Color from '../../style-spec/util/color';\n\nimport {\n UniformMatrix3f,\n Uniform1f,\n Uniform3f,\n Uniform4f,\n} from '../uniform_binding';\nimport type {\n UniformValues,\n UniformLocations,\n} from '../uniform_binding';\nimport type Context from '../../gl/context';\n\nexport type SkyboxCaptureUniformsType = {|\n 'u_matrix_3f': UniformMatrix3f,\n 'u_sun_direction': Uniform3f,\n 'u_sun_intensity': Uniform1f,\n 'u_color_tint_r': Uniform4f,\n 'u_color_tint_m': Uniform4f,\n 'u_luminance': Uniform1f,\n|};\n\nconst skyboxCaptureUniforms = (context: Context, locations: UniformLocations): SkyboxCaptureUniformsType => ({\n 'u_matrix_3f': new UniformMatrix3f(context, locations.u_matrix_3f),\n 'u_sun_direction': new Uniform3f(context, locations.u_sun_direction),\n 'u_sun_intensity': new Uniform1f(context, locations.u_sun_intensity),\n 'u_color_tint_r': new Uniform4f(context, locations.u_color_tint_r),\n 'u_color_tint_m': new Uniform4f(context, locations.u_color_tint_m),\n 'u_luminance': new Uniform1f(context, locations.u_luminance),\n});\n\nconst skyboxCaptureUniformValues = (\n matrix: Float32Array,\n sunDirection: vec3,\n sunIntensity: number,\n atmosphereColor: Color,\n atmosphereHaloColor: Color\n): UniformValues<SkyboxCaptureUniformsType> => ({\n 'u_matrix_3f': matrix,\n 'u_sun_direction': sunDirection,\n 'u_sun_intensity': sunIntensity,\n 'u_color_tint_r': [\n atmosphereColor.r,\n atmosphereColor.g,\n atmosphereColor.b,\n atmosphereColor.a\n ],\n 'u_color_tint_m': [\n atmosphereHaloColor.r,\n atmosphereHaloColor.g,\n atmosphereHaloColor.b,\n atmosphereHaloColor.a\n ],\n 'u_luminance': 5e-5,\n});\n\nexport {\n skyboxCaptureUniforms,\n skyboxCaptureUniformValues,\n};\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<number>,\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<OverscaledTileID>, 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<TileBatch> = [];\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<number> = 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 if (painter.terrain) painter.terrain.setupElevationDraw(tile, program);\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,\n buffers.collisionVertexBuffer,\n buffers.collisionVertexBufferExt);\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 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';\nimport {getAnchorAlignment, WritingMode} from '../symbol/shaping';\nimport ONE_EM from '../symbol/one_em';\nimport {evaluateVariableOffset} from '../symbol/symbol_layout';\nimport Tile from '../source/tile';\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 tile: Tile,\n labelPlaneMatrixInv: ?Float32Array\n }\n};\n\nfunction drawSymbols(painter: Painter, sourceCache: SourceCache, layer: SymbolStyleLayer, coords: Array<OverscaledTileID>, 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 const elevation = tr.elevation;\n const getElevation = elevation ? (p => elevation.getAtTileOffset(coord, p.x, p.y)) : (_ => 0);\n updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, symbolSize,\n tr, labelPlaneMatrix, coord.posMatrix, tileScale, size, updateTextFitIcon, getElevation);\n }\n }\n}\n\nfunction updateVariableAnchorsForBucket(bucket, rotateWithMap, pitchWithMap, variableOffsets, symbolSize,\n transform, labelPlaneMatrix, posMatrix, tileScale, size, updateTextFitIcon, getElevation) {\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 elevation = getElevation(tileAnchor);\n const projectedAnchor = symbolProjection.project(tileAnchor, pitchWithMap ? posMatrix : labelPlaneMatrix, elevation);\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, elevation).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 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<SymbolTileRenderState> = [];\n const defines = painter.terrain && pitchWithMap ? ['PITCH_WITH_MAP_TERRAIN'] : null;\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, defines);\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 // labelPlaneMatrixInv is used for converting vertex pos to tile coordinates needed for sampling elevation.\n const labelPlaneMatrixInv = painter.terrain && pitchWithMap && alongLine ? mat4.invert(new Float32Array(16), labelPlaneMatrix) : identityMat4;\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 const elevation = tr.elevation;\n const getElevation = elevation ? (p => elevation.getAtTileOffset(coord, p.x, p.y)) : null;\n symbolProjection.updateLineLabels(bucket, coord.posMatrix, painter, isText, labelPlaneMatrix, glCoordMatrix, pitchWithMap, keepUpright, getElevation);\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 tile,\n labelPlaneMatrixInv\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 if (painter.terrain) painter.terrain.setupElevationDraw(state.tile, state.program, {useDepthForOcclusion: true, labelPlaneMatrixInv: state.labelPlaneMatrixInv});\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<SymbolSDFUniformsType>);\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<OverscaledTileID>) {\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 painter.prepareDrawTile(coord);\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 = (painter.terrain && painter.terrain.renderingToTexture) ? painter.terrain.drapeBufferSize : [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 EXTENT from '../data/extent';\nimport {\n fillExtrusionUniformValues,\n fillExtrusionPatternUniformValues,\n} from './program/fill_extrusion_program';\nimport Point from '@mapbox/point-geometry';\nimport {OverscaledTileID} from '../source/tile_id';\nimport assert from 'assert';\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';\n\nexport default draw;\n\nfunction draw(painter: Painter, source: SourceCache, layer: FillExtrusionStyleLayer, coords: Array<OverscaledTileID>) {\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 (painter.terrain) {\n const terrain = painter.terrain;\n if (!bucket.enableTerrain) continue;\n terrain.setupElevationDraw(tile, program, {useMeterToDem: true});\n flatRoofsUpdate(context, source, coord, bucket, layer, terrain);\n if (!bucket.centroidVertexBuffer) {\n const attrIndex: number | void = program.attributes['a_centroid_pos'];\n if (attrIndex !== undefined) gl.vertexAttrib2f(attrIndex, 0, 0);\n }\n }\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, painter.terrain ? bucket.centroidVertexBuffer : null);\n }\n}\n\n// Flat roofs array is prepared in the bucket, except for buildings that are on tile borders.\n// For them, join pieces, calculate joined size here, and then upload data.\nfunction flatRoofsUpdate(context, source, coord, bucket, layer, terrain) {\n // For all four borders: 0 - left, 1, right, 2 - top, 3 - bottom\n const neighborCoord = [\n coord => {\n let x = coord.canonical.x - 1;\n let w = coord.wrap;\n if (x < 0) {\n x = (1 << coord.canonical.z) - 1;\n w--;\n }\n return new OverscaledTileID(coord.overscaledZ, w, coord.canonical.z, x, coord.canonical.y);\n },\n coord => {\n let x = coord.canonical.x + 1;\n let w = coord.wrap;\n if (x === 1 << coord.canonical.z) {\n x = 0;\n w++;\n }\n return new OverscaledTileID(coord.overscaledZ, w, coord.canonical.z, x, coord.canonical.y);\n },\n coord => new OverscaledTileID(coord.overscaledZ, coord.wrap, coord.canonical.z, coord.canonical.x,\n (coord.canonical.y === 0 ? 1 << coord.canonical.z : coord.canonical.y) - 1),\n coord => new OverscaledTileID(coord.overscaledZ, coord.wrap, coord.canonical.z, coord.canonical.x,\n coord.canonical.y === (1 << coord.canonical.z) - 1 ? 0 : coord.canonical.y + 1)\n ];\n\n const getLoadedBucket = (nid) => {\n const maxzoom = source.getSource().maxzoom;\n // In overscale range, look one tile zoom above and under. We do this to\n // avoid flickering and use the content in Z-1 and Z+1 buckets until Z bucket is loaded.\n for (const j of [0, -1, 1]) {\n if (nid.overscaledZ + j < maxzoom) continue;\n if (j > 0 && nid.overscaledZ < maxzoom) continue;\n const n = source.getTileByID(nid.calculateScaledKey(nid.overscaledZ + j));\n if (n && n.hasData()) {\n const nBucket: ?FillExtrusionBucket = (n.getBucket(layer): any);\n if (nBucket) return nBucket;\n }\n }\n };\n\n const projectedToBorder = [0, 0, 0]; // [min, max, maxOffsetFromBorder]\n const xjoin = (a, b) => {\n projectedToBorder[0] = Math.min(a.min.y, b.min.y);\n projectedToBorder[1] = Math.max(a.max.y, b.max.y);\n projectedToBorder[2] = EXTENT - b.min.x > a.max.x ? b.min.x - EXTENT : a.max.x;\n return projectedToBorder;\n };\n const yjoin = (a, b) => {\n projectedToBorder[0] = Math.min(a.min.x, b.min.x);\n projectedToBorder[1] = Math.max(a.max.x, b.max.x);\n projectedToBorder[2] = EXTENT - b.min.y > a.max.y ? b.min.y - EXTENT : a.max.y;\n return projectedToBorder;\n };\n const projectCombinedSpanToBorder = [\n (a, b) => xjoin(a, b),\n (a, b) => xjoin(b, a),\n (a, b) => yjoin(a, b),\n (a, b) => yjoin(b, a)\n ];\n\n const centroid = new Point(0, 0);\n const error = 3; // Allow intrusion of a building to the building with adjacent wall.\n\n let demTile, neighborDEMTile, neighborTileID;\n\n const flatBase = (min, max, edge, verticalEdge, maxOffsetFromBorder) => {\n const points = [[verticalEdge ? edge : min, verticalEdge ? min : edge, 0], [verticalEdge ? edge : max, verticalEdge ? max : edge, 0]];\n\n const coord3 = maxOffsetFromBorder < 0 ? EXTENT + maxOffsetFromBorder : maxOffsetFromBorder;\n const thirdPoint = [verticalEdge ? coord3 : (min + max) / 2, verticalEdge ? (min + max) / 2 : coord3, 0];\n if ((edge === 0 && maxOffsetFromBorder < 0) || (edge !== 0 && maxOffsetFromBorder > 0)) {\n // Third point is inside neighbor tile, not in the |coord| tile.\n terrain.getForTilePoints(neighborTileID, [thirdPoint], true, neighborDEMTile);\n } else {\n points.push(thirdPoint);\n }\n terrain.getForTilePoints(coord, points, true, demTile);\n return Math.max(points[0][2], points[1][2], thirdPoint[2]) / terrain.exaggeration();\n };\n\n // Process all four borders: get neighboring tile\n for (let i = 0; i < 4; i++) {\n // Sort by border intersection area minimums, ascending.\n const a = bucket.borders[i];\n if (a.length === 0) { bucket.borderDone[i] = true; }\n if (bucket.borderDone[i]) continue;\n const nid = neighborTileID = neighborCoord[i](coord);\n const nBucket: ?FillExtrusionBucket = getLoadedBucket(nid);\n if (!nBucket || !nBucket.enableTerrain) continue;\n\n neighborDEMTile = terrain.findDEMTileFor(nid);\n if (!neighborDEMTile || !neighborDEMTile.dem) continue;\n if (!demTile) {\n const dem = terrain.findDEMTileFor(coord);\n if (!(dem && dem.dem)) return; // defer update until an elevation tile is available.\n demTile = dem;\n }\n const j = (i < 2 ? 1 : 5) - i;\n const b = nBucket.borders[j];\n let ib = 0;\n for (let ia = 0; ia < a.length; ia++) {\n const parta = bucket.featuresOnBorder[a[ia]];\n const partABorderRange = parta.borders[i];\n // Find all nBucket parts that share the border overlap.\n let partb;\n while (ib < b.length) {\n // Pass all that are before the overlap.\n partb = nBucket.featuresOnBorder[b[ib]];\n const partBBorderRange = partb.borders[j];\n if (partBBorderRange[1] > partABorderRange[0] + error) break;\n if (!nBucket.borderDone[j]) nBucket.encodeCentroid(undefined, partb, false);\n ib++;\n }\n if (partb && ib < b.length) {\n const saveIb = ib;\n let count = 0;\n while (true) {\n // Collect all parts overlapping parta on the edge, to make sure it is only one.\n const partBBorderRange = partb.borders[j];\n if (partBBorderRange[0] > partABorderRange[1] - error) break;\n count++;\n if (++ib === b.length) break;\n partb = nBucket.featuresOnBorder[b[ib]];\n }\n partb = nBucket.featuresOnBorder[b[saveIb]];\n\n // If any of a or b crosses more than one tile edge, don't support flat roof.\n if (parta.intersectsCount() > 1 || partb.intersectsCount() > 1 || count !== 1) {\n if (count !== 1) {\n ib = saveIb; // rewind unprocessed ib so that it is processed again for the next ia.\n }\n\n bucket.encodeCentroid(undefined, parta, false);\n if (!nBucket.borderDone[j]) nBucket.encodeCentroid(undefined, partb, false);\n continue;\n }\n\n // Now we have 1-1 matching of parts in both tiles that share the edge. Calculate flat base elevation\n // as average of three points: 2 are edge points (combined span projected to border) and one is point of\n // span that has maximum offset to border.\n const span = projectCombinedSpanToBorder[i](parta, partb);\n const edge = (i % 2) ? EXTENT - 1 : 0;\n centroid.x = flatBase(span[0], Math.min(EXTENT - 1, span[1]), edge, i < 2, span[2]);\n centroid.y = 0;\n assert(parta.vertexArrayOffset !== undefined && parta.vertexArrayOffset < bucket.layoutVertexArray.length);\n bucket.encodeCentroid(centroid, parta, false);\n\n assert(partb.vertexArrayOffset !== undefined && partb.vertexArrayOffset < nBucket.layoutVertexArray.length);\n if (!nBucket.borderDone[j]) nBucket.encodeCentroid(centroid, partb, false);\n } else {\n assert(parta.intersectsCount() > 1 || (partb && partb.intersectsCount() > 1)); // expected at the end of border, when buildings cover corner (show building w/o flat roof).\n bucket.encodeCentroid(undefined, parta, false);\n }\n }\n\n bucket.borderDone[i] = bucket.needsCentroidUpdate = true;\n if (!nBucket.borderDone[j]) {\n nBucket.borderDone[j] = nBucket.needsCentroidUpdate = true;\n }\n }\n\n if (bucket.needsCentroidUpdate || (!bucket.centroidVertexBuffer && bucket.centroidVertexArray.length !== 0)) {\n bucket.uploadCentroid(context);\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\nexport function drawDebugQueryGeometry(painter: Painter, sourceCache: SourceCache, coords: Array<OverscaledTileID>) {\n for (let i = 0; i < coords.length; i++) {\n drawTileQueryGeometry(painter, sourceCache, coords[i]);\n }\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<OverscaledTileID>) {\n for (let i = 0; i < coords.length; i++) {\n drawDebugTile(painter, sourceCache, coords[i]);\n }\n}\n\nfunction drawTileQueryGeometry(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 const tile = sourceCache.getTileByID(coord.key);\n if (painter.terrain) painter.terrain.setupElevationDraw(tile, program);\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 if (tile.queryGeometryDebugViz && tile.queryGeometryDebugViz.vertices.length > 0) {\n tile.queryGeometryDebugViz.lazyUpload(context);\n const vertexBuffer = tile.queryGeometryDebugViz.vertexBuffer;\n const indexBuffer = tile.queryGeometryDebugViz.indexBuffer;\n const segments = tile.queryGeometryDebugViz.segments;\n if (vertexBuffer != null && indexBuffer != null && segments != null) {\n program.draw(context, gl.LINE_STRIP, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n debugUniformValues(posMatrix, tile.queryGeometryDebugViz.color), id,\n vertexBuffer, indexBuffer, segments);\n }\n }\n\n if (tile.queryBoundsDebugViz && tile.queryBoundsDebugViz.vertices.length > 0) {\n tile.queryBoundsDebugViz.lazyUpload(context);\n const vertexBuffer = tile.queryBoundsDebugViz.vertexBuffer;\n const indexBuffer = tile.queryBoundsDebugViz.indexBuffer;\n const segments = tile.queryBoundsDebugViz.segments;\n if (vertexBuffer != null && indexBuffer != null && segments != null) {\n program.draw(context, gl.LINE_STRIP, depthMode, stencilMode, colorMode, CullFaceMode.disabled,\n debugUniformValues(posMatrix, tile.queryBoundsDebugViz.color), id,\n vertexBuffer, indexBuffer, segments);\n }\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 const tile = sourceCache.getTileByID(coord.key);\n if (painter.terrain) painter.terrain.setupElevationDraw(tile, program);\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 = tile.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\nimport {createLayout} from '../util/struct_array';\n\nexport const skyboxAttributes = createLayout([\n {name: 'a_pos_3f', components: 3, type: 'Float32'}\n]);\n\nexport default skyboxAttributes;\nexport const {members, size, alignment} = skyboxAttributes;\n","// @flow\n\nimport {members as skyboxAttributes} from './skybox_attributes';\nimport {SkyboxVertexArray, TriangleIndexArray} from '../data/array_types';\nimport SegmentVector from '../data/segment';\nimport type IndexBuffer from '../gl/index_buffer';\nimport type VertexBuffer from '../gl/vertex_buffer';\nimport type Context from '../gl/context';\n\nfunction addVertex(vertexArray, x, y, z) {\n vertexArray.emplaceBack(\n // a_pos\n x,\n y,\n z\n );\n}\n\nclass SkyboxGeometry {\n vertexArray: SkyboxVertexArray;\n vertexBuffer: VertexBuffer;\n indices: TriangleIndexArray;\n indexBuffer: IndexBuffer;\n segment: SegmentVector;\n\n constructor(context: Context) {\n this.vertexArray = new SkyboxVertexArray();\n this.indices = new TriangleIndexArray();\n\n addVertex(this.vertexArray, -1.0, -1.0, 1.0);\n addVertex(this.vertexArray, 1.0, -1.0, 1.0);\n addVertex(this.vertexArray, -1.0, 1.0, 1.0);\n addVertex(this.vertexArray, 1.0, 1.0, 1.0);\n addVertex(this.vertexArray, -1.0, -1.0, -1.0);\n addVertex(this.vertexArray, 1.0, -1.0, -1.0);\n addVertex(this.vertexArray, -1.0, 1.0, -1.0);\n addVertex(this.vertexArray, 1.0, 1.0, -1.0);\n\n // +x\n this.indices.emplaceBack(5, 1, 3);\n this.indices.emplaceBack(3, 7, 5);\n // -x\n this.indices.emplaceBack(6, 2, 0);\n this.indices.emplaceBack(0, 4, 6);\n // +y\n this.indices.emplaceBack(2, 6, 7);\n this.indices.emplaceBack(7, 3, 2);\n // -y\n this.indices.emplaceBack(5, 4, 0);\n this.indices.emplaceBack(0, 1, 5);\n // +z\n this.indices.emplaceBack(0, 2, 3);\n this.indices.emplaceBack(3, 1, 0);\n // -z\n this.indices.emplaceBack(7, 6, 4);\n this.indices.emplaceBack(4, 5, 7);\n\n this.vertexBuffer = context.createVertexBuffer(this.vertexArray, skyboxAttributes);\n this.indexBuffer = context.createIndexBuffer(this.indices);\n\n this.segment = SegmentVector.simpleSegment(0, 0, 36, 12);\n }\n}\n\nexport default SkyboxGeometry;\n","// @flow\n\nimport StencilMode from '../gl/stencil_mode';\nimport DepthMode from '../gl/depth_mode';\nimport ColorMode from '../gl/color_mode';\nimport CullFaceMode from '../gl/cull_face_mode';\nimport Context from '../gl/context';\nimport Texture from './texture';\nimport Program from './program';\nimport type SourceCache from '../source/source_cache';\nimport SkyboxGeometry from './skybox_geometry';\nimport {skyboxUniformValues, skyboxGradientUniformValues} from './program/skybox_program';\nimport {skyboxCaptureUniformValues} from './program/skybox_capture_program';\nimport SkyLayer from '../style/style_layer/sky_style_layer';\nimport type Painter from './painter';\nimport {vec3, mat3, mat4} from 'gl-matrix';\nimport assert from 'assert';\n\nexport default drawSky;\n\nfunction drawSky(painter: Painter, sourceCache: SourceCache, layer: SkyLayer) {\n const opacity = layer.paint.get('sky-opacity');\n if (opacity === 0) {\n return;\n }\n\n const context = painter.context;\n const type = layer.paint.get('sky-type');\n const depthMode = new DepthMode(context.gl.LEQUAL, DepthMode.ReadOnly, [0, 1]);\n const temporalOffset = (painter.frameCounter / 1000.0) % 1;\n\n if (type === 'atmosphere') {\n if (painter.renderPass === 'offscreen') {\n if (layer.needsSkyboxCapture(painter)) {\n captureSkybox(painter, layer, 32, 32);\n layer.markSkyboxValid(painter);\n }\n } else if (painter.renderPass === 'sky') {\n drawSkyboxFromCapture(painter, layer, depthMode, opacity, temporalOffset);\n }\n } else if (type === 'gradient') {\n if (painter.renderPass === 'sky') {\n drawSkyboxGradient(painter, layer, depthMode, opacity, temporalOffset);\n }\n } else {\n assert(false, `${type} is unsupported sky-type`);\n }\n}\n\nfunction drawSkyboxGradient(painter: Painter, layer: SkyLayer, depthMode: DepthMode, opacity: number, temporalOffset: number) {\n const context = painter.context;\n const gl = context.gl;\n const transform = painter.transform;\n const program = painter.useProgram('skyboxGradient');\n\n // Lazily initialize geometry and texture if they havent been created yet.\n if (!layer.skyboxGeometry) {\n layer.skyboxGeometry = new SkyboxGeometry(context);\n }\n context.activeTexture.set(gl.TEXTURE0);\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 const uniformValues = skyboxGradientUniformValues(\n transform.skyboxMatrix,\n layer.getCenter(painter, false),\n layer.paint.get('sky-gradient-radius'),\n opacity,\n temporalOffset\n );\n\n program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled,\n painter.colorModeForRenderPass(), CullFaceMode.backCW,\n uniformValues, 'skyboxGradient', layer.skyboxGeometry.vertexBuffer,\n layer.skyboxGeometry.indexBuffer, layer.skyboxGeometry.segment);\n}\n\nfunction drawSkyboxFromCapture(painter: Painter, layer: SkyLayer, depthMode: DepthMode, opacity: number, temporalOffset: number) {\n const context = painter.context;\n const gl = context.gl;\n const transform = painter.transform;\n const program = painter.useProgram('skybox');\n\n context.activeTexture.set(gl.TEXTURE0);\n\n gl.bindTexture(gl.TEXTURE_CUBE_MAP, layer.skyboxTexture);\n\n const uniformValues = skyboxUniformValues(transform.skyboxMatrix, layer.getCenter(painter, false), 0, opacity, temporalOffset);\n\n program.draw(context, gl.TRIANGLES, depthMode, StencilMode.disabled,\n painter.colorModeForRenderPass(), CullFaceMode.backCW,\n uniformValues, 'skybox', layer.skyboxGeometry.vertexBuffer,\n layer.skyboxGeometry.indexBuffer, layer.skyboxGeometry.segment);\n}\n\nfunction drawSkyboxFace(context: Context, layer: SkyLayer, program: Program<*>, faceRotate: mat4, sunDirection: vec3, i: number) {\n const gl = context.gl;\n\n const atmosphereColor = layer.paint.get('sky-atmosphere-color');\n const atmosphereHaloColor = layer.paint.get('sky-atmosphere-halo-color');\n const sunIntensity = layer.paint.get('sky-atmosphere-sun-intensity');\n\n const uniformValues = skyboxCaptureUniformValues(\n mat3.fromMat4([], faceRotate),\n sunDirection,\n sunIntensity,\n atmosphereColor,\n atmosphereHaloColor);\n\n const glFace = gl.TEXTURE_CUBE_MAP_POSITIVE_X + i;\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, glFace, layer.skyboxTexture, 0);\n\n program.draw(context, gl.TRIANGLES, DepthMode.disabled, StencilMode.disabled, ColorMode.unblended, CullFaceMode.frontCW,\n uniformValues, 'skyboxCapture', layer.skyboxGeometry.vertexBuffer,\n layer.skyboxGeometry.indexBuffer, layer.skyboxGeometry.segment);\n}\n\nfunction captureSkybox(painter: Painter, layer: SkyLayer, width: number, height: number) {\n const context = painter.context;\n const gl = context.gl;\n let fbo = layer.skyboxFbo;\n\n // Using absence of fbo as a signal for lazy initialization of all resources, cache resources in layer object\n if (!fbo) {\n fbo = layer.skyboxFbo = context.createFramebuffer(width, height, false);\n layer.skyboxGeometry = new SkyboxGeometry(context);\n layer.skyboxTexture = context.gl.createTexture();\n\n gl.bindTexture(gl.TEXTURE_CUBE_MAP, layer.skyboxTexture);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);\n gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);\n\n for (let i = 0; i < 6; ++i) {\n const glFace = gl.TEXTURE_CUBE_MAP_POSITIVE_X + i;\n\n // The format here could be RGB, but render tests are not happy with rendering to such a format\n gl.texImage2D(glFace, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);\n }\n }\n\n context.bindFramebuffer.set(fbo.framebuffer);\n context.viewport.set([0, 0, width, height]);\n\n const sunDirection = layer.getCenter(painter, true);\n const program = painter.useProgram('skyboxCapture');\n const faceRotate = new Float64Array(16);\n\n // +x;\n mat4.identity(faceRotate);\n mat4.rotateY(faceRotate, faceRotate, -Math.PI * 0.5);\n drawSkyboxFace(context, layer, program, faceRotate, sunDirection, 0);\n // -x\n mat4.identity(faceRotate);\n mat4.rotateY(faceRotate, faceRotate, Math.PI * 0.5);\n drawSkyboxFace(context, layer, program, faceRotate, sunDirection, 1);\n // +y\n mat4.identity(faceRotate);\n mat4.rotateX(faceRotate, faceRotate, -Math.PI * 0.5);\n drawSkyboxFace(context, layer, program, faceRotate, sunDirection, 2);\n // -y\n mat4.identity(faceRotate);\n mat4.rotateX(faceRotate, faceRotate, Math.PI * 0.5);\n drawSkyboxFace(context, layer, program, faceRotate, sunDirection, 3);\n // +z\n mat4.identity(faceRotate);\n drawSkyboxFace(context, layer, program, faceRotate, sunDirection, 4);\n // -z\n mat4.identity(faceRotate);\n mat4.rotateY(faceRotate, faceRotate, Math.PI);\n drawSkyboxFace(context, layer, program, faceRotate, sunDirection, 5);\n\n context.viewport.set([0, 0, painter.width, painter.height]);\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, MAX_SAFE_INTEGER} 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 assert from 'assert';\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, drawDebugQueryGeometry} from './draw_debug';\nimport custom from './draw_custom';\nimport sky from './draw_sky';\nimport {Terrain} from '../terrain/terrain';\nimport {Debug} from '../util/debug';\n\nconst draw = {\n symbol,\n circle,\n heatmap,\n line,\n fill,\n 'fill-extrusion': fillExtrusion,\n hillshade,\n raster,\n background,\n sky,\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';\nimport type {DynamicDefinesType} from './program/program_uniforms';\n\nexport type RenderPass = 'offscreen' | 'opaque' | 'translucent' | 'sky';\nexport type CanvasCopyInstances = {\n canvasCopies: WebGLTexture[],\n timeStamps: number[]\n}\n\ntype PainterOptions = {\n showOverdrawInspector: boolean,\n showTileBoundaries: boolean,\n showQueryGeometry: boolean,\n showPadding: boolean,\n rotating: boolean,\n zooming: boolean,\n moving: boolean,\n gpuTiming: boolean,\n fadeDuration: number,\n isInitialLoad: boolean,\n speedIndexTiming: boolean\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<Texture> };\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: {[_: number]: 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 frameCounter: 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 _terrain: ?Terrain;\n tileLoaded: boolean;\n frameCopies: Array<WebGLTexture>;\n loadTimeStamps: Array<number>;\n\n constructor(gl: WebGLRenderingContext, transform: Transform) {\n this.context = new Context(gl);\n this.transform = transform;\n this._tileTextures = {};\n this.frameCopies = [];\n this.loadTimeStamps = [];\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 this.frameCounter = 0;\n }\n\n updateTerrain(style: Style, cameraChanging: boolean) {\n const enabled = !!style && !!style.terrain;\n if (!enabled && (!this._terrain || !this._terrain.enabled)) return;\n if (!this._terrain) {\n this._terrain = new Terrain(this, style);\n }\n const terrain: Terrain = this._terrain;\n this.transform.elevation = enabled ? terrain : null;\n terrain.update(style, this.transform, cameraChanging);\n }\n\n get terrain(): ?Terrain {\n return this._terrain && this._terrain.enabled ? this._terrain : null;\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 this.loadTimeStamps.push(window.performance.now());\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, sourceCache?: SourceCache, tileIDs?: Array<OverscaledTileID>) {\n if (!sourceCache || this.currentStencilSource === sourceCache.id || !layer.isTileClipped() || !tileIDs || !tileIDs.length) return;\n\n this.currentStencilSource = sourceCache.id;\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): $ReadOnly<StencilMode> {\n if (this.terrain) return this.terrain.stencilModeForRTTOverlap(tileID);\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<OverscaledTileID>): [{[_: number]: $ReadOnly<StencilMode>}, Array<OverscaledTileID>] {\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<ColorMode> {\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<DepthMode> {\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<OverscaledTileID>} = {};\n const coordsDescending: {[_: string]: Array<OverscaledTileID>} = {};\n const coordsDescendingSymbol: {[_: string]: Array<OverscaledTileID>} = {};\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 if (this.terrain) {\n this.terrain.updateTileBinding(coordsDescendingSymbol);\n // All render to texture is done in translucent pass to remove need\n // for depth buffer allocation per tile.\n this.opaquePassCutoff = 0;\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 const sourceCache = style._getLayerSourceCache(layer);\n if (!layer.hasOffscreenPass() || layer.isHidden(this.transform.zoom)) continue;\n\n const coords = sourceCache ? coordsDescending[sourceCache.id] : undefined;\n if (!(layer.type === 'custom' || layer.isSky()) && !(coords && coords.length)) continue;\n\n this.renderLayer(this, sourceCache, layer, coords);\n }\n\n this.depthRangeFor3D = [0, 1 - ((style.order.length + 2) * this.numSublayers * this.depthEpsilon)];\n\n // Terrain depth offscreen render pass ==========================\n // With terrain on, renders the depth buffer into a texture.\n // This texture is used for occlusion testing (labels)\n if (this.terrain && (this.style.hasSymbolLayers() || this.style.hasCircleLayers())) {\n this.terrain.drawDepth();\n }\n\n // Rebind the main framebuffer now that all offscreen layers have been rendered:\n this.context.bindFramebuffer.set(null);\n this.context.viewport.set([0, 0, this.width, this.height]);\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\n // Opaque pass ===============================================\n // Draw opaque layers top-to-bottom first.\n this.renderPass = 'opaque';\n\n if (!this.terrain) {\n for (this.currentLayer = layerIds.length - 1; this.currentLayer >= 0; this.currentLayer--) {\n const layer = this.style._layers[layerIds[this.currentLayer]];\n const sourceCache = style._getLayerSourceCache(layer);\n if (layer.isSky()) continue;\n const coords = sourceCache ? coordsDescending[sourceCache.id] : undefined;\n\n this._renderTileClippingMasks(layer, sourceCache, coords);\n this.renderLayer(this, sourceCache, layer, coords);\n }\n }\n\n // Sky pass ======================================================\n // Draw all sky layers bottom to top.\n // They are drawn at max depth, they are drawn after opaque and before\n // translucent to fail depth testing and mix with translucent objects.\n this.renderPass = 'sky';\n if (this.transform.isHorizonVisible()) {\n for (this.currentLayer = 0; this.currentLayer < layerIds.length; this.currentLayer++) {\n const layer = this.style._layers[layerIds[this.currentLayer]];\n const sourceCache = style._getLayerSourceCache(layer);\n if (!layer.isSky()) continue;\n const coords = sourceCache ? coordsDescending[sourceCache.id] : undefined;\n\n this.renderLayer(this, sourceCache, layer, coords);\n }\n }\n\n // Translucent pass ===============================================\n // Draw all other layers bottom-to-top.\n this.renderPass = 'translucent';\n\n this.currentLayer = 0;\n while (this.currentLayer < layerIds.length) {\n const layer = this.style._layers[layerIds[this.currentLayer]];\n const sourceCache = style._getLayerSourceCache(layer);\n\n // Nothing to draw in translucent pass for sky layers, advance\n if (layer.isSky()) {\n ++this.currentLayer;\n continue;\n }\n\n // With terrain on and for draped layers only, issue rendering and progress\n // this.currentLayer until the next non-draped layer.\n // Otherwise we interleave terrain draped render with non-draped layers on top\n if (this.terrain && this.style.isLayerDraped(layer)) {\n if (layer.isHidden(this.transform.zoom)) {\n ++this.currentLayer;\n continue;\n }\n const terrain = (((this.terrain): any): Terrain);\n const prevLayer = this.currentLayer;\n this.currentLayer = terrain.renderBatch(this.currentLayer);\n assert(this.currentLayer > prevLayer);\n continue;\n }\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 = sourceCache ?\n (layer.type === 'symbol' ? coordsDescendingSymbol : coordsDescending)[sourceCache.id] :\n undefined;\n\n this._renderTileClippingMasks(layer, sourceCache, sourceCache ? coordsAscending[sourceCache.id] : undefined);\n this.renderLayer(this, sourceCache, layer, coords);\n\n ++this.currentLayer;\n }\n\n if (this.terrain) {\n this.terrain.postRender();\n }\n\n if (this.options.showTileBoundaries || this.options.showQueryGeometry) {\n //Use source with highest maxzoom\n let selectedSource = null;\n const layers = values(this.style._layers);\n layers.forEach((layer) => {\n const sourceCache = style._getLayerSourceCache(layer);\n if (sourceCache && !layer.isHidden(this.transform.zoom)) {\n if (!selectedSource || (selectedSource.getSource().maxzoom < sourceCache.getSource().maxzoom)) {\n selectedSource = sourceCache;\n }\n }\n });\n if (selectedSource) {\n if (this.options.showTileBoundaries) {\n draw.debug(this, selectedSource, selectedSource.getVisibleCoordinates());\n }\n\n Debug.run(() => {\n if (this.options.showQueryGeometry && selectedSource) {\n drawDebugQueryGeometry(this, selectedSource, selectedSource.getVisibleCoordinates());\n }\n });\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 this.frameCounter = (this.frameCounter + 1) % MAX_SAFE_INTEGER;\n\n if (this.tileLoaded && this.options.speedIndexTiming) {\n this.loadTimeStamps.push(window.performance.now());\n this.saveCanvasCopy();\n }\n }\n\n renderLayer(painter: Painter, sourceCache?: SourceCache, layer: StyleLayer, coords?: Array<OverscaledTileID>) {\n if (layer.isHidden(this.transform.zoom)) return;\n if (layer.type !== 'background' && layer.type !== 'sky' && layer.type !== 'custom' && !(coords && 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, this.options.isInitialLoad);\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<ResolvedImage>): 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 /**\n * Returns #defines that would need to be injected into every Program\n * based on the current state of Painter.\n *\n * @returns {string[]}\n * @private\n */\n currentGlobalDefines(): string[] {\n const terrain = this.terrain && !this.terrain.renderingToTexture; // Enables elevation sampling in vertex shader.\n const rtt = this.terrain && this.terrain.renderingToTexture;\n\n const defines = [];\n if (terrain) defines.push('TERRAIN');\n if (rtt) defines.push('RENDER_TO_TEXTURE');\n if (this._showOverdrawInspector) defines.push('OVERDRAW_INSPECTOR');\n return defines;\n }\n\n useProgram(name: string, programConfiguration: ?ProgramConfiguration, fixedDefines: ?DynamicDefinesType[]): Program<any> {\n this.cache = this.cache || {};\n const defines = (((fixedDefines || []): any): string[]);\n\n const globalDefines = this.currentGlobalDefines();\n const allDefines = globalDefines.concat(defines);\n const key = Program.cacheKey(name, allDefines, programConfiguration);\n\n if (!this.cache[key]) {\n this.cache[key] = new Program(this.context, name, shaders[name], programConfiguration, programUniforms[name], allDefines);\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 if (this._terrain) {\n this._terrain.destroy();\n }\n this.emptyTexture.destroy();\n if (this.debugOverlayTexture) {\n this.debugOverlayTexture.destroy();\n }\n }\n\n prepareDrawTile(tileID: OverscaledTileID) {\n if (this.terrain) {\n this.terrain.prepareDrawTile(tileID);\n }\n }\n\n setTileLoadedFlag(flag: boolean) {\n this.tileLoaded = flag;\n }\n\n saveCanvasCopy() {\n this.frameCopies.push(this.canvasCopy());\n this.tileLoaded = false;\n }\n\n canvasCopy() {\n const gl = this.context.gl;\n const texture = gl.createTexture();\n gl.bindTexture(gl.TEXTURE_2D, texture);\n gl.copyTexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, 0);\n return texture;\n }\n\n getCanvasCopiesAndTimestamps(): CanvasCopyInstances {\n return {\n canvasCopies: this.frameCopies,\n timeStamps: this.loadTimeStamps\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, circleDefinesValues} 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';\nimport type Tile from '../source/tile';\nimport type {DynamicDefinesType} from './program/program_uniforms';\n\nexport default drawCircles;\n\ntype TileRenderState = {\n programConfiguration: ProgramConfiguration,\n program: Program<*>,\n layoutVertexBuffer: VertexBuffer,\n indexBuffer: IndexBuffer,\n uniformValues: UniformValues<CircleUniformsType>,\n tile: Tile\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<OverscaledTileID>) {\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<SegmentsTileRenderState> = [];\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 definesValues = circleDefinesValues(layer);\n const program = painter.useProgram('circle', programConfiguration, ((definesValues: any): DynamicDefinesType[]));\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 tile\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, tile} = segmentsState.state;\n const segments = segmentsState.segments;\n if (painter.terrain) painter.terrain.setupElevationDraw(tile, program, {useDepthForOcclusion: true});\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<OverscaledTileID>) {\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 if (painter.terrain) painter.terrain.setupElevationDraw(tile, program);\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<OverscaledTileID>) {\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 if (image && !tile.patternsLoaded()) continue;\n\n const bucket: ?LineBucket = (tile.getBucket(layer): any);\n if (!bucket) continue;\n painter.prepareDrawTile(coord);\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 matrix = painter.terrain ? coord.posMatrix : null;\n const uniformValues = image ? linePatternUniformValues(painter, tile, layer, crossfade, matrix) :\n dasharray ? lineSDFUniformValues(painter, tile, layer, dasharray, crossfade, matrix) :\n gradient ? lineGradientUniformValues(painter, tile, layer, matrix, bucket.lineClipsArray.length) :\n lineUniformValues(painter, tile, layer, matrix);\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 ImageSource from '../source/image_source';\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';\nimport rasterFade from './raster_fade';\n\nexport default drawRaster;\n\nfunction drawRaster(painter: Painter, sourceCache: SourceCache, layer: RasterStyleLayer, tileIDs: Array<OverscaledTileID>, variableOffsets: any, isInitialLoad: boolean) {\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 // When rendering to texture, coordinates are already sorted: primary by\n // proxy id and secondary sort is by Z.\n const renderingToTexture = painter.terrain && painter.terrain.renderingToTexture;\n\n const [stencilModes, coords] = source instanceof ImageSource || renderingToTexture ? [{}, 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 = renderingToTexture ? DepthMode.disabled : 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 if (renderingToTexture && !(tile && tile.hasData())) continue;\n\n const posMatrix = (renderingToTexture) ? coord.posMatrix :\n painter.transform.calculatePosMatrix(coord.toUnwrapped(), align);\n\n const stencilMode = painter.terrain && renderingToTexture ?\n painter.terrain.stencilModeForRTTOverlap(coord) :\n stencilModes[coord.overscaledZ];\n\n const rasterFadeDuration = isInitialLoad ? 0 : layer.paint.get('raster-fade-duration');\n tile.registerFadeDuration(rasterFadeDuration);\n\n const parentTile = sourceCache.findLoadedParent(coord, 0);\n const fade = rasterFade(tile, parentTile, sourceCache, painter.transform, rasterFadeDuration);\n if (painter.terrain) painter.terrain.prepareDrawTile(coord);\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, stencilMode, colorMode, CullFaceMode.disabled,\n uniformValues, layer.id, painter.rasterBoundsBuffer,\n painter.quadTriangleIndexBuffer, painter.rasterBoundsSegments);\n }\n }\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';\nimport {OverscaledTileID} from '../source/tile_id';\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, coords: Array<OverscaledTileID>) {\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 = coords ? coords : 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 = coords ? tileID.posMatrix : painter.transform.calculatePosMatrix(tileID.toUnwrapped());\n painter.prepareDrawTile(tileID);\n\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\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 apparent 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 | EdgeInsets} start The initial padding options.\n * @param {PaddingOptions} target The target padding options.\n * @param {number} t The interpolation variable.\n * @returns {EdgeInsets} The interpolated edge insets.\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 The width of the map in pixels.\n * @param {number} height The height of the map in pixels.\n * @returns {Point} The apparent center or vanishing point of the map.\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 state as json, useful when you want to have a\n * read-only representation of the inset.\n *\n * @returns {PaddingOptions} The current padding options.\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 MercatorCoordinate from '../geo/mercator_coordinate';\nimport {degToRad, wrap} from '../util/util';\nimport {vec3, vec4, quat, mat4} from 'gl-matrix';\nimport type {Elevation} from '../terrain/elevation';\n\nimport type {LngLatLike} from '../geo/lng_lat';\n\nfunction getColumn(matrix: mat4, col: number): vec4 {\n return [matrix[col * 4], matrix[col * 4 + 1], matrix[col * 4 + 2], matrix[col * 4 + 3]];\n}\n\nfunction setColumn(matrix: mat4, col: number, values: vec4) {\n matrix[col * 4 + 0] = values[0];\n matrix[col * 4 + 1] = values[1];\n matrix[col * 4 + 2] = values[2];\n matrix[col * 4 + 3] = values[3];\n}\n\nfunction updateTransformOrientation(matrix: mat4, orientation: quat) {\n // Take temporary copy of position to prevent it from being overwritten\n const position: vec4 = getColumn(matrix, 3);\n\n // Convert quaternion to rotation matrix\n mat4.fromQuat(matrix, orientation);\n setColumn(matrix, 3, position);\n}\n\nfunction updateTransformPosition(matrix: mat4, position: vec3) {\n setColumn(matrix, 3, [position[0], position[1], position[2], 1.0]);\n}\n\nfunction wrapCameraPosition(position: vec3 | MercatorCoordinate) {\n if (!position) return;\n const mercatorCoordinate = Array.isArray(position) ? new MercatorCoordinate(position[0], position[1], position[2]) : position;\n mercatorCoordinate.x = wrap(mercatorCoordinate.x, 0, 1);\n return mercatorCoordinate;\n}\n\nfunction orientationFromPitchBearing(pitch: number, bearing: number): quat {\n // Both angles are considered to define CW rotation around their respective axes.\n // Values have to be negated to achieve the proper quaternion in left handed coordinate space\n const orientation = quat.identity([]);\n quat.rotateZ(orientation, orientation, -bearing);\n quat.rotateX(orientation, orientation, -pitch);\n return orientation;\n}\n\nexport function orientationFromFrame(forward: vec3, up: vec3): ?quat {\n // Find right-vector of the resulting coordinate frame. Up-vector has to be\n // sanitized first in order to remove the roll component from the orientation\n const xyForward = [forward[0], forward[1], 0];\n const xyUp = [up[0], up[1], 0];\n\n const epsilon = 1e-15;\n\n if (vec3.length(xyForward) >= epsilon) {\n // Roll rotation can be seen as the right vector not being on the xy-plane, ie. right[2] != 0.0.\n // It can be negated by projecting the up vector on top of the forward vector.\n const xyDir = vec3.normalize([], xyForward);\n vec3.scale(xyUp, xyDir, vec3.dot(xyUp, xyDir));\n\n up[0] = xyUp[0];\n up[1] = xyUp[1];\n }\n\n const right = vec3.cross([], up, forward);\n if (vec3.len(right) < epsilon) {\n return null;\n }\n\n const bearing = Math.atan2(-right[1], right[0]);\n const pitch = Math.atan2(Math.sqrt(forward[0] * forward[0] + forward[1] * forward[1]), -forward[2]);\n\n return orientationFromPitchBearing(pitch, bearing);\n}\n\n/**\n * Various options for accessing physical properties of the underlying camera entity.\n * A direct access to these properties allows more flexible and precise controlling of the camera\n * while also being fully compatible and interchangeable with CameraOptions. All fields are optional.\n * See {@link Map#setFreeCameraOptions} and {@link Map#getFreeCameraOptions}\n *\n * @param {MercatorCoordinate} position Position of the camera in slightly modified web mercator coordinates\n - The size of 1 unit is the width of the projected world instead of the \"mercator meter\".\n Coordinate [0, 0, 0] is the north-west corner and [1, 1, 0] is the south-east corner.\n - Z coordinate is conformal and must respect minimum and maximum zoom values.\n - Zoom is automatically computed from the altitude (z)\n * @param {quat} orientation Orientation of the camera represented as a unit quaternion [x, y, z, w]\n in a left-handed coordinate space. Direction of the rotation is clockwise around the respective axis.\n The default pose of the camera is such that the forward vector is looking up the -Z axis and\n the up vector is aligned with north orientation of the map:\n forward: [0, 0, -1]\n up: [0, -1, 0]\n right [1, 0, 0]\n Orientation can be set freely but certain constraints still apply\n - Orientation must be representable with only pitch and bearing.\n - Pitch has an upper limit\n */\nclass FreeCameraOptions {\n orientation: ?quat;\n _position: ?MercatorCoordinate;\n _elevation: ?Elevation;\n _renderWorldCopies: boolean;\n\n constructor(position: ?MercatorCoordinate, orientation: ?quat) {\n this.position = position;\n this.orientation = orientation;\n }\n\n get position(): ?MercatorCoordinate {\n return this._position;\n }\n\n set position(position: ?MercatorCoordinate) {\n this._position = this._renderWorldCopies ? wrapCameraPosition(position) : position;\n }\n\n /**\n * Helper function for setting orientation of the camera by defining a focus point\n * on the map.\n *\n * @param {LngLatLike} location Location of the focus point on the map\n * @param {vec3?} up Up vector of the camera is necessary in certain scenarios where bearing can't be deduced\n * from the viewing direction.\n */\n lookAtPoint(location: LngLatLike, up?: vec3) {\n this.orientation = null;\n if (!this.position) {\n return;\n }\n\n const altitude = this._elevation ? this._elevation.getAtPoint(MercatorCoordinate.fromLngLat(location)) : 0;\n const pos: MercatorCoordinate = this.position;\n const target = MercatorCoordinate.fromLngLat(location, altitude);\n const forward = [target.x - pos.x, target.y - pos.y, target.z - pos.z];\n if (!up)\n up = [0, 0, 1];\n\n // flip z-component if the up vector is pointing downwards\n up[2] = Math.abs(up[2]);\n\n this.orientation = orientationFromFrame(forward, up);\n }\n\n /**\n * Helper function for setting the orientation of the camera as a pitch and a bearing.\n *\n * @param {number} pitch Pitch angle in degrees\n * @param {number} bearing Bearing angle in degrees\n */\n setPitchBearing(pitch: number, bearing: number) {\n this.orientation = orientationFromPitchBearing(degToRad(pitch), degToRad(-bearing));\n }\n}\n\n/**\n * While using the free camera API the outcome value of isZooming, isMoving and isRotating\n * is not a result of the free camera API.\n * If the user sets the map.interactive to true, there will be conflicting behaviors while\n * interacting with map via zooming or moving using mouse or/and keyboard which will result\n * in isZooming, isMoving and isRotating to return true while using free camera API. In order\n * to prevent the confilicting behavior please set map.interactive to false which will result\n * in muting the following events: zoom, zoomend, zoomstart, rotate, rotateend, rotatestart,\n * move, moveend, movestart, pitch, pitchend, pitchstart.\n */\n\nclass FreeCamera {\n _transform: mat4;\n _orientation: quat;\n\n constructor(position: ?vec3, orientation: ?quat) {\n this._transform = mat4.identity([]);\n this._orientation = quat.identity([]);\n\n if (orientation) {\n this._orientation = orientation;\n updateTransformOrientation(this._transform, this._orientation);\n }\n\n if (position) {\n updateTransformPosition(this._transform, position);\n }\n }\n\n get mercatorPosition(): MercatorCoordinate {\n const pos = this.position;\n return new MercatorCoordinate(pos[0], pos[1], pos[2]);\n }\n\n get position(): vec3 {\n const col: vec4 = getColumn(this._transform, 3);\n return [col[0], col[1], col[2]];\n }\n\n set position(value: vec3) {\n updateTransformPosition(this._transform, value);\n }\n\n get orientation(): quat {\n return this._orientation;\n }\n\n set orientation(value: quat) {\n this._orientation = value;\n updateTransformOrientation(this._transform, this._orientation);\n }\n\n getPitchBearing(): {pitch: number, bearing: number} {\n const f = this.forward();\n const r = this.right();\n\n return {\n bearing: Math.atan2(-r[1], r[0]),\n pitch: Math.atan2(Math.sqrt(f[0] * f[0] + f[1] * f[1]), -f[2])\n };\n }\n\n setPitchBearing(pitch: number, bearing: number) {\n this._orientation = orientationFromPitchBearing(pitch, bearing);\n updateTransformOrientation(this._transform, this._orientation);\n }\n\n forward(): vec3 {\n const col: vec4 = getColumn(this._transform, 2);\n // Forward direction is towards the negative Z-axis\n return [-col[0], -col[1], -col[2]];\n }\n\n up(): vec3 {\n const col: vec4 = getColumn(this._transform, 1);\n // Up direction has to be flipped to point towards north\n return [-col[0], -col[1], -col[2]];\n }\n\n right(): vec3 {\n const col: vec4 = getColumn(this._transform, 0);\n return [col[0], col[1], col[2]];\n }\n\n getCameraToWorld(worldSize: number, pixelsPerMeter: number): Float64Array {\n const cameraToWorld = new Float64Array(16);\n mat4.invert(cameraToWorld, this.getWorldToCamera(worldSize, pixelsPerMeter));\n return cameraToWorld;\n }\n\n getWorldToCamera(worldSize: number, pixelsPerMeter: number): Float64Array {\n // transformation chain from world space to camera space:\n // 1. Height value (z) of renderables is in meters. Scale z coordinate by pixelsPerMeter\n // 2. Transform from pixel coordinates to camera space with cameraMatrix^-1\n // 3. flip Y if required\n\n // worldToCamera: flip * cam^-1 * zScale\n // cameraToWorld: (flip * cam^-1 * zScale)^-1 => (zScale^-1 * cam * flip^-1)\n const matrix = new Float64Array(16);\n\n // Compute inverse of camera matrix and post-multiply negated translation\n const invOrientation = new Float64Array(4);\n const invPosition = this.position;\n\n quat.conjugate(invOrientation, this._orientation);\n vec3.scale(invPosition, invPosition, -worldSize);\n\n mat4.fromQuat(matrix, invOrientation);\n mat4.translate(matrix, matrix, invPosition);\n\n // Pre-multiply y (2nd row)\n matrix[1] *= -1.0;\n matrix[5] *= -1.0;\n matrix[9] *= -1.0;\n matrix[13] *= -1.0;\n\n // Post-multiply z (3rd column)\n matrix[8] *= pixelsPerMeter;\n matrix[9] *= pixelsPerMeter;\n matrix[10] *= pixelsPerMeter;\n matrix[11] *= pixelsPerMeter;\n\n return matrix;\n }\n\n getCameraToClipPerspective(fovy: number, aspectRatio: number, nearZ: number, farZ: number): Float64Array {\n const matrix = new Float64Array(16);\n mat4.perspective(matrix, fovy, aspectRatio, nearZ, farZ);\n return matrix;\n }\n\n clone(): FreeCamera {\n return new FreeCamera([...this.position], [...this.orientation]);\n }\n}\n\nexport {\n FreeCamera,\n FreeCameraOptions\n};\n","// @flow\n\nimport LngLat from './lng_lat';\nimport LngLatBounds from './lng_lat_bounds';\nimport MercatorCoordinate, {mercatorXfromLng, mercatorYfromLat, mercatorZfromAltitude, latFromMercatorY} from './mercator_coordinate';\nimport Point from '@mapbox/point-geometry';\nimport {wrap, clamp, radToDeg, degToRad} from '../util/util';\nimport {number as interpolate} from '../style-spec/util/interpolate';\nimport EXTENT from '../data/extent';\nimport {vec4, mat4, mat2, vec3, quat} from 'gl-matrix';\nimport {Aabb, Frustum, Ray} from '../util/primitives.js';\nimport EdgeInsets from './edge_insets';\nimport {FreeCamera, FreeCameraOptions, orientationFromFrame} from '../ui/free_camera';\nimport assert from 'assert';\n\nimport {UnwrappedTileID, OverscaledTileID, CanonicalTileID} from '../source/tile_id';\nimport type {Elevation} from '../terrain/elevation';\nimport type {PaddingOptions} from './edge_insets';\n\nconst NUM_WORLD_COPIES = 3;\nconst DEFAULT_MIN_ZOOM = 0;\n\ntype RayIntersectionResult = { p0: vec4, p1: vec4, t: number};\ntype ElevationReference = \"sea\" | \"ground\";\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<number>;\n projMatrix: Float64Array;\n invProjMatrix: Float64Array;\n alignedProjMatrix: Float64Array;\n pixelMatrix: Float64Array;\n pixelMatrixInverse: Float64Array;\n skyboxMatrix: Float32Array;\n glCoordMatrix: Float32Array;\n labelPlaneMatrix: Float32Array;\n freezeTileCoverage: boolean;\n cameraElevationReference: ElevationReference;\n _elevation: ?Elevation;\n _fov: number;\n _pitch: number;\n _zoom: number;\n _cameraZoom: ?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: {[_: number]: Float32Array};\n _alignedPosMatrixCache: {[_: number]: Float32Array};\n _camera: FreeCamera;\n _centerAltitude: number;\n _horizonShift: number;\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 || DEFAULT_MIN_ZOOM;\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 this._camera = new FreeCamera();\n this._centerAltitude = 0;\n this.cameraElevationReference = \"ground\";\n\n // Move the horizon closer to the center. 0 would not shift the horizon. 1 would put the horizon at the center.\n this._horizonShift = 0.1;\n }\n\n clone(): Transform {\n const clone = new Transform(this._minZoom, this._maxZoom, this._minPitch, this.maxPitch, this._renderWorldCopies);\n clone._elevation = this._elevation;\n clone._centerAltitude = this._centerAltitude;\n clone.tileSize = this.tileSize;\n clone.latRange = this.latRange;\n clone.width = this.width;\n clone.height = this.height;\n clone.cameraElevationReference = this.cameraElevationReference;\n clone._center = this._center;\n clone._setZoom(this.zoom);\n clone._cameraZoom = this._cameraZoom;\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._camera = this._camera.clone();\n clone._calcMatrices();\n clone.freezeTileCoverage = this.freezeTileCoverage;\n return clone;\n }\n\n get elevation(): ?Elevation { return this._elevation; }\n set elevation(elevation: ?Elevation) {\n if (this._elevation === elevation) return;\n this._elevation = elevation;\n if (!elevation) {\n this._cameraZoom = null;\n this._centerAltitude = 0;\n } else {\n if (this._updateCenterElevation())\n this._updateCameraOnTerrain();\n }\n this._calcMatrices();\n }\n updateElevation(constrainCameraOverTerrain: boolean) { // On render, no need for higher granularity on update reasons.\n if (this._terrainEnabled() && this._cameraZoom == null) {\n if (this._updateCenterElevation())\n this._updateCameraOnTerrain();\n }\n if (constrainCameraOverTerrain) {\n this._constrainCameraAltitude();\n }\n this._calcMatrices();\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._setZoom(z);\n if (this._terrainEnabled()) {\n this._updateCameraOnTerrain();\n }\n this._constrain();\n this._calcMatrices();\n }\n _setZoom(z: number) {\n this._zoom = z;\n this.scale = this.zoomScale(z);\n this.tileZoom = Math.floor(z);\n this.zoomFraction = z - this.tileZoom;\n }\n\n _updateCenterElevation(): boolean {\n if (!this._elevation)\n return false;\n\n // Camera zoom describes the distance of the camera to the sea level (altitude). It is used only for manipulating the camera location.\n // The standard zoom (this._zoom) defines the camera distance to the terrain (height). Its behavior and conceptual meaning in determining\n // which tiles to stream is same with or without the terrain.\n const elevationAtCenter = this._elevation.getAtPoint(MercatorCoordinate.fromLngLat(this.center), -1);\n\n if (elevationAtCenter === -1) {\n // Elevation data not loaded yet\n this._cameraZoom = null;\n return false;\n }\n\n this._centerAltitude = elevationAtCenter;\n return true;\n }\n\n // Places the camera above terrain so that the current zoom value is respected at the center.\n // In other words, camera height in relative to ground elevation remains constant.\n // Returns false if the elevation data is not available (yet) at the center point.\n _updateCameraOnTerrain() {\n const height = this.cameraToCenterDistance / this.worldSize;\n const terrainElevation = mercatorZfromAltitude(this._centerAltitude, this.center.lat);\n\n this._cameraZoom = this._zoomFromMercatorZ(terrainElevation + height);\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\n this._unmodified = false;\n this._center = center;\n if (this._terrainEnabled()) {\n if (this.cameraElevationReference === \"ground\") {\n // Check that the elevation data is available at the new location.\n if (this._updateCenterElevation())\n this._updateCameraOnTerrain();\n else\n this._cameraZoom = null;\n } else {\n this._updateZoomFromElevation();\n }\n }\n this._constrain();\n this._calcMatrices();\n }\n\n _updateZoomFromElevation() {\n if (this._cameraZoom == null || !this._elevation)\n return;\n\n // Compute zoom level from the height of the camera relative to the terrain\n const cameraZoom: number = this._cameraZoom;\n const elevationAtCenter = this._elevation.getAtPoint(MercatorCoordinate.fromLngLat(this.center));\n const mercatorElevation = mercatorZfromAltitude(elevationAtCenter, this.center.lat);\n const altitude = this._mercatorZfromZoom(cameraZoom);\n const minHeight = this._mercatorZfromZoom(this._maxZoom);\n const height = Math.max(altitude - mercatorElevation, minHeight);\n\n this._setZoom(this._zoomFromMercatorZ(height));\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 * Computes a zoom value relative to a map plane that goes through the provided mercator position.\n * @param {MercatorCoordinate} position A position defining the altitude of the the map plane.\n * @returns {number} The zoom value.\n */\n computeZoomRelativeTo(position: MercatorCoordinate): number {\n // Find map center position on the target plane by casting a ray from screen center towards the plane.\n // Direct distance to the target position is used if the target position is above camera position.\n const centerOnTargetAltitude = this.rayIntersectionCoordinate(this.pointRayIntersection(this.centerPoint, position.toAltitude()));\n\n let targetPosition: ?vec3;\n if (position.z < this._camera.position[2]) {\n targetPosition = [centerOnTargetAltitude.x, centerOnTargetAltitude.y, centerOnTargetAltitude.z];\n } else {\n targetPosition = [position.x, position.y, position.z];\n }\n\n const distToTarget = vec3.length(vec3.sub([], this._camera.position, targetPosition));\n return clamp(this._zoomFromMercatorZ(distToTarget), this._minZoom, this._maxZoom);\n }\n\n setFreeCameraOptions(options: FreeCameraOptions) {\n if (!this.height)\n return;\n\n if (!options.position && !options.orientation)\n return;\n\n // Camera state must be up-to-date before accessing its getters\n this._updateCameraState();\n\n let changed = false;\n if (options.orientation && !quat.exactEquals(options.orientation, this._camera.orientation)) {\n changed = this._setCameraOrientation(options.orientation);\n }\n\n if (options.position) {\n const newPosition = [options.position.x, options.position.y, options.position.z];\n if (!vec3.exactEquals(newPosition, this._camera.position)) {\n this._setCameraPosition(newPosition);\n changed = true;\n }\n }\n\n if (changed) {\n this._updateStateFromCamera();\n this.recenterOnTerrain();\n }\n }\n\n getFreeCameraOptions(): FreeCameraOptions {\n this._updateCameraState();\n const pos = this._camera.position;\n const options = new FreeCameraOptions();\n options.position = new MercatorCoordinate(pos[0], pos[1], pos[2]);\n options.orientation = this._camera.orientation;\n options._elevation = this.elevation;\n options._renderWorldCopies = this._renderWorldCopies;\n\n return options;\n }\n\n _setCameraOrientation(orientation: quat): boolean {\n // zero-length quaternions are not valid\n if (!quat.length(orientation))\n return false;\n\n quat.normalize(orientation, orientation);\n\n // The new orientation must be sanitized by making sure it can be represented\n // with a pitch and bearing. Roll-component must be removed and the camera can't be upside down\n const forward = vec3.transformQuat([], [0, 0, -1], orientation);\n const up = vec3.transformQuat([], [0, -1, 0], orientation);\n\n if (up[2] < 0.0)\n return false;\n\n const updatedOrientation = orientationFromFrame(forward, up);\n if (!updatedOrientation)\n return false;\n\n this._camera.orientation = updatedOrientation;\n return true;\n }\n\n _setCameraPosition(position: vec3) {\n // Altitude must be clamped to respect min and max zoom\n const minWorldSize = this.zoomScale(this.minZoom) * this.tileSize;\n const maxWorldSize = this.zoomScale(this.maxZoom) * this.tileSize;\n const distToCenter = this.cameraToCenterDistance;\n\n position[2] = clamp(position[2], distToCenter / maxWorldSize, distToCenter / minWorldSize);\n this._camera.position = position;\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 the vertical half-fov, accounting for padding, in radians.\n *\n * @readonly\n * @type {number}\n * @private\n */\n get fovAboveCenter(): number {\n return this._fov * (0.5 + this.centerOffset.y / this.height);\n }\n\n /**\n * Returns true if the padding options are equal.\n *\n * @param {PaddingOptions} padding The padding options to compare.\n * @returns {boolean} True if the padding options are equal.\n * @memberof Transform\n */\n isPaddingEqual(padding: PaddingOptions): boolean {\n return this._edgeInsets.equals(padding);\n }\n\n /**\n * Helper method to update edge-insets inplace.\n *\n * @param {PaddingOptions} start The initial padding options.\n * @param {PaddingOptions} target The target padding options.\n * @param {number} t The interpolation variable.\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 * @returns {Array<OverscaledTileID>} 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 useElevationData?: boolean\n }\n ): Array<OverscaledTileID> {\n let z = this.coveringZoomLevel(options);\n const actualZ = z;\n\n const useElevationData = !!options.useElevationData;\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 = 1 << z;\n const centerPoint = [numTiles * centerCoord.x, numTiles * centerCoord.y, 0];\n const cameraFrustum = Frustum.fromInvProjectionMatrix(this.invProjMatrix, this.worldSize, z);\n const cameraCoord = this.pointCoordinate(this.getCameraPoint());\n const meterToTile = numTiles * mercatorZfromAltitude(1, this.center.lat);\n const cameraAltitude = this._camera.position[2] / mercatorZfromAltitude(1, this.center.lat);\n const cameraPoint = [numTiles * cameraCoord.x, numTiles * cameraCoord.y, cameraAltitude];\n // Let's consider an example for !roundZoom: e.g. tileZoom 16 is used from zoom 16 all the way to zoom 16.99.\n // This would mean that the minimal distance to split would be based on distance from camera to center of 16.99 zoom.\n // The same is already incorporated in logic behind roundZoom for raster (so there is no adjustment needed in following line).\n // 0.02 added to compensate for precision errors, see \"coveringTiles for terrain\" test in transform.test.js.\n const zoomSplitDistance = this.cameraToCenterDistance / options.tileSize * (options.roundZoom ? 1 : 0.502);\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 const minZoom = this.pitch <= 60.0 && this._edgeInsets.top <= this._edgeInsets.bottom && !this._elevation ? z : 0;\n\n const maxRange = this.elevation ? this.elevation.exaggeration() * 10000 : 0;\n const newRootTile = (wrap: number): any => {\n const max = maxRange;\n const min = -maxRange;\n return {\n // With elevation, this._elevation provides z coordinate values. For 2D:\n // All tiles are on zero elevation plane => z difference is zero\n aabb: new Aabb([wrap * numTiles, 0, min], [(wrap + 1) * numTiles, numTiles, max]),\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 const getAABBFromElevation = (aabb, tileID) => {\n assert(this._elevation);\n if (!this._elevation) return; // To silence flow.\n const minmax = this._elevation.getMinMaxForTile(tileID);\n if (minmax) {\n aabb.min[2] = minmax.min;\n aabb.max[2] = minmax.max;\n aabb.center[2] = (aabb.min[2] + aabb.max[2]) / 2;\n }\n };\n const square = a => a * a;\n const cameraHeightSqr = square((cameraAltitude - this._centerAltitude) * meterToTile); // in tile coordinates.\n\n // Scale distance to split for acute angles.\n // dzSqr: z component of camera to tile distance, square.\n // dSqr: 3D distance of camera to tile, square.\n const distToSplitScale = (dzSqr, dSqr) => {\n // When the angle between camera to tile ray and tile plane is smaller\n // than acuteAngleThreshold, scale the distance to split. Scaling is adaptive: smaller\n // the angle, the scale gets lower value. Although it seems early to start at 45,\n // it is not: scaling kicks in around 60 degrees pitch.\n const acuteAngleThresholdSin = 0.707; // Math.sin(45)\n const stretchTile = 1.1;\n // Distances longer than 'dz / acuteAngleThresholdSin' gets scaled\n // following geometric series sum: every next dz length in distance can be\n // 'stretchTile times' longer. It is further, the angle is sharper. Total,\n // adjusted, distance would then be:\n // = dz / acuteAngleThresholdSin + (dz * stretchTile + dz * stretchTile ^ 2 + ... + dz * stretchTile ^ k),\n // where k = (d - dz / acuteAngleThresholdSin) / dz = d / dz - 1 / acuteAngleThresholdSin;\n // = dz / acuteAngleThresholdSin + dz * ((stretchTile ^ (k + 1) - 1) / (stretchTile - 1) - 1)\n // or put differently, given that k is based on d and dz, tile on distance d could be used on distance scaled by:\n // 1 / acuteAngleThresholdSin + (stretchTile ^ (k + 1) - 1) / (stretchTile - 1) - 1\n if (dSqr * square(acuteAngleThresholdSin) < dzSqr) return 1.0; // Early return, no scale.\n const r = Math.sqrt(dSqr / dzSqr);\n const k = r - 1 / acuteAngleThresholdSin;\n return r / (1 / acuteAngleThresholdSin + (Math.pow(stretchTile, k + 1) - 1) / (stretchTile - 1) - 1);\n };\n\n if (this._renderWorldCopies) {\n // Render copy of the globe thrice on both sides\n for (let i = 1; i <= NUM_WORLD_COPIES; 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 let shouldSplit = true;\n if (minZoom <= it.zoom && it.zoom < maxZoom) {\n const dx = it.aabb.distanceX(cameraPoint);\n const dy = it.aabb.distanceY(cameraPoint);\n let dzSqr = cameraHeightSqr;\n\n if (useElevationData) {\n dzSqr = square(it.aabb.distanceZ(cameraPoint) * meterToTile);\n }\n\n const distanceSqr = dx * dx + dy * dy + dzSqr;\n const distToSplit = (1 << maxZoom - it.zoom) * zoomSplitDistance;\n const distToSplitSqr = square(distToSplit * distToSplitScale(Math.max(dzSqr, cameraHeightSqr), distanceSqr));\n\n shouldSplit = distanceSqr < distToSplitSqr;\n }\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 || !shouldSplit) {\n const tileZoom = it.zoom === maxZoom ? overscaledZ : it.zoom;\n if (!!options.minzoom && options.minzoom > tileZoom) {\n // Not within source tile range.\n continue;\n }\n\n const dx = centerPoint[0] - ((0.5 + x + (it.wrap << it.zoom)) * (1 << (z - it.zoom)));\n const dy = centerPoint[1] - 0.5 - y;\n const id = it.tileID ? it.tileID : new OverscaledTileID(tileZoom, it.wrap, it.zoom, x, y);\n\n result.push({tileID: id, distanceSq: dx * dx + dy * dy});\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 const aabb = it.aabb.quadrant(i);\n let tileID = null;\n if (useElevationData && it.zoom > maxZoom - 6) {\n // Using elevation data for tiles helps clipping out tiles that are not visible and\n // precise distance calculation. it.zoom > maxZoom - 6 is an optimization as those before get subdivided\n // or they are so far at horizon that it doesn't matter.\n tileID = new OverscaledTileID(it.zoom + 1 === maxZoom ? overscaledZ : it.zoom + 1, it.wrap, it.zoom + 1, childX, childY);\n getAABBFromElevation(aabb, tileID);\n }\n stack.push({aabb, zoom: it.zoom + 1, x: childX, y: childY, wrap: it.wrap, fullyVisible, tileID});\n }\n }\n const cover = result.sort((a, b) => a.distanceSq - b.distanceSq).map(a => a.tileID);\n // Relax the assertion on terrain, on high zoom we use distance to center of tile\n // while camera might be closer to selected center of map.\n assert(!cover.length || this.elevation || cover[0].overscaledZ === overscaledZ);\n return cover;\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 setLocation(location: MercatorCoordinate) {\n this.center = this.coordinateLocation(location);\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. In 3D mode\n * (with terrain) this behaves the same as in 2D mode.\n * This method is coupled with {@see pointLocation} in 3D mode to model map manipulation\n * using flat plane approach to keep constant elevation above ground.\n * @param {LngLat} lnglat location\n * @returns {Point} screen point\n * @private\n */\n locationPoint(lnglat: LngLat) {\n return this._coordinatePoint(this.locationCoordinate(lnglat), false);\n }\n\n /**\n * Given a location, return the screen point that corresponds to it\n * In 3D mode (when terrain is enabled) elevation is sampled for the point before\n * projecting it. In 2D mode, behaves the same locationPoint.\n * @param {LngLat} lnglat location\n * @returns {Point} screen point\n * @private\n */\n locationPoint3D(lnglat: LngLat) {\n return this._coordinatePoint(this.locationCoordinate(lnglat), true);\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 point on screen, return its lnglat\n * In 3D mode (map with terrain) returns location of terrain raycast point.\n * In 2D mode, behaves the same as {@see pointLocation}.\n * @param {Point} p screen point\n * @returns {LngLat} lnglat location\n * @private\n */\n pointLocation3D(p: Point) {\n return this.coordinateLocation(this.pointCoordinate3D(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 /**\n * Casts a ray from a point on screen and returns the Ray,\n * and the extent along it, at which it intersects the map plane.\n *\n * @param {Point} p viewport pixel co-ordinates\n * @param {number} z optional altitude of the map plane\n * @returns {{ p0: vec4, p1: vec4, t: number }} p0,p1 are two points on the ray\n * t is the fractional extent along the ray at which the ray intersects the map plane\n * @private\n */\n pointRayIntersection(p: Point, z: ?number): RayIntersectionResult {\n const targetZ = (z !== undefined && z !== null) ? z : this._centerAltitude;\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 p0 = [p.x, p.y, 0, 1];\n const p1 = [p.x, p.y, 1, 1];\n\n vec4.transformMat4(p0, p0, this.pixelMatrixInverse);\n vec4.transformMat4(p1, p1, this.pixelMatrixInverse);\n\n const w0 = p0[3];\n const w1 = p1[3];\n vec4.scale(p0, p0, 1 / w0);\n vec4.scale(p1, p1, 1 / w1);\n\n const z0 = p0[2];\n const z1 = p1[2];\n\n const t = z0 === z1 ? 0 : (targetZ - z0) / (z1 - z0);\n\n return {p0, p1, t};\n }\n\n screenPointToMercatorRay(p: Point): Ray {\n const p0 = [p.x, p.y, 0, 1];\n const p1 = [p.x, p.y, 1, 1];\n\n vec4.transformMat4(p0, p0, this.pixelMatrixInverse);\n vec4.transformMat4(p1, p1, this.pixelMatrixInverse);\n\n vec4.scale(p0, p0, 1 / p0[3]);\n vec4.scale(p1, p1, 1 / p1[3]);\n\n // Convert altitude from meters to pixels\n p0[2] = mercatorZfromAltitude(p0[2], this._center.lat) * this.worldSize;\n p1[2] = mercatorZfromAltitude(p1[2], this._center.lat) * this.worldSize;\n\n vec4.scale(p0, p0, 1 / this.worldSize);\n vec4.scale(p1, p1, 1 / this.worldSize);\n\n return new Ray([p0[0], p0[1], p0[2]], vec3.normalize([], vec3.sub([], p1, p0)));\n }\n\n /**\n * Helper method to convert the ray intersection with the map plane to MercatorCoordinate\n *\n * @param {RayIntersectionResult} rayIntersection\n * @returns {MercatorCoordinate}\n * @private\n */\n rayIntersectionCoordinate(rayIntersection: RayIntersectionResult): MercatorCoordinate {\n const {p0, p1, t} = rayIntersection;\n\n const z0 = mercatorZfromAltitude(p0[2], this._center.lat);\n const z1 = mercatorZfromAltitude(p1[2], this._center.lat);\n\n return new MercatorCoordinate(\n interpolate(p0[0], p1[0], t) / this.worldSize,\n interpolate(p0[1], p1[1], t) / this.worldSize,\n interpolate(z0, z1, t));\n }\n\n /**\n * Given a point on screen, returns MercatorCoordinate.\n * @param {Point} p top left origin screen point, in pixels.\n * @private\n */\n pointCoordinate(p: Point): MercatorCoordinate {\n const horizonOffset = this.horizonLineFromTop(false);\n const clamped = new Point(p.x, Math.max(horizonOffset, p.y));\n\n return this.rayIntersectionCoordinate(this.pointRayIntersection(clamped));\n }\n\n /**\n * Given a point on screen, returns MercatorCoordinate.\n * In 3D mode, raycast to terrain. In 2D mode, behaves the same as {@see pointCoordinate}.\n * For p above terrain, don't return point behind camera but clamp p.y at the top of terrain.\n * @param {Point} p top left origin screen point, in pixels.\n * @private\n */\n pointCoordinate3D(p: Point): MercatorCoordinate {\n if (!this.elevation) return this.pointCoordinate(p);\n const elevation = this.elevation;\n let raycast = this.elevation.pointCoordinate(p);\n if (raycast) return new MercatorCoordinate(raycast[0], raycast[1], raycast[2]);\n let start = 0, end = this.horizonLineFromTop();\n if (p.y > end) return this.pointCoordinate(p); // holes between tiles below horizon line or below bottom.\n const samples = 10;\n const threshold = 0.02 * end;\n const r = p.clone();\n\n for (let i = 0; i < samples && end - start > threshold; i++) {\n r.y = interpolate(start, end, 0.66); // non uniform binary search favoring points closer to horizon.\n const rCast = elevation.pointCoordinate(r);\n if (rCast) {\n end = r.y;\n raycast = rCast;\n } else {\n start = r.y;\n }\n }\n return raycast ? new MercatorCoordinate(raycast[0], raycast[1], raycast[2]) : this.pointCoordinate(p);\n }\n\n /**\n * Returns true if a screenspace Point p, is above the horizon.\n *\n * @param {Point} p\n * @returns {boolean}\n * @private\n */\n isPointAboveHorizon(p: Point): boolean {\n if (!this.elevation) {\n const horizon = this.horizonLineFromTop();\n return p.y < horizon;\n } else {\n return !this.elevation.pointCoordinate(p);\n }\n }\n\n /**\n * Given a coordinate, return the screen point that corresponds to it\n * @param {Coordinate} coord\n * @param {boolean} sampleTerrainIn3D in 3D mode (terrain enabled), sample elevation for the point.\n * If false, do the same as in 2D mode, assume flat camera elevation plane for all points.\n * @returns {Point} screen point\n * @private\n */\n _coordinatePoint(coord: MercatorCoordinate, sampleTerrainIn3D: boolean) {\n const elevation = sampleTerrainIn3D && this.elevation ? this.elevation.getAtPoint(coord, this._centerAltitude) : this._centerAltitude;\n const p = [coord.x * this.worldSize, coord.y * this.worldSize, elevation + coord.toAltitude(), 1];\n vec4.transformMat4(p, p, this.pixelMatrix);\n return p[3] > 0 ?\n new Point(p[0] / p[3], p[1] / p[3]) :\n new Point(Number.MAX_VALUE, Number.MAX_VALUE);\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 if (this._terrainEnabled()) return this._getBounds3D();\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 _getBounds3D(): LngLatBounds {\n assert(this.elevation);\n const elevation = ((this.elevation: any): Elevation);\n const minmax = elevation.visibleDemTiles.reduce((acc, t) => {\n if (t.dem) {\n const tree = t.dem.tree;\n acc.min = Math.min(acc.min, tree.minimums[0]);\n acc.max = Math.max(acc.max, tree.maximums[0]);\n }\n return acc;\n }, {min: Number.MAX_VALUE, max: 0});\n minmax.min *= elevation.exaggeration();\n minmax.max *= elevation.exaggeration();\n const top = this.horizonLineFromTop();\n return [\n new Point(0, top),\n new Point(this.width, top),\n new Point(this.width, this.height),\n new Point(0, this.height)\n ].reduce((acc, p) => {\n return acc\n .extend(this.coordinateLocation(this.rayIntersectionCoordinate(this.pointRayIntersection(p, minmax.min))))\n .extend(this.coordinateLocation(this.rayIntersectionCoordinate(this.pointRayIntersection(p, minmax.max))));\n }, new LngLatBounds());\n }\n\n /**\n * Returns position of horizon line from the top of the map in pixels. If horizon is not visible, returns 0.\n * @private\n */\n horizonLineFromTop(clampToTop: boolean = true): number {\n // h is height of space above map center to horizon.\n const h = this.height / 2 / Math.tan(this._fov / 2) / Math.tan(Math.max(this._pitch, 0.1)) + this.centerOffset.y;\n // incorporate 3% of the area above center to account for reduced precision.\n const horizonEpsilon = 0.03;\n const offset = this.height / 2 - h * (1 - horizonEpsilon);\n return clampToTop ? Math.max(0, offset) : offset;\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<number> {\n return this.mercatorMatrix.slice();\n }\n\n recenterOnTerrain() {\n if (!this._elevation)\n return;\n\n const elevation: Elevation = this._elevation;\n this._updateCameraState();\n\n // Cast a ray towards the sea level and find the intersection point with the terrain.\n const start = this._camera.position;\n const dir = this._camera.forward();\n\n if (start.z <= 0 || dir[2] >= 0)\n return;\n\n // The raycast function expects z-component to be in meters\n const metersToMerc = mercatorZfromAltitude(1.0, this._center.lat);\n start[2] /= metersToMerc;\n dir[2] /= metersToMerc;\n vec3.normalize(dir, dir);\n\n const t = elevation.raycast(start, dir, elevation.exaggeration());\n\n if (t) {\n const point = vec3.scaleAndAdd([], start, dir, t);\n const newCenter = new MercatorCoordinate(point[0], point[1], mercatorZfromAltitude(point[2], latFromMercatorY(point[1])));\n\n const pos = this._camera.position;\n const camToNew = [newCenter.x - pos[0], newCenter.y - pos[1], newCenter.z - pos[2]];\n const maxAltitude = newCenter.z + vec3.length(camToNew);\n\n // Camera zoom has to be updated as the orbit distance might have changed\n this._cameraZoom = this._zoomFromMercatorZ(maxAltitude);\n this._centerAltitude = newCenter.toAltitude();\n this._center = newCenter.toLngLat();\n this._updateZoomFromElevation();\n this._constrain();\n this._calcMatrices();\n }\n }\n\n _constrainCameraAltitude() {\n if (!this._elevation)\n return;\n\n const elevation: Elevation = this._elevation;\n this._updateCameraState();\n const elevationAtCamera = elevation.getAtPoint(this._camera.mercatorPosition);\n\n const minHeight = this._minimumHeightOverTerrain() * Math.cos(degToRad(this._maxPitch));\n const terrainElevation = mercatorZfromAltitude(elevationAtCamera, this._center.lat);\n const cameraHeight = this._camera.position[2] - terrainElevation;\n\n if (cameraHeight < minHeight) {\n const center = MercatorCoordinate.fromLngLat(this._center, this._centerAltitude);\n const cameraPos = this._camera.mercatorPosition;\n const cameraToCenter = [center.x - cameraPos.x, center.y - cameraPos.y, center.z - cameraPos.z];\n const prevDistToCamera = vec3.length(cameraToCenter);\n\n // Adjust the camera vector so that the camera is placed above the terrain.\n // Distance between the camera and the center point is kept constant.\n cameraToCenter[2] -= minHeight - cameraHeight;\n\n const newDistToCamera = vec3.length(cameraToCenter);\n if (newDistToCamera === 0)\n return;\n\n vec3.scale(cameraToCenter, cameraToCenter, prevDistToCamera / newDistToCamera);\n this._camera.position = [center.x - cameraToCenter[0], center.y - cameraToCenter[1], center.z - cameraToCenter[2]];\n this._camera.orientation = orientationFromFrame(cameraToCenter, this._camera.up());\n this._updateStateFromCamera();\n }\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._constrainCameraAltitude();\n\n this._unmodified = unmodified;\n this._constraining = false;\n }\n\n /**\n * Returns the minimum zoom at which `this.width` can fit `this.lngRange`\n * and `this.height` can fit `this.latRange`.\n *\n * @returns {number} The zoom value.\n */\n _minZoomForBounds(): number {\n const minZoomForDim = (dim: number, range: [number, number]): number => {\n return Math.log2(dim / (this.tileSize * Math.abs(range[1] - range[0])));\n };\n let minLatZoom = DEFAULT_MIN_ZOOM;\n if (this.latRange) {\n const latRange = this.latRange;\n minLatZoom = minZoomForDim(this.height, [mercatorYfromLat(latRange[0]), mercatorYfromLat(latRange[1])]);\n }\n let minLngZoom = DEFAULT_MIN_ZOOM;\n if (this.lngRange) {\n const lngRange = this.lngRange;\n minLngZoom = minZoomForDim(this.width, [mercatorXfromLng(lngRange[0]), mercatorXfromLng(lngRange[1])]);\n }\n\n return Math.max(minLatZoom, minLngZoom);\n }\n\n /**\n * Returns the maximum distance of the camera from the center of the bounds, such that\n * `this.width` can fit `this.lngRange` and `this.height` can fit `this.latRange`.\n * In mercator units.\n *\n * @returns {number} The mercator z coordinate.\n */\n _maxCameraBoundsDistance(): number {\n return this._mercatorZfromZoom(this._minZoomForBounds());\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 const pixelsPerMeter = mercatorZfromAltitude(1, this.center.lat) * this.worldSize;\n\n this._updateCameraState();\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.fovAboveCenter;\n\n const cameraToSeaLevelDistance = this._camera.position[2] * this.worldSize / Math.cos(this._pitch);\n const topHalfSurfaceDistance = Math.sin(fovAboveCenter) * cameraToSeaLevelDistance / 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 + cameraToSeaLevelDistance;\n // Add a bit extra to avoid precision problems when a fragment's distance is exactly `furthestDistance`\n\n const horizonDistance = cameraToSeaLevelDistance * (1 / this._horizonShift);\n\n const farZ = Math.min(furthestDistance * 1.01, horizonDistance);\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 const worldToCamera = this._camera.getWorldToCamera(this.worldSize, pixelsPerMeter);\n const cameraToClip = this._camera.getCameraToClipPerspective(this._fov, this.width / this.height, nearZ, farZ);\n\n // Apply center of perspective offset\n cameraToClip[8] = -offset.x * 2 / this.width;\n cameraToClip[9] = offset.y * 2 / this.height;\n\n let m = mat4.mul([], cameraToClip, worldToCamera);\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 / pixelsPerMeter]);\n\n this.projMatrix = m;\n // For tile cover calculation, use inverted of base (non elevated) matrix\n // as tile elevations are in tile coordinates and relative to center elevation.\n this.invProjMatrix = mat4.invert(new Float64Array(16), this.projMatrix);\n\n const view = new Float32Array(16);\n mat4.identity(view);\n mat4.scale(view, view, [1, -1, 1]);\n mat4.rotateX(view, view, this._pitch);\n mat4.rotateZ(view, view, this.angle);\n\n const projection = mat4.perspective(new Float32Array(16), this._fov, this.width / this.height, nearZ, farZ);\n // The distance in pixels the skybox needs to be shifted down by to meet the shifted horizon.\n const skyboxHorizonShift = (Math.PI / 2 - this._pitch) * (this.height / this._fov) * this._horizonShift;\n // Apply center of perspective offset to skybox projection\n projection[8] = -offset.x * 2 / this.width;\n projection[9] = (offset.y + skyboxHorizonShift) * 2 / this.height;\n this.skyboxMatrix = mat4.multiply(view, projection, view);\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 coordinates 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 _updateCameraState() {\n if (!this.height) return;\n\n // Set camera orientation and move it to a proper distance from the map\n this._camera.setPitchBearing(this._pitch, this.angle);\n\n const dir = this._camera.forward();\n const distance = this.cameraToCenterDistance;\n const center = this.point;\n\n // Use camera zoom (if terrain is enabled) to maintain constant altitude to sea level\n const zoom = this._cameraZoom ? this._cameraZoom : this._zoom;\n const altitude = this._mercatorZfromZoom(zoom);\n const height = altitude - mercatorZfromAltitude(this._centerAltitude, this.center.lat);\n\n // simplified version of: this._worldSizeFromZoom(this._zoomFromMercatorZ(height))\n const updatedWorldSize = this.cameraToCenterDistance / height;\n\n this._camera.position = [\n center.x / this.worldSize - (dir[0] * distance) / updatedWorldSize,\n center.y / this.worldSize - (dir[1] * distance) / updatedWorldSize,\n mercatorZfromAltitude(this._centerAltitude, this._center.lat) + (-dir[2] * distance) / updatedWorldSize\n ];\n }\n\n /**\n * Apply a 3d translation to the camera position, but clamping it so that\n * it respects the bounds set by `this.latRange` and `this.lngRange`.\n *\n * @param {vec3} translation The translation vector.\n */\n _translateCameraConstrained(translation: vec3) {\n const maxDistance = this._maxCameraBoundsDistance();\n // Define a ceiling in mercator Z\n const maxZ = maxDistance * Math.cos(this._pitch);\n const z = this._camera.position[2];\n const deltaZ = translation[2];\n let t = 1;\n // we only need to clamp if the camera is moving upwards\n if (deltaZ > 0) {\n t = Math.min((maxZ - z) / deltaZ, 1);\n }\n\n this._camera.position = vec3.scaleAndAdd([], this._camera.position, translation, t);\n this._updateStateFromCamera();\n }\n\n _updateStateFromCamera() {\n const position = this._camera.position;\n const dir = this._camera.forward();\n const {pitch, bearing} = this._camera.getPitchBearing();\n\n // Compute zoom from the distance between camera and terrain\n const centerAltitude = mercatorZfromAltitude(this._centerAltitude, this.center.lat);\n const minHeight = this._mercatorZfromZoom(this._maxZoom) * Math.cos(degToRad(this._maxPitch));\n const height = Math.max((position[2] - centerAltitude) / Math.cos(pitch), minHeight);\n const zoom = this._zoomFromMercatorZ(height);\n\n // Cast a ray towards the ground to find the center point\n vec3.scaleAndAdd(position, position, dir, height);\n\n this._pitch = clamp(pitch, degToRad(this.minPitch), degToRad(this.maxPitch));\n this.angle = wrap(bearing, -Math.PI, Math.PI);\n this._setZoom(clamp(zoom, this._minZoom, this._maxZoom));\n\n if (this._terrainEnabled())\n this._updateCameraOnTerrain();\n\n this._center = new MercatorCoordinate(position[0], position[1], position[2]).toLngLat();\n this._unmodified = false;\n this._constrain();\n this._calcMatrices();\n }\n\n _worldSizeFromZoom(zoom: number): number {\n return Math.pow(2.0, zoom) * this.tileSize;\n }\n\n _mercatorZfromZoom(zoom: number): number {\n return this.cameraToCenterDistance / this._worldSizeFromZoom(zoom);\n }\n\n _minimumHeightOverTerrain() {\n // Determine minimum height for the camera over the terrain related to current zoom.\n // Values above than 2 allow max-pitch camera closer to e.g. top of the hill, exposing\n // drape raster overscale artifacts or cut terrain (see under it) as it gets clipped on\n // near plane. Returned value is in mercator coordinates.\n const MAX_DRAPE_OVERZOOM = 2;\n const zoom = Math.min((this._cameraZoom != null ? this._cameraZoom : this._zoom) + MAX_DRAPE_OVERZOOM, this._maxZoom);\n return this._mercatorZfromZoom(zoom);\n }\n\n _zoomFromMercatorZ(z: number): number {\n return this.scaleZoom(this.cameraToCenterDistance / (z * this.tileSize));\n }\n\n _terrainEnabled(): boolean {\n return !!this._elevation;\n }\n\n isHorizonVisibleForPoints(p0: Point, p1: Point): boolean {\n const minX = Math.min(p0.x, p1.x);\n const maxX = Math.max(p0.x, p1.x);\n const minY = Math.min(p0.y, p1.y);\n const maxY = Math.max(p0.y, p1.y);\n\n const min = new Point(minX, minY);\n const max = new Point(maxX, maxY);\n\n const corners = [\n min, max,\n new Point(minX, maxY),\n new Point(maxX, minY),\n ];\n\n const minWX = (this._renderWorldCopies) ? -NUM_WORLD_COPIES : 0;\n const maxWX = (this._renderWorldCopies) ? 1 + NUM_WORLD_COPIES : 1;\n const minWY = 0;\n const maxWY = 1;\n\n for (const corner of corners) {\n const rayIntersection = this.pointRayIntersection(corner);\n if (rayIntersection.t < 0) {\n return true;\n }\n const coordinate = this.rayIntersectionCoordinate(rayIntersection);\n if (coordinate.x < minWX || coordinate.y < minWY ||\n coordinate.x > maxWX || coordinate.y > maxWY) {\n return true;\n }\n }\n\n return false;\n }\n\n // Checks the four corners of the frustum to see if they lie in the map's quad.\n isHorizonVisible(): boolean {\n // we consider the horizon as visible if the angle between\n // a the top plane of the frustum and the map plane is smaller than this threshold.\n const horizonAngleEpsilon = 2;\n if (this.pitch + radToDeg(this.fovAboveCenter) > (90 - horizonAngleEpsilon)) {\n return true;\n }\n\n return this.isHorizonVisibleForPoints(new Point(0, 0), new Point(this.width, this.height));\n }\n\n /**\n * Converts a zoom delta value into a physical distance travelled in web mercator coordinates.\n * @param {vec3} center Destination mercator point of the movement.\n * @param {number} zoomDelta Change in the zoom value.\n * @returns {number} The distance in mercator coordinates.\n */\n zoomDeltaToMovement(center: vec3, zoomDelta: number): number {\n const distance = vec3.length(vec3.sub([], this._camera.position, center));\n const relativeZoom = this._zoomFromMercatorZ(distance) + zoomDelta;\n return distance - this._mercatorZfromZoom(relativeZoom);\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\nexport default Transform;\n","// @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 window.history.replaceState(window.history.state, null, location);\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<Point>;\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<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 `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\n /**\n * Fired after speed index calculation is completed if speedIndexTiming option has set to true\n *\n * @private\n * @event speedindexcompleted\n * @memberof Map\n * @instance\n * @example\n * // Initialize the map\n * var map = new mapboxgl.Map({ // map options });\n * map.speedIndexTiming = true;\n * // Set an event listener that fires\n * map.on('speedindexcompleted', function() {\n * console.log(`speed index is ${map.speedIndexNumber}`);\n * });\n */\n | 'speedindexcompleted'\n;\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: false})\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 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<Touch>, points: Array<Point>) {\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<Point>) {\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<Point>, mapTouches: Array<Touch>) {\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<Point>, mapTouches: Array<Touch>) {\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<Point>, mapTouches: Array<Touch>) {\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<Point>, mapTouches: Array<Touch>) {\n this.singleTap.touchstart(e, points, mapTouches);\n }\n\n touchmove(e: TouchEvent, points: Array<Point>, mapTouches: Array<Touch>) {\n this.singleTap.touchmove(e, points, mapTouches);\n }\n\n touchend(e: TouchEvent, points: Array<Point>, mapTouches: Array<Touch>) {\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<Point>, mapTouches: Array<Touch>) {\n this._zoomIn.touchstart(e, points, mapTouches);\n this._zoomOut.touchstart(e, points, mapTouches);\n }\n\n touchmove(e: TouchEvent, points: Array<Point>, mapTouches: Array<Touch>) {\n this._zoomIn.touchmove(e, points, mapTouches);\n this._zoomOut.touchmove(e, points, mapTouches);\n }\n\n touchend(e: TouchEvent, points: Array<Point>, mapTouches: Array<Touch>) {\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 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<Point>, mapTouches: Array<Touch>) {\n return this._calculateTransform(e, points, mapTouches);\n }\n\n touchmove(e: TouchEvent, points: Array<Point>, mapTouches: Array<Touch>) {\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<Point>, mapTouches: Array<Touch>) {\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<Point>, mapTouches: Array<Touch>) {\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<Point>, mapTouches: Array<Touch>) {\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<Point>, mapTouches: Array<Touch>) {\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<Point>, mapTouches: Array<Touch>) {\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<Touch>, points: Array<Point>, 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 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 Point from '@mapbox/point-geometry';\n\nimport type Map from '../map';\nimport type HandlerManager from '../handler_manager';\nimport MercatorCoordinate from '../../geo/mercator_coordinate';\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 _aroundPoint: Point;\n _aroundCoord: MercatorCoordinate;\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 this._aroundPoint = this._aroundCenter ? this._map.transform.centerPoint : pos;\n this._aroundCoord = this._map.transform.pointCoordinate3D(this._aroundPoint);\n this._targetZoom = undefined;\n\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 const startingZoom = () => {\n return tr._terrainEnabled() ? tr.computeZoomRelativeTo(this._aroundCoord) : tr.zoom;\n };\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 startZoom = startingZoom();\n const startScale = Math.pow(2.0, startZoom);\n\n const fromScale = typeof this._targetZoom === 'number' ? tr.zoomScale(this._targetZoom) : startScale;\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 = startingZoom();\n this._easing = this._smoothOutEasing(200);\n }\n\n this._delta = 0;\n }\n const targetZoom = typeof this._targetZoom === 'number' ?\n this._targetZoom : startingZoom();\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 - startingZoom(),\n around: this._aroundPoint,\n aroundCoord: this._aroundCoord,\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 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 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<Point>, mapTouches: Array<Touch>) {\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<Point>, mapTouches: Array<Touch>) {\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<Point>, mapTouches: Array<Touch>) {\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';\nimport {vec3} from 'gl-matrix';\nimport MercatorCoordinate, {altitudeFromMercatorZ} from '../geo/mercator_coordinate';\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\nclass TrackingEllipsoid {\n constants: Array<number>;\n radius: number;\n\n constructor() {\n // a, b, c in the equation x²/a² + y²/b² + z²/c² = 1\n this.constants = [1, 1, 0.01];\n this.radius = 0;\n }\n\n setup(center: vec3, pointOnSurface: vec3) {\n const centerToSurface = vec3.sub([], pointOnSurface, center);\n if (centerToSurface[2] < 0) {\n this.radius = vec3.length(vec3.div([], centerToSurface, this.constants));\n } else {\n // The point on surface is above the center. This can happen for example when the camera is\n // below the clicked point (like a mountain) Use slightly shorter radius for less aggressive movement\n this.radius = vec3.length([centerToSurface[0], centerToSurface[1], 0]);\n }\n }\n\n // Cast a ray from the center of the ellipsoid and the intersection point.\n projectRay(dir: vec3): vec3 {\n // Perform the intersection test against a unit sphere\n vec3.div(dir, dir, this.constants);\n vec3.normalize(dir, dir);\n vec3.mul(dir, dir, this.constants);\n\n const intersection = vec3.scale([], dir, this.radius);\n\n if (intersection[2] > 0) {\n // The intersection point is above horizon so special handling is required.\n // Otherwise direction of the movement would be inverted due to the ellipsoid shape\n const h = vec3.scale([], [0, 0, 1], vec3.dot(intersection, [0, 0, 1]));\n const r = vec3.scale([], vec3.normalize([], [intersection[0], intersection[1], 0]), this.radius);\n const p = vec3.add([], intersection, vec3.scale([], vec3.sub([], vec3.add([], r, h), intersection), 2));\n\n intersection[0] = p[0];\n intersection[1] = p[1];\n }\n\n return intersection;\n }\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<Point>, mapTouches: Array<Touch>) => HandlerResult | void;\n +touchmove?: (e: TouchEvent, points: Array<Point>, mapTouches: Array<Touch>) => HandlerResult | void;\n +touchend?: (e: TouchEvent, points: Array<Point>, mapTouches: Array<Touch>) => HandlerResult | void;\n +touchcancel?: (e: TouchEvent, points: Array<Point>, mapTouches: Array<Touch>) => 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 // the point to not move when changing the camera in mercator coordinates\n aroundCoord?: MercatorCoordinate | 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 _trackingEllipsoid: TrackingEllipsoid;\n _dragOrigin: ?vec3;\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 this._trackingEllipsoid = new TrackingEllipsoid();\n this._dragOrigin = null;\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 this._add('blockableMapEvent', new BlockableMapEventHandler(map));\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 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<string>) {\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<string>, 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 if (e.type === 'blur') {\n this.stop(true);\n return;\n }\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 _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.aroundCoord !== undefined) combined.aroundCoord = change.aroundCoord;\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 const eventStarted = (type) => {\n const newEvent = combinedEventsInProgress[type];\n return newEvent && !this._eventsInProgress[type];\n };\n\n const eventEnded = (type) => {\n const event = this._eventsInProgress[type];\n return event && !this._handlersById[event.handlerName].isActive();\n };\n\n const toVec3 = (p: MercatorCoordinate): vec3 => [p.x, p.y, p.z];\n\n if (eventEnded(\"drag\") && !hasChange(combinedResult)) {\n const preZoom = tr.zoom;\n tr.cameraElevationReference = \"sea\";\n tr.recenterOnTerrain();\n tr.cameraElevationReference = \"ground\";\n // Map zoom might change during the pan operation due to terrain elevation.\n if (preZoom !== tr.zoom) this._map._update(true);\n }\n\n if (!hasChange(combinedResult)) {\n return this._fireEvents(combinedEventsInProgress, deactivatedHandlers, true);\n }\n let {panDelta, zoomDelta, bearingDelta, pitchDelta, around, aroundCoord, pinchAround} = combinedResult;\n\n if (pinchAround !== undefined) {\n around = pinchAround;\n }\n\n if (eventStarted(\"drag\") && around) {\n this._dragOrigin = toVec3(tr.pointCoordinate3D(around));\n // Construct the tracking ellipsoid every time user changes the drag origin.\n // Direction of the ray will define size of the shape and hence defining the available range of movement\n this._trackingEllipsoid.setup(tr._camera.position, this._dragOrigin);\n }\n\n // All movement of the camera is done relative to the sea level\n tr.cameraElevationReference = \"sea\";\n\n // stop any ongoing camera animations (easeTo, flyTo)\n map._stop(true);\n\n around = around || map.transform.centerPoint;\n if (bearingDelta) tr.bearing += bearingDelta;\n if (pitchDelta) tr.pitch += pitchDelta;\n tr._updateCameraState();\n\n // Compute Mercator 3D camera offset based on screenspace panDelta\n const panVec = [0, 0, 0];\n if (panDelta) {\n assert(this._dragOrigin, '_dragOrigin should have been setup with a previous dragstart');\n const startRay = tr.screenPointToMercatorRay(around);\n const endRay = tr.screenPointToMercatorRay(around.sub(panDelta));\n\n const startPoint = this._trackingEllipsoid.projectRay(startRay.dir);\n const endPoint = this._trackingEllipsoid.projectRay(endRay.dir);\n panVec[0] = endPoint[0] - startPoint[0];\n panVec[1] = endPoint[1] - startPoint[1];\n }\n\n const originalZoom = tr.zoom;\n // Compute Mercator 3D camera offset based on screenspace requested ZoomDelta\n const zoomVec = [0, 0, 0];\n if (zoomDelta) {\n // Zoom value has to be computed relative to a secondary map plane that is created from the terrain position below the cursor.\n // This way the zoom interpolation can be kept linear and independent of the (possible) terrain elevation\n const pickedPosition: vec3 = aroundCoord ? toVec3(aroundCoord) : toVec3(tr.pointCoordinate3D(around));\n\n const aroundRay = {dir: vec3.normalize([], vec3.sub([], pickedPosition, tr._camera.position))};\n const centerRay = tr.screenPointToMercatorRay(tr.centerPoint);\n\n if (aroundRay.dir[2] < 0) {\n // Compute center point on the elevated map plane by casting a ray from the center of the screen.\n // ZoomDelta is then subtracted from the relative zoom value and converted to a movement vector\n const pickedAltitude = altitudeFromMercatorZ(pickedPosition[2], pickedPosition[1]);\n const centerOnTargetPlane = tr.rayIntersectionCoordinate(tr.pointRayIntersection(tr.centerPoint, pickedAltitude));\n const movement = tr.zoomDeltaToMovement(toVec3(centerOnTargetPlane), zoomDelta) * (centerRay.dir[2] / aroundRay.dir[2]);\n\n vec3.scale(zoomVec, aroundRay.dir, movement);\n } else if (tr._terrainEnabled()) {\n // Special handling is required if the ray created from the cursor is heading up.\n // This scenario is possible if user is trying to zoom towards e.g. a hill or a mountain.\n // Convert zoomDelta to a movement vector as if the camera would be orbiting around the picked point\n const movement = tr.zoomDeltaToMovement(pickedPosition, zoomDelta);\n vec3.scale(zoomVec, aroundRay.dir, movement);\n }\n }\n\n // Mutate camera state via CameraAPI\n const translation = vec3.add(panVec, panVec, zoomVec);\n tr._translateCameraConstrained(translation);\n\n if (zoomDelta && Math.abs(tr.zoom - originalZoom) > 0.0001) {\n tr.recenterOnTerrain();\n }\n\n tr.cameraElevationReference = \"ground\";\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\nexport default HandlerManager;\n","// @flow\n\nimport {\n bindAll,\n extend,\n warnOnce,\n clamp,\n wrap,\n ease as defaultEasing,\n pick,\n degToRad\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';\nimport MercatorCoordinate, {mercatorZfromAltitude} from '../geo/mercator_coordinate';\nimport {vec3} from 'gl-matrix';\nimport type {FreeCameraOptions} from './free_camera';\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 {Aabb, Frustum} from '../util/primitives.js';\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\nexport type ElevationBoxRaycast = {\n minLngLat: LngLat,\n maxLngLat: LngLat,\n minAltitude: number,\n maxAltitude: number\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 _extendCameraOptions(options?: CameraOptions) {\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 options.padding = extend(defaultPadding, options.padding);\n return 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 eOptions = this._extendCameraOptions(options);\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(-degToRad(bearing));\n const p1rotated = p1world.rotate(-degToRad(bearing));\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 + eOptions.padding.left + eOptions.padding.right)) / size.x;\n const scaleY = (tr.height - (edgePadding.top + edgePadding.bottom + eOptions.padding.top + eOptions.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 const zoom = Math.min(tr.scaleZoom(tr.scale * Math.min(scaleX, scaleY)), eOptions.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 eOptions.offset.x === 'number') ? new Point(eOptions.offset.x, eOptions.offset.y) : Point.convert(eOptions.offset);\n const paddingOffsetX = (eOptions.padding.left - eOptions.padding.right) / 2;\n const paddingOffsetY = (eOptions.padding.top - eOptions.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 * Finds the best camera fit for two given viewport point coordinates.\n * The method will iteratively ray march towards the target and stops\n * when any of the given input points collides with the view frustum.\n * @memberof Map#\n * @param {LngLatLike} p0 First point\n * @param {LngLatLike} p1 Second point\n * @param {number} minAltitude Optional min altitude in meters\n * @param {number} maxAltitude Optional max altitude in meters\n * @param options\n * @param {number | PaddingOptions} [options.padding] The amount of padding in pixels to add to the given bounds.\n * @returns {CameraOptions | void} If map is able to fit to provided bounds, returns `CameraOptions` with\n * `center`, `zoom`, `bearing` and `pitch`. If map is unable to fit, method will warn and return undefined.\n * @private\n */\n _cameraForBox(p0: LngLatLike, p1: LngLatLike, minAltitude?: number, maxAltitude?: number, options?: CameraOptions): void | CameraOptions & AnimationOptions {\n const eOptions = this._extendCameraOptions(options);\n\n minAltitude = minAltitude || 0;\n maxAltitude = maxAltitude || 0;\n\n p0 = LngLat.convert(p0);\n p1 = LngLat.convert(p1);\n\n const tr = this.transform.clone();\n tr.padding = eOptions.padding;\n\n const camera = this.getFreeCameraOptions();\n const focus = new LngLat((p0.lng + p1.lng) * 0.5, (p0.lat + p1.lat) * 0.5);\n const focusAltitude = (minAltitude + maxAltitude) * 0.5;\n\n if (tr._camera.position[2] < mercatorZfromAltitude(focusAltitude, focus.lat)) {\n warnOnce('Map cannot fit within canvas with the given bounds, padding, and/or offset.');\n return;\n }\n\n camera.lookAtPoint(focus);\n\n tr.setFreeCameraOptions(camera);\n\n const coord0 = MercatorCoordinate.fromLngLat(p0);\n const coord1 = MercatorCoordinate.fromLngLat(p1);\n\n const toVec3 = (p: MercatorCoordinate): vec3 => [p.x, p.y, p.z];\n\n const centerIntersectionPoint = tr.pointRayIntersection(tr.centerPoint, focusAltitude);\n const centerIntersectionCoord = toVec3(tr.rayIntersectionCoordinate(centerIntersectionPoint));\n const centerMercatorRay = tr.screenPointToMercatorRay(tr.centerPoint);\n\n const maxMarchingSteps = 10;\n\n let steps = 0;\n let halfDistanceToGround;\n do {\n const z = Math.floor(tr.zoom);\n const z2 = 1 << z;\n\n const minX = Math.min(z2 * coord0.x, z2 * coord1.x);\n const minY = Math.min(z2 * coord0.y, z2 * coord1.y);\n const maxX = Math.max(z2 * coord0.x, z2 * coord1.x);\n const maxY = Math.max(z2 * coord0.y, z2 * coord1.y);\n\n const aabb = new Aabb([minX, minY, minAltitude], [maxX, maxY, maxAltitude]);\n\n const frustum = Frustum.fromInvProjectionMatrix(tr.invProjMatrix, tr.worldSize, z);\n\n // Stop marching when frustum intersection\n // reports any aabb point not fully inside\n if (aabb.intersects(frustum) !== 2) {\n // Went too far, step one iteration back\n if (halfDistanceToGround) {\n tr._camera.position = vec3.scaleAndAdd([], tr._camera.position, centerMercatorRay.dir, -halfDistanceToGround);\n tr._updateStateFromCamera();\n }\n break;\n }\n\n const cameraPositionToGround = vec3.sub([], tr._camera.position, centerIntersectionCoord);\n halfDistanceToGround = 0.5 * vec3.length(cameraPositionToGround);\n\n // March the camera position forward by half the distance to the ground\n tr._camera.position = vec3.scaleAndAdd([], tr._camera.position, centerMercatorRay.dir, halfDistanceToGround);\n try {\n tr._updateStateFromCamera();\n } catch (e) {\n warnOnce('Map cannot fit within canvas with the given bounds, padding, and/or offset.');\n return;\n }\n } while (++steps < maxMarchingSteps);\n\n return {\n center: tr.center,\n zoom: tr.zoom,\n bearing: tr.bearing,\n pitch: tr.pitch\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 _raycastElevationBox(point0: Point, point1: Point): ?ElevationBoxRaycast {\n const elevation = this.transform.elevation;\n\n if (!elevation) return;\n\n const point2 = new Point(point0.x, point1.y);\n const point3 = new Point(point1.x, point0.y);\n\n const r0 = elevation.pointCoordinate(point0);\n if (!r0) return;\n const r1 = elevation.pointCoordinate(point1);\n if (!r1) return;\n const r2 = elevation.pointCoordinate(point2);\n if (!r2) return;\n const r3 = elevation.pointCoordinate(point3);\n if (!r3) return;\n\n const m0 = new MercatorCoordinate(r0[0], r0[1]).toLngLat();\n const m1 = new MercatorCoordinate(r1[0], r1[1]).toLngLat();\n const m2 = new MercatorCoordinate(r2[0], r2[1]).toLngLat();\n const m3 = new MercatorCoordinate(r3[0], r3[1]).toLngLat();\n\n const minLng = Math.min(m0.lng, Math.min(m1.lng, Math.min(m2.lng, m3.lng)));\n const minLat = Math.min(m0.lat, Math.min(m1.lat, Math.min(m2.lat, m3.lat)));\n\n const maxLng = Math.max(m0.lng, Math.max(m1.lng, Math.max(m2.lng, m3.lng)));\n const maxLat = Math.max(m0.lat, Math.max(m1.lat, Math.max(m2.lat, m3.lat)));\n\n const minAltitude = Math.min(r0[3], Math.min(r1[3], Math.min(r2[3], r3[3])));\n const maxAltitude = Math.max(r0[3], Math.max(r1[3], Math.max(r2[3], r3[3])));\n\n const minLngLat = new LngLat(minLng, minLat);\n const maxLngLat = new LngLat(maxLng, maxLat);\n\n return {minLngLat, maxLngLat, minAltitude, maxAltitude};\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. This value is ignored if the map has non-zero pitch.\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 let lngLat0, lngLat1, minAltitude, maxAltitude;\n const point0 = Point.convert(p0);\n const point1 = Point.convert(p1);\n\n const raycast = this._raycastElevationBox(point0, point1);\n\n if (!raycast) {\n if (this.transform.isHorizonVisibleForPoints(point0, point1)) {\n return this;\n }\n\n lngLat0 = this.transform.pointLocation(point0);\n lngLat1 = this.transform.pointLocation(point1);\n } else {\n lngLat0 = raycast.minLngLat;\n lngLat1 = raycast.maxLngLat;\n minAltitude = raycast.minAltitude;\n maxAltitude = raycast.maxAltitude;\n }\n\n if (this.transform.pitch === 0) {\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 return this._fitInternal(\n this._cameraForBox(\n lngLat0,\n lngLat1,\n minAltitude,\n maxAltitude,\n options),\n options, 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 * Returns position and orientation of the camera entity.\n *\n * @memberof Map#\n * @returns {FreeCameraOptions} The camera state\n */\n getFreeCameraOptions(): FreeCameraOptions {\n return this.transform.getFreeCameraOptions();\n }\n\n /**\n * `FreeCameraOptions` provides more direct access to the underlying camera entity.\n * For backwards compatibility the state set using this API must be representable with\n * `CameraOptions` as well. Parameters are clamped into a valid range or discarded as invalid\n * if the conversion to the pitch and bearing presentation is ambiguous. For example orientation\n * can be invalid if it leads to the camera being upside down, the quaternion has zero length,\n * or the pitch is over the maximum pitch limit.\n *\n * @memberof Map#\n * @param {FreeCameraOptions} options `FreeCameraOptions` 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 */\n setFreeCameraOptions(options: FreeCameraOptions, eventData?: Object) {\n this.stop();\n\n const tr = this.transform;\n const prevZoom = tr.zoom;\n const prevPitch = tr.pitch;\n const prevBearing = tr.bearing;\n\n tr.setFreeCameraOptions(options);\n\n const zoomChanged = prevZoom !== tr.zoom;\n const pitchChanged = prevPitch !== tr.pitch;\n const bearingChanged = prevBearing !== tr.bearing;\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 this.fire(new Event('moveend', eventData));\n return this;\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 tr.recenterOnTerrain();\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 this.transform.cameraElevationReference = \"sea\";\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 this.transform.cameraElevationReference = \"ground\";\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. <https://www.win.tue.nl/~vanwijk/zoompan.pdf#page=5>.\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 // w<sub>m</sub>: 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 tr._updateCenterElevation();\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<string>\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<string>} [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<string> = [];\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 const sourceCaches = this._map.style._sourceCaches;\n if (Object.entries(sourceCaches).length === 0) return true;\n for (const id in sourceCaches) {\n const source = sourceCaches[id].getSource();\n if (source.hasOwnProperty('mapbox_logo') && !source.mapbox_logo) {\n return false;\n }\n }\n\n return true;\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<Task>;\n _id: TaskID;\n _cleared: boolean;\n _currentlyRunning: Array<Task> | 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, getMapSessionAPI, postMapLoadEvent, AUTH_ERR_MSG} 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 {supported} 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 TerrainSpecification,\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<string>,\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 optimizeForTerrain?: boolean,\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 = 85;\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 optimizeForTerrain: true,\n renderWorldCopies: true,\n refreshExpiredTiles: true,\n maxTileCacheSize: null,\n localIdeographFontFamily: 'sans-serif',\n localFontFamily: null,\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-85).\n * @param {number} [options.maxPitch=85] The maximum pitch of the map (0-85).\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<string>} [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-85). 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.optimizeForTerrain=true] With terrain on, if `true`, the map will render for performance priority, which may lead to layer reordering allowing to maximize performance (layers that are draped over terrain will be drawn first, including fill, line, background, hillshade and raster). Otherwise, if set to `false`, the map will always be drawn for layer order priority.\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 {string} [options.localFontFamily=false] Defines a CSS\n * font-family for locally overriding generation of all glyphs. Font settings from the map's style will be ignored, except for font-weight keywords (light/regular/medium/bold).\n * If set, this option override the setting in localIdeographFontFamily\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 _showQueryGeometry: ?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 _renderNextFrame: ?boolean;\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 _isInitialLoad: boolean;\n _shouldCheckAccess: boolean;\n _fadeDuration: number;\n _crossSourceCollisions: boolean;\n _crossFadingFactor: number;\n _collectResourceTiming: boolean;\n _optimizeForTerrain: boolean;\n _renderTaskQueue: TaskQueue;\n _controls: Array<IControl>;\n _logoControl: IControl;\n _mapId: number;\n _localIdeographFontFamily: string;\n _localFontFamily: string;\n _requestManager: RequestManager;\n _locale: Object;\n _removed: boolean;\n _speedIndexTiming: 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._isInitialLoad = true;\n this._crossSourceCollisions = options.crossSourceCollisions;\n this._crossFadingFactor = 1;\n this._collectResourceTiming = options.collectResourceTiming;\n this._optimizeForTerrain = options.optimizeForTerrain;\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._localFontFamily = options.localFontFamily;\n this._localIdeographFontFamily = options.localIdeographFontFamily;\n\n if (options.style) this.setStyle(options.style, {localFontFamily: this._localFontFamily, localIdeographFontFamily: this._localIdeographFontFamily});\n\n if (options.attributionControl)\n this.addControl(new AttributionControl({customAttribution: options.customAttribution}));\n\n this._logoControl = new LogoControl();\n this.addControl(this._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 is 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 * const added = map.hasControl(navigation);\n * // added === true\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 dimensions = this._containerDimensions();\n const width = dimensions[0];\n const height = dimensions[1];\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.stop();\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-85).\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 85).\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 * When the map is pitched and `lnglat` is completely behind the camera, there are no pixel\n * coordinates corresponding to that location. In that case,\n * the `x` and `y` components of the returned {@link Point} are set to Number.MAX_VALUE.\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.locationPoint3D(LngLat.convert(lnglat));\n }\n\n /**\n * Returns a {@link LngLat} representing geographical coordinates that correspond\n * to the specified pixel coordinates. If horizon is visible, and specified pixel is\n * above horizon, returns a {@link LngLat} corresponding to point on horizon, nearest\n * to the point.\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.pointLocation3D(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 && 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 && 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 && 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 (optional) The function to be called when the event is fired once.\n * The listener function is called with the data object passed to `fire`,\n * extended with `target` and `type` properties. If the listener is not provided,\n * returns a Promise that will be resolved when the event is fired once.\n * @returns {Map} `this` | Promise\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<PointLike>} [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<string>} [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<Object>} 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 return this.style.queryRenderedFeatures(geometry, 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<Object>} 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<any>, 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, localFontFamily: this._localFontFamily}, options);\n\n if ((options.diff !== false &&\n options.localIdeographFontFamily === this._localIdeographFontFamily &&\n options.localFontFamily === this._localFontFamily) && this.style && style) {\n this._diffStyle(style, options);\n return this;\n } else {\n this._localIdeographFontFamily = options.localIdeographFontFamily;\n this._localFontFamily = options.localFontFamily;\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 delete this.style;\n }\n\n if (style) {\n this.style = new Style(this, options || {});\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 this._updateTerrain();\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 * map.on('load', function() {\n * var styleJson = map.getStyle();\n * });\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 sourceCaches = this.style && this.style._getSourceCaches(id);\n if (sourceCaches.length === 0) {\n this.fire(new ErrorEvent(new Error(`There is no source with ID '${id}'`)));\n return;\n }\n\n return sourceCaches.every(sc => sc.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 this._updateTerrain();\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<StyleImageMetadata> = {}) {\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<string>} 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 terrain property of the style.\n *\n * @param terrain Terrain properties to set. Must conform to the [Mapbox Style Specification](https://docs.mapbox.com/mapbox-gl-js/style-spec/root/#terrain).\n * If `null` or `undefined` is provided, function removes terrain.\n * @returns {Map} `this`\n * @example\n * map.addSource('mapbox-dem', {\n * 'type': 'raster-dem',\n * 'url': 'mapbox://mapbox.mapbox-terrain-dem-v1',\n * 'tileSize': 512,\n * 'maxzoom': 14\n * });\n * // add the DEM source as a terrain layer with exaggerated height\n * map.setTerrain({ 'source': 'mapbox-dem', 'exaggeration': 1.5 });\n */\n setTerrain(terrain: TerrainSpecification) {\n this._lazyInitEmptyStyle();\n this.style.setTerrain(terrain);\n return this._update(true);\n }\n\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 * @returns {Map} The map object.\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 `<canvas>` 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 `<canvas>`, but not from\n * map controls.\n *\n * @returns {HTMLElement} The container of the map's `<canvas>`.\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 `<canvas>` element.\n *\n * @returns {HTMLCanvasElement} The map's `<canvas>` 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({}, supported.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 this.on('data', (event: MapDataEvent) => {\n if (event.dataType === 'source') {\n this.painter.setTileLoadedFlag(true);\n }\n });\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 const m = PerformanceUtils.beginMeasure('render');\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 const fadeDuration = this._isInitialLoad ? 0 : this._fadeDuration;\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,\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._updateTerrain(); // Terrain DEM source updates here and skips update in style._updateSources.\n this.style._updateSources(this.transform);\n }\n\n this._placementDirty = this.style && this.style._updatePlacement(this.painter.transform, this.showCollisionBoxes, fadeDuration, this._crossSourceCollisions);\n\n // Actually draw\n this.painter.render(this.style, {\n showTileBoundaries: this.showTileBoundaries,\n showOverdrawInspector: this._showOverdrawInspector,\n showQueryGeometry: !!this._showQueryGeometry,\n rotating: this.isRotating(),\n zooming: this.isZooming(),\n moving: this.isMoving(),\n fadeDuration,\n isInitialLoad: this._isInitialLoad,\n showPadding: this.showPadding,\n gpuTiming: !!this.listens('gpu-timing-layer'),\n speedIndexTiming: this.speedIndexTiming,\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 PerformanceUtils.endMeasure(m);\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 {\n this._triggerFrame(false);\n if (!this.isMoving() && this.loaded()) {\n this.fire(new Event('idle'));\n if (this._isInitialLoad) {\n this._authenticate();\n }\n this._isInitialLoad = false;\n // check the options to see if need to calculate the speed index\n if (this.speedIndexTiming) {\n const speedIndexNumber = this._calculateSpeedIndex();\n this.fire(new Event('speedindexcompleted', {speedIndex: speedIndexNumber}));\n this.speedIndexTiming = false;\n }\n }\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 /***** START WARNING - REMOVAL OR MODIFICATION OF THE\n * FOLLOWING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******\n * The following code is used to access Mapbox's APIs. Removal or modification\n * of this code can result in higher fees and/or\n * termination of your account with Mapbox.\n *\n * Under the Mapbox Terms of Service, you may not use this code to access Mapbox\n * Mapping APIs other than through Mapbox SDKs.\n *\n * The Mapping APIs documentation is available at https://docs.mapbox.com/api/maps/#maps\n * and the Mapbox Terms of Service are available at https://www.mapbox.com/tos/\n ******************************************************************************/\n\n _authenticate() {\n getMapSessionAPI(this._getMapId(), this._requestManager._skuToken, this._requestManager._customAccessToken, (err) => {\n if (err) {\n // throwing an error here will cause the callback to be called again unnecessarily\n if (err.message === AUTH_ERR_MSG || err.status === 401) {\n console.error('Error: A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/');\n browser.setErrorState();\n const gl = this.painter.context.gl;\n if (this._logoControl instanceof LogoControl) {\n this._logoControl._updateLogo();\n }\n if (gl) gl.clear(gl.DEPTH_BUFFER_BIT | gl.COLOR_BUFFER_BIT | gl.STENCIL_BUFFER_BIT);\n }\n }\n });\n postMapLoadEvent(this._getMapId(), this._requestManager._skuToken, this._requestManager._customAccessToken, () => {});\n }\n\n /***** END WARNING - REMOVAL OR MODIFICATION OF THE\n PRECEDING CODE VIOLATES THE MAPBOX TERMS OF SERVICE ******/\n\n _updateTerrain() {\n // Recalculate if enabled/disabled and calculate elevation cover. As camera is using elevation tiles before\n // render (and deferred update after zoom recalculation), this needs to be called when removing terrain source.\n this.painter.updateTerrain(this.style, this.isMoving() || this.isRotating() || this.isZooming());\n }\n\n _calculateSpeedIndex(): number {\n const finalFrame = this.painter.canvasCopy();\n const canvasCopyInstances = this.painter.getCanvasCopiesAndTimestamps();\n canvasCopyInstances.timeStamps.push(performance.now());\n\n const gl = this.painter.context.gl;\n const framebuffer = gl.createFramebuffer();\n gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);\n\n function read(texture) {\n gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);\n const pixels = new Uint8Array(gl.drawingBufferWidth * gl.drawingBufferHeight * 4);\n gl.readPixels(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels);\n return pixels;\n }\n\n return this._canvasPixelComparison(read(finalFrame), canvasCopyInstances.canvasCopies.map(read), canvasCopyInstances.timeStamps);\n }\n\n _canvasPixelComparison(finalFrame: Uint8Array, allFrames: Uint8Array[], timeStamps: number[]): number {\n let finalScore = timeStamps[1] - timeStamps[0];\n const numPixels = finalFrame.length / 4;\n\n for (let i = 0; i < allFrames.length; i++) {\n const frame = allFrames[i];\n let cnt = 0;\n for (let j = 0; j < frame.length; j += 4) {\n if (frame[j] === finalFrame[j] &&\n frame[j + 1] === finalFrame[j + 1] &&\n frame[j + 2] === finalFrame[j + 2] &&\n frame[j + 3] === finalFrame[j + 3]) {\n cnt = cnt + 1;\n }\n }\n //calculate the % visual completeness\n const interval = timeStamps[i + 2] - timeStamps[i + 1];\n const visualCompletness = cnt / numPixels;\n finalScore += interval * (1 - visualCompletness);\n }\n return finalScore;\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 this._triggerFrame(true);\n }\n\n _triggerFrame(render: boolean) {\n this._renderNextFrame = this._renderNextFrame || render;\n if (this.style && !this._frame) {\n this._frame = browser.frame((paintStartTimeStamp: number) => {\n const isRenderFrame = !!this._renderNextFrame;\n PerformanceUtils.frame(paintStartTimeStamp, isRenderFrame);\n this._frame = null;\n this._renderNextFrame = null;\n if (isRenderFrame) {\n this._render(paintStartTimeStamp);\n }\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 speedindex metric calculation is on or off\n *\n * @private\n * @name speedIndexTiming\n * @type {boolean}\n * @instance\n * @memberof Map\n * @example\n * map.speedIndexTiming = true;\n */\n get speedIndexTiming(): boolean { return !!this._speedIndexTiming; }\n set speedIndexTiming(value: boolean) {\n if (this._speedIndexTiming === value) return;\n this._speedIndexTiming = 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<number>)} 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. Don't shift away if it new position is further from center.\n // This preserves object constancy when the map center is auto-wrapped during animations,\n // but don't allow it to run away on horizon (points towards horizon get closer and closer).\n if (priorPos) {\n const left = new LngLat(lngLat.lng - 360, lngLat.lat);\n const right = new LngLat(lngLat.lng + 360, lngLat.lat);\n // Unless offscreen, keep the marker within same wrap distance to center. This is to prevent\n // running it to infinity `lng` near horizon when bearing is ~90°.\n const withinWrap = Math.ceil(Math.abs(lngLat.lng - transform.center.lng) / 360) * 360;\n const delta = transform.locationPoint(lngLat).distSqr(priorPos);\n const offscreen = priorPos.x < 0 || priorPos.y < 0 || priorPos.x > transform.width || priorPos.y > transform.height;\n if (transform.locationPoint(left).distSqr(priorPos) < delta && (offscreen || Math.abs(left.lng - transform.center.lng) < withinWrap)) {\n lngLat = left;\n } else if (transform.locationPoint(right).distSqr(priorPos) < delta && (offscreen || Math.abs(right.lng - transform.center.lng) < withinWrap)) {\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 _occlusionTimer: ?TimeoutID;\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(\"<h1>Hello World!</h1>\")) // 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(\"<h1>Hello World!</h1>\"))\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(\"<h1>Hello World!</h1>\"))\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 _updateOcclusion() {\n if (!this._occlusionTimer) {\n this._occlusionTimer = setTimeout(this._onOcclusionTimer.bind(this), 60);\n }\n }\n\n _onOcclusionTimer() {\n const tr = this._map.transform;\n const pos = this._pos ? this._pos.sub(this._transformedOffset()) : null;\n if (pos && pos.x >= 0 && pos.x < tr.width && pos.y >= 0 && pos.y < tr.height) {\n // calculate if occluded.\n const raycastLoc = this._map.unproject(pos);\n const camera = this._map.getFreeCameraOptions();\n if (camera.position) {\n const cameraPos = camera.position.toLngLat();\n const raycastDistance = cameraPos.distanceTo(raycastLoc);\n const posDistance = cameraPos.distanceTo(this._lngLat);\n const occluded = raycastDistance < posDistance * 0.9;\n this._element.classList.toggle('mapboxgl-marker-occluded', occluded);\n }\n }\n this._occlusionTimer = null;\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._transformedOffset());\n\n if (this._map.transform.elevation) this._updateOcclusion();\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 * This is initially added to fix the behavior of default symbols only, in order\n * to prevent any regression for custom symbols in client code.\n * @private\n */\n _transformedOffset() {\n if (!this._defaultMarker) return this._offset;\n const tr = this._map.transform;\n const offset = this._offset.mult(this._scale);\n if (this._rotationAlignment === \"map\") offset._rotate(tr.angle);\n if (this._pitchAlignment === \"map\") offset.y *= Math.cos(tr._pitch);\n return offset;\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._transformedOffset());\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}&nbsp;${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 {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(\"<h1>Hello World!</h1>\")\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(\"<h1>Null Island</h1>\")\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(\"<h1>Hello World!</h1>\")\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(\"<p>Hello World!</p>\")\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(\"<h1>Hello World!</h1>\")\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 = '&#215;';\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 {WorkerPerformanceUtils} from './util/worker_performance_utils';\nimport {PerformanceUtils} from './util/performance';\nimport {FreeCameraOptions} from './ui/free_camera';\nimport browser from './util/browser';\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 FreeCameraOptions,\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 * Provides an interface for external module bundlers such as Webpack or Rollup to package\n * mapbox-gl's WebWorker into a separate class and integrate it with the library.\n *\n * Takes precedence over `mapboxgl.workerUrl`.\n *\n * @var {Object} workerClass\n * @returns {Object|null} a Class object, an instance of which exposes the `Worker` interface.\n * @example\n * import mapboxgl from 'mapbox-gl/dist/mapbox-gl-csp.js'\n * import MapboxGLWorker from 'mapbox-gl/dist/mapbox-gl-csp-worker.js'\n *\n * mapboxgl.workerClass = MapboxGLWorker;\n */\n workerClass: null,\n\n /**\n * Sets the time used by GL JS internally for all animations. Useful for generating videos from GL JS.\n * @var {number} time\n */\n setNow: browser.setNow,\n\n /**\n * Restores the internal animation timing to follow regular computer time (`performance.now()`).\n */\n restoreNow: browser.restoreNow\n};\n\n//This gets automatically stripped out in production builds.\nDebug.extend(exported, {isSafari, getPerformanceMetrics: PerformanceUtils.getPerformanceMetrics, getPerformanceMetricsAsync: WorkerPerformanceUtils.getPerformanceMetricsAsync});\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","// @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 ('onwebkitfullscreenchange' in window.document) {\n this._fullscreenchange = 'webkitfullscreenchange';\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).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).webkitFullscreenElement;\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.webkitCancelFullScreen) {\n (window.document: any).webkitCancelFullScreen();\n }\n } else if (this._container.requestFullscreen) {\n this._container.requestFullscreen();\n } else if ((this._container: any).webkitRequestFullscreen) {\n (this._container: any).webkitRequestFullscreen();\n }\n }\n}\n\nexport default FullscreenControl;\n","//\n// Our custom intro provides a specialized \"define()\" function, called by the\n// AMD modules below, that sets up the worker blob URL and then executes the\n// main module, storing its exported value as 'mapboxgl'\n\n// The three \"chunks\" imported here are produced by a first Rollup pass,\n// which outputs them as AMD modules.\n\n// Shared dependencies, i.e.:\n/*\ndefine(['exports'], function (exports) {\n // Code for all common dependencies\n // Each module's exports are attached attached to 'exports' (with\n // names rewritten to avoid collisions, etc.)\n})\n*/\nimport './build/mapboxgl/shared';\n\n// Worker and its unique dependencies, i.e.:\n/*\ndefine(['./shared.js'], function (__shared__js) {\n // Code for worker script and its unique dependencies.\n // Expects the output of 'shared' module to be passed in as an argument,\n // since all references to common deps look like, e.g.,\n // __shared__js.shapeText().\n});\n*/\n// When this wrapper function is passed to our custom define() above,\n// it gets stringified, together with the shared wrapper (using\n// Function.toString()), and the resulting string of code is made into a\n// Blob URL that gets used by the main module to create the web workers.\nimport './build/mapboxgl/worker';\n\n// Main module and its unique dependencies\n/*\ndefine(['./shared.js'], function (__shared__js) {\n // Code for main GL JS module and its unique dependencies.\n // Expects the output of 'shared' module to be passed in as an argument,\n // since all references to common deps look like, e.g.,\n // __shared__js.shapeText().\n //\n // Returns the actual mapboxgl (i.e. src/index.js)\n});\n*/\nimport './build/mapboxgl/index';\n\nexport default mapboxgl;\n"],"names":["UnitBezier","p1x","p1y","p2x","p2y","this","cx","bx","ax","cy","by","ay","prototype","sampleCurveX","t","sampleCurveY","sampleCurveDerivativeX","solveCurveX","x","epsilon","t0","t1","t2","x2","i","Math","abs","d2","solve","module","Point","y","clone","add","p","_add","sub","_sub","multByPoint","_multByPoint","divByPoint","_divByPoint","mult","k","_mult","div","_div","rotate","a","_rotate","rotateAround","_rotateAround","matMult","m","_matMult","unit","_unit","perp","_perp","round","_round","mag","sqrt","equals","other","dist","distSqr","dx","dy","angle","atan2","angleTo","b","angleWith","angleWithSep","cos","sin","convert","Array","isArray","deepEqual","length","Object","keys","key","MAX_SAFE_INTEGER","pow","DEG_TO_RAD","PI","RAD_TO_DEG","degToRad","easeCubicInOut","t3","bezier","ease","clamp","n","min","max","wrap","d","w","asyncAll","array","fn","callback","remaining","results","error","forEach","item","err","result","values","obj","push","extend","dest","src","sources","id","uniqueId","uuid","random","toString","replace","validateUuid","str","test","bindAll","fns","context","bind","endsWith","string","suffix","indexOf","mapObject","input","iterator","output","call","filterObject","map","warnOnceHistory","warnOnce","message","console","warn","isCounterClockwise","c","calculateSignedArea","ring","sum","p1","p2","len","j","isWorker","WorkerGlobalScope","self","parseCacheControl","cacheControl","header","$0","$1","$2","$3","value","toLowerCase","maxAge","parseInt","isNaN","linkEl","reducedMotionQuery","_isSafari","isSafari","scope","userAgent","navigator","safari","match","storageAvailable","type","storage","window","setItem","removeItem","e","stubTime","errorState","exported","now","undefined","performance","setErrorState","setNow","time","restoreNow","frame","cancel","requestAnimationFrame","cancelAnimationFrame","getImageData","img","padding","canvas","document","createElement","getContext","Error","width","height","drawImage","resolveURL","path","href","devicePixelRatio","prefersReducedMotion","matchMedia","matches","mapboxHTTPURLRegex","config","API_URL","API_URL_REGEX","prodMapboxHTTPURLRegex","process","env","RegExp","EVENTS_URL","SESSION_PATH","FEEDBACK_URL","TILE_URL_VERSION","RASTER_URL_PREFIX","REQUIRE_ACCESS_TOKEN","ACCESS_TOKEN","MAX_PARALLEL_IMAGE_REQUESTS","supported","testSupport","gl","webpCheckComplete","webpImgTest","webpImgTestOnloadComplete","testWebpTextureUpload","glForTesting","texture","createTexture","bindTexture","TEXTURE_2D","texImage2D","RGBA","UNSIGNED_BYTE","isContextLost","deleteTexture","onload","onerror","SKU_ID","isMapboxURL","url","isMapboxHTTPURL","urlRe","parseUrl","parts","protocol","authority","params","split","formatUrl","join","parseAccessToken","accessToken","JSON","parse","decodeURIComponent","atob","charCodeAt","slice","TelemetryEvent","constructor","anonId","eventData","queue","pendingRequest","getStorageKey","domain","tokenData","u","btoa","encodeURIComponent","String","fromCharCode","Number","fetchEventData","isLocalStorageAvailable","storageKey","uuidKey","data","localStorage","getItem","saveEventData","stringify","processRequests","_","postEvent","timestamp","additionalPayload","customAccessToken","eventsUrlObject","payload","event","created","Date","toISOString","sdkIdentifier","skuId","userId","finalPayload","request","headers","Content-Type","body","postData","queueRequest","turnstileEvent_","super","_customAccessToken","postTurnstileEvent","tileUrls","some","lastSuccess","tokenU","dueForEvent","nextUpdate","shift","lastUpdate","nextDate","daysElapsed","getDate","enabled.telemetry","mapLoadEvent_","success","skuToken","postMapLoadEvent","mapId","errorCb","mapSessionAPI_","getSession","token","authUrlObject","getData","getSessionAPI","getMapSessionAPI","sharedCache","responseConstructorSupportsReadableStream","cacheLimit","cacheCheckThreshold","cacheOpen","caches","open","stripQueryParameters","start","supportsOffscreenCanvas","globalEntryCounter","Infinity","offscreenCanvasSupported","OffscreenCanvas","createImageBitmap","ResourceType","Unknown","Style","Source","Tile","Glyphs","SpriteImage","SpriteJSON","Image","freeze","AJAXError","status","name","getReferrer","worker","referrer","location","parent","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","options","Headers","v","get","toUTCString","getTime","Response","ReadableStream","blob","prepareBody","clonedResponse","cache","put","cachePut","strippedURL","fresh","expires","isFresh","delete","cacheGet","abort","makeFetchRequest","actor","send","xhr","XMLHttpRequest","responseType","setRequestHeader","withCredentials","getResponseHeader","makeXMLHttpRequest","getArrayBuffer","sameOrigin","host","transparentPngUrl","imageQueue","numImageRequests","getImage","webpSupported","accept","queued","cancelled","advanced","advanceImageRequestQueue","Blob","Uint8Array","imgBitmap","arrayBufferToImageBitmap","URL","revokeObjectURL","byteLength","createObjectURL","arrayBufferToImage","_addEventListener","listener","listenerList","_removeEventListener","index","splice","Event","ErrorEvent","Evented","on","_listeners","off","_oneTimeListeners","once","Promise","resolve","fire","properties","listens","target","listeners","oneTimeListeners","_eventedParent","_eventedParentData","setEventedParent","ValidationError","identifier","__line__","line","validateConstants","constants","inputs","unbundle","Boolean","valueOf","deepUnbundle","unbundledValue","ParsingError","Scope","bindings","expression","concat","has","NullType","kind","NumberType","StringType","BooleanType","ColorType","ObjectType","ValueType","CollatorType","FormattedType","ResolvedImageType","itemType","N","valueMemberTypes","checkSubtype","expected","memberType","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","exports","css_str","iv","substr","op","ep","fname","alpha","pop","s","l","Color","r","g","[object Object]","rgba","parseCSSColor","toArray","Collator","caseSensitive","diacriticSensitive","locale","sensitivity","collator","Intl","usage","compare","lhs","rhs","resolvedLocale","resolvedOptions","FormattedSection","image","scale","fontStack","textColor","Formatted","sections","unformatted","isEmpty","section","fromString","serialize","serialized","ResolvedImage","available","validateRGBA","isValue","mixed","typeOf","Literal","args","expectedType","evaluate","eachChild","outputDefined","RuntimeError","toJSON","types","number","boolean","object","Assertion","floor","parsed","ctx","every","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","canonical","geometryType","geometry","canonicalID","cached","CompoundExpression","_evaluate","definition","definitions","availableOverloads","overloads","filter","signature","signatureContext","ParsingContext","registry","parsedArgs","argParseFailed","errors","signatures","stringifySignature","actualTypes","CollatorExpression","updateBBox","bbox","coord","boxWithinBox","bbox1","bbox2","getTileCoordinates","log","tilesAtZoom","z","onBoundary","x1","y1","y2","pointWithinPolygon","point","rings","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","points","getTileLines","lineBBox","tileLines","tileLine","Within","geojson","geometries","features","polygonGeometry","tilePolygon","tilePolygons","pointsWithinPolygons","linesWithinPolygons","isFeatureConstant","isStateConstant","isGlobalPropertyConstant","Var","boundExpression","part","expr","_parse","annotate","typeAnnotation","Expr","actual","isConstant","isTypeAnnotation","childrenConstant","ec","findStopLessThanOrEqualTo","stops","lastIndex","currentValue","nextValue","lowerIndex","upperIndex","currentIndex","Step","labels","outputs","label","outputType","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","lower","upper","exponentialInterpolation","base","controlPoints","rest","interpolationFactor","outputLower","outputUpper","lowerValue","upperValue","difference","progress","Coalesce","needsAnnotation","requestedImageName","argCount","Let","binding","At","In","needle","haystack","IndexOf","fromIndex","Match","inputType","cases","otherwise","labelContext","sortedLabels","sort","groupedByOutput","outputLookup","outputIndex","coerceLabel","Case","branches","Slice","beginIndex","endIndex","isComparableType","eqCollate","makeComparison","compareBasic","compareWithCollator","isOrderComparison","Comparison","hasUntypedArgument","lt","rt","Equals","NotEquals","LessThan","GreaterThan","LessThanOrEqual","NumberFormat","currency","minFractionDigits","maxFractionDigits","style","minimumFractionDigits","maximumFractionDigits","format","Length","expressions","==","!=",">","<",">=","<=","at","case","coalesce","in","index-of","interpolate-hcl","interpolate-lab","let","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","register","typeof","typeToString","to-rgba","rgb","feature-state","geometry-type","zoom","heatmap-density","heatmapDensity","line-progress","lineProgress","sky-radial-progress","skyRadialProgress","accumulated","+","*","-","/","%","ln2","LN2","pi","E","^","log10","LN10","ln","log2","asin","acos","atan","ceil","filter-==","filter-id-==","filter-type-==","filter-<","filter-id-<","filter->","filter-id->","filter-<=","filter-id-<=","filter->=","filter-id->=","filter-has","filter-has-id","filter-type-in","filter-id-in","filter-in-small","filter-in-large","binarySearch","all","any","!","is-supported-script","isSupportedScript","upcase","toUpperCase","downcase","resolved-locale","StyleExpression","_warningHistory","_evaluator","_defaultValue","getDefaultValue","_enumValues","evaluateWithoutErrorHandling","isExpression","createExpression","parser","color","enum","formatted","resolvedImage","getExpectedType","ZoomConstantExpression","_styleExpression","isStateDependent","ZoomDependentExpression","zoomStops","interpolationType","createPropertyExpression","isZoomConstant","zoomCurve","findZoomCurve","childResult","StylePropertyFunction","specification","_parameters","_specification","createFunction","isColor","zoomAndFeatureDependent","zoomDependent","property","innerFun","categoricalKeyType","create","featureFunctions","featureFunctionStops","validateObject","elementSpecs","valueSpec","elementValidators","objectElementValidators","styleSpec","objectKey","elementSpecKey","elementSpec","validateElement","validateSpec","required","validateArray","arraySpec","validateArrayElement","arrayElementValidator","validate","arrayElementSpec","minimum","maximum","$version","function","arrayIndex","validateNumber","specMin","specMax","validateFunction","functionValueSpec","functionType","stopKeyType","previousStopDomainValue","previousStopDomainZoom","stopDomainValues","isZoomFunction","isPropertyFunction","isZoomAndPropertyFunction","validateFunctionStop","validateStopDomainValue","reportValue","isFinite","validateExpression","expressionContext","expressionObj","propertyKey","propertyType","validateEnum","isExpressionFilter","filterSpec","transition","property-type","createFilter","needGeometry","convertFilter","compiled","globalProperties","geometryNeeded","convertComparisonOp","convertNegation","filters","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","mapExpr","reduceExpr","source_video","source_image","validateLight","light","lightSpec","rootType","validateTerrain","terrain","terrainSpec","VALIDATORS","validateStyleMin","latestStyleSpec","$root","validateGlyphsURL","sortErrors","wrapCleanErrors","inner","paintProperty","layoutProperty","validateStyle","emitValidationErrors","emitter","hasErrors","GridIndex","extent","cells","ArrayBuffer","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","ImageData","ImageBitmap","klass","defineProperty","writeable","omit","shallow","Grid","grid","transferables","deserialize","_classRegistryKey","isArrayBuffer","isImageBitmap","isView","view","$name","ZoomHistory","first","update","floorZ","lastIntegerZoom","lastIntegerZoomTime","lastZoom","lastFloorZoom","unicodeBlockLookup","char","allowsVerticalWritingMode","chars","charHasUprightVerticalOrientation","allowsLetterSpacing","charAllowsLetterSpacing","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","defaultTransitioningPropertyValues","PossiblyEvaluated","hasTransition","Layout","defaultPropertyValues","PossiblyEvaluatedPropertyValue","constantOr","defaultPossiblyEvaluatedValues","DataConstantProperty","DataDrivenProperty","overrides","CrossFadedDataDrivenProperty","evaluatedValue","constantValue","_calculate","cameraVal","mid","CrossFadedProperty","ColorRampProperty","Properties","overridableProperties","overridable","defaultPropertyValue","defaultTransitionablePropertyValue","packUint8ToFloat","viewTypes","Int8","Int8Array","Uint8","Int16","Int16Array","Uint16","Uint16Array","Int32","Uint32","Uint32Array","Float32","Float32Array","Struct","structArray","_structArray","_pos1","size","_pos2","_pos4","_pos8","StructArray","isTransferred","capacity","resize","_trim","bytesPerElement","_refreshViews","clear","reserve","oldUint8Array","uint8","createLayout","members","alignment","maxSize","member","typeSize","BYTES_PER_ELEMENT","memberOffset","align","components","StructArrayLayout2i4","int16","emplaceBack","v0","emplace","o2","StructArrayLayout4i8","v3","StructArrayLayout2i4ub1f12","float32","v4","v5","v6","o1","o4","StructArrayLayout2f8","StructArrayLayout10ui20","uint16","v7","v8","v9","StructArrayLayout4i4ui4i24","v10","v11","StructArrayLayout3f12","StructArrayLayout1ul4","uint32","StructArrayLayout2i4f1i1ul2ui32","StructArrayLayout2i2i2i12","StructArrayLayout2f1f2i16","StructArrayLayout2ub2f12","StructArrayLayout3ui6","StructArrayLayout2i2ui3ul3ui2f3ub1ul1i48","v12","v13","v14","v15","v16","StructArrayLayout8i15ui1ul4f68","v17","v18","v19","v20","v21","v22","v23","v24","v25","v26","v27","StructArrayLayout1f4","StructArrayLayout3i6","StructArrayLayout1ul3ui12","StructArrayLayout2ui4","StructArrayLayout1ui2","StructArrayLayout4f16","CollisionBoxStruct","anchorPointX","anchorPointY","featureIndex","sourceLayerIndex","bucketIndex","anchorPoint","CollisionBoxArray","PlacedSymbolStruct","anchorX","anchorY","glyphStartIndex","numGlyphs","vertexStartIndex","lineStartIndex","lineLength","segment","lowerSize","upperSize","lineOffsetX","lineOffsetY","writingMode","placedOrientation","hidden","crossTileID","associatedIconIndex","PlacedSymbolArray","SymbolInstanceStruct","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","layoutVertexArrayOffset","FeatureIndexArray","FillExtrusionCentroidStruct","a_centroid_pos0","a_centroid_pos1","FillExtrusionCentroidArray","patternAttributes","seed","remainder","bytes","h1","h1b","c1","c2","k1","murmur3","murmur2","FeaturePositionMap","ids","positions","indexed","getNumericId","getPositions","intId","Float64Array","left","right","pivot","swap","numValue","arr","tmp","Uniform","Uniform1f","current","uniform1f","Uniform4f","uniform4f","UniformColor","emptyMat4","emptyMat3","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","destroy","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","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","StyleLayer","_featureFilter","metadata","minzoom","maxzoom","sourceLayer","_unevaluatedLayout","_transitionablePaint","setPaintProperty","setLayoutProperty","_transitioningPaint","_crossfadeParameters","getLayoutProperty","visibility","_validate","getPaintProperty","transitionable","isCrossFadedProperty","wasDataDriven","oldValue","_handleSpecialPaintPropertyUpdate","newValue","_handleOverridablePaintPropertyUpdate","getProgramIds","getProgramConfiguration","isHidden","updateTransitions","recalculate","source-layer","sprite","is3D","isSky","isTileClipped","hasOffscreenPass","SegmentVector","segments","prepareSegment","numVertices","layoutVertexArray","indexArray","sortKey","MAX_VERTEX_ARRAY_LENGTH","vertexLength","vertexOffset","primitiveOffset","primitiveLength","vaos","MAX","BITS","MIN","loadGeometry","toEvaluationFeature","addCircleVertex","extrudeX","extrudeY","CircleBucket","overscaling","layerIds","hasPattern","CircleLayoutArray","TriangleIndexArray","stateDependentLayerIds","populate","styleLayer","bucketFeatures","circleSortKey","evaluationFeature","bucketFeature","addFeature","states","stateDependentLayers","uploadPending","uploaded","layoutVertexBuffer","layoutAttributes","indexBuffer","createIndexBuffer","polygonIntersectsPolygon","polygonA","polygonB","polygonContainsPoint","lineIntersectsLine","polygonIntersectsBufferedPoint","radius","pointIntersectsBufferedLine","polygonIntersectsMultiPolygon","multiPolygon","multiPolygonContainsPoint","lineIntersectsBufferedLine","lineA","lineB","a0","a1","lineSegmentIntersectsLineSegment","b0","b1","radiusSquared","distToSegmentSquared","l2","polygonIntersectsBox","boxX1","boxY1","boxX2","boxY2","corners","corner","edgeIntersectsBox","e1","e2","dir","getMaximumPaintValue","bucket","translateDistance","translate","queryGeometry","translateAnchor","bearing","pixelsToTileUnits","pt","translated","tilespaceTranslate","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","multiply","a00","a01","a02","a03","a10","a11","a12","a13","a20","a21","a22","a23","a30","a31","a32","a33","b2","b3","hypot","arguments","mul","fromValues","subtract","scaleAndAdd","normalize","dot","cross","az","bz","transformMat4","transformQuat","q","qx","qy","qz","uvx","uvy","uvz","uuvx","uuvy","uuvz","w2","rotateX","rad","aw","bw","vec3","mat3","Frustum","points_","planes_","planes","invProj","frustumCoords","vec4","frustumPlanes","Aabb","min_","max_","center","quadrant","qMin","qMax","axis","distanceX","distanceY","distanceZ","intersects","frustum","aabbPoints","fullyInside","plane","pointsInside","projMin","MAX_VALUE","projMax","projectedPoint","projectPoint","pixelPosMatrix","origin","up","intersectAtHeight","intersectionPt","intersectsPlane","HeatmapBucket","createImage","channels","Uint8ClampedArray","RangeError","resizeImage","newImage","copyImage","srcImg","dstImg","srcPt","dstPt","srcData","dstData","srcOffset","dstOffset","AlphaImage","RGBAImage","copy","heatmap-radius","heatmap-weight","heatmap-intensity","heatmap-color","heatmap-opacity","renderColorRamp","evaluationGlobals","resolution","clips","renderPixel","stride","evaluationKey","pxColor","clip","hillshade-illumination-direction","hillshade-illumination-anchor","hillshade-exaggeration","hillshade-shadow-color","hillshade-highlight-color","hillshade-accent-color","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","tail","numMerges","pSize","qSize","inSize","sortLinked","indexCurve","isEarHashed","isEar","cureLocalIntersections","splitEarcut","pointInTriangle","maxTX","maxTY","minZ","maxZ","locallyInside","isValidDiagonal","splitPolygon","hole","hx","hy","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","fillExtrusionAttributes","centroidAttributes","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","nxRatio","nySign","normalUp","top","PartMetadata","acc","polyCount","startRing","currentPolyCount","edges","append","checkBorders","borders","processBorderOverlap","checkBorderIntersection","addBorderIntersection","centroid","count","reduce","span","intersectsCount","FillExtrusionBucket","FillExtrusionLayoutArray","centroidVertexArray","enableTerrain","featuresOnBorder","borderDone","tileToMeter","circumferenceAtEquator","vertexArrayOffset","sortBorders","uploadCentroid","centroidVertexBuffer","needsCentroidUpdate","edgeDistance","isBoundaryEdge","bottomRight","encodeCentroid","polyInfo","fill-extrusion-opacity","fill-extrusion-color","fill-extrusion-translate","fill-extrusion-translate-anchor","fill-extrusion-height","fill-extrusion-base","fill-extrusion-vertical-gradient","getIntersectionDistance","projectedQueryGeometry","projectedFace","ab","ac","ap","dotABAB","dotABAC","dotACAC","dotAPAB","dotAPAC","denom","distance","closestDistance","toPoint","getTerrainHeightOffset","zBase","zTop","demSampler","exaggeration","lat","ele","getElevationAt","flatRoof","centroidElevation","posX","posY","spanX","spanY","meterToDEM","getMeterToDEM","wX","wY","posPx","tileCoordToPixel","offsetX","offsetY","getElevationAtPixel","fourSample","diffX","diffY","diffSumY","slopeX","slopeY","flatElevation","lineLayoutAttributes","lineLayoutAttributesExt","COS_HALF_SHARP_CORNER","LineBucket","lineClipsArray","gradients","LineLayoutArray","layoutVertexArray2","LineExtLayoutArray","maxLineLength","lineSortKey","patternBucketFeature","layoutVertexBuffer2","layoutAttributesExt","lineFeatureClips","cap","miterLimit","roundLimit","lineClips","addLine","scaledDistance","totalDistance","lineSoFar","updateScaledDistance","isPolygon","sharpCornerOffset","SHARP_CORNER_OFFSET","currentVertex","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","totalFeatureLength","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","getLineWidth","lineWidth","lineGapWidth","symbolLayoutAttributes","dynamicLayoutAttributes","collisionVertexAttributes","collisionVertexAttributesExt","collisionBoxLayout","collisionCircleLayout","getSizeData","tileZoom","layoutSize","minZoom","maxZoom","minSize","evaluateSizeForFeature","sizeData","uSize","uSizeT","evaluateSizeForZoom","transform","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","bitmap","advance","readGlyph","metrics","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","textOptions","imageOptions","TaggedString","sectionIndex","imageSectionID","defaultFontStack","addImageSection","addTextSection","getSection","getSectionIndex","getCharCode","verticalizePunctuation","nextCharCode","prevCharCode","trim","beginningWhitespace","whitespace","trailingWhitespace","substring","getMaxScale","forText","nextImageSectionCharCode","getNextImageSectionCharCode","forImage","shapeText","glyphMap","glyphPositions","lineHeight","textAnchor","textJustify","spacing","allowVerticalPlacement","symbolPlacement","layoutTextSize","layoutTextSizeThisZoom","logicalInput","fromFeature","untaggedLines","determineLineBreaks","taggedLine","processedLines","lineBreakPoints","lineBreak","breakLines","positionedLines","shaping","bottom","iconsInText","verticalizable","maxLineHeight","justify","lineMaxScale","maxLineOffset","positionedLine","positionedGlyphs","lineOffset","codePoint","baselineOffset","rect","verticalAdvance","imagePosition","localGlyph","glyphPosition","justifyLine","currentLineHeight","horizontalAlign","verticalAlign","getAnchorAlignment","blockHeight","lineCount","shiftX","shiftY","positionedGlyph","shapeLines","9","10","11","12","13","32","breakable","38","40","41","43","45","47","173","183","8203","8208","8211","8231","getGlyphAdvance","calculateBadness","targetWidth","penalty","isLastBreak","raggedness","calculatePenalty","nextCodePoint","penalizableIdeographicBreak","evaluateBreak","breakIndex","breakX","potentialBreaks","bestPriorBreak","bestBreakBadness","potentialBreak","breakBadness","badness","priorBreak","potentialLineBreaks","totalWidth","determineAverageLineWidth","hasServerSuggestedBreakpoints","currentX","ideographicBreak","leastBadBreaks","lastLineBreak","anchor","lastPositionedGlyph","lineIndent","shapeIcon","iconOffset","iconAnchor","fitIconToText","shapedIcon","shapedText","textFit","fontScale","collisionPadding","textLeft","textRight","textTop","textBottom","Anchor","checkMaxAngle","labelLength","windowSize","maxAngle","anchorDistance","recentCorners","recentAngleDelta","angleDelta","getLineLength","getAngleWindowSize","glyphSize","boxScale","getShapedLabelLength","getCenterAnchor","angleWindowSize","prevDistance","centerDistance","segmentDistance","getAnchors","tileExtent","shapedLabelLength","isLineContinued","resample","placeAtMiddle","halfLabelLength","markedDistance","anchors","segmentDist","clipLine","clippedLines","clippedLine","p0","TinySDF","INF","fontSize","cutoff","fontFamily","fontWeight","gridSize","textBaseline","textAlign","fillStyle","gridOuter","gridInner","middle","edt","edt1d","_draw","getMetrics","glyphWidth","glyphHeight","imgTop","imgLeft","imgData","textMetrics","measureText","doubleBuffer","actualBoundingBoxLeft","actualBoundingBoxAscent","actualBoundingBoxRight","actualBoundingBoxDescent","clearRect","fillText","alphaChannel","prepareGrids","extractAlpha","sdfWidth","sdfHeight","fontAscent","fontBoundingBoxAscent","draw","drawWithMetrics","LocalGlyphMode","none","ideographs","GlyphManager","requestManager","localGlyphMode","localFontFamily","entries","localGlyphs","200","400","500","900","setURL","getGlyphs","stack","entry","requests","ranges","_tinySDF","range","loadGlyphRange","_doesCharSupportLocalGlyph","cb","family","tinySDF","baselineAdjustment","getIconQuads","iconRotate","isSDFIcon","hasIconTextFit","quads","imageWidth","imageHeight","iconWidth","iconHeight","reduceRanges","stretchWidth","stretchHeight","fixedWidth","fixedHeight","stretchOffsetX","stretchContentWidth","stretchOffsetY","stretchContentHeight","fixedOffsetX","fixedContentWidth","fixedOffsetY","fixedContentHeight","sumWithinRange","makeBox","leftEm","getEmOffset","stretch","leftPx","getPxOffset","fixed","topEm","topPx","rightEm","rightPx","bottomEm","bottomPx","tr","bl","pixelOffsetTL","pixelOffsetBR","matrix","tex","glyphOffset","minFontScaleX","minFontScaleY","isSDF","xCuts","stretchZonesToCuts","yCuts","xi","yi","stretchZones","fixedSize","stretchSize","cuts","stretchOffset","iconSize","fixedOffset","fontstack","urlTemplate","transformRequest","normalizeGlyphsURL","Protobuf","parseGlyphPBF","TinyQueue","_down","_up","peek","halfLength","best","polygonRings","precision","debug","outerRing","cellSize","cellQueue","Queue","compareMax","Cell","bestCell","getCentroidCell","numProbes","minDistSq","pointToPolygonDist","SQRT2","INVALID_TEXT_OFFSET","POSITIVE_INFINITY","evaluateVariableOffset","fromTextOffset","radialOffset","hypotenuse","fromRadialOffset","performSymbolLayout","imageMap","showCollisionBoxes","createArrays","tilePixelRatio","compareText","iconsNeedLinear","unevaluatedLayoutValues","sizes","textSizeData","compositeTextSizes","iconSizeData","compositeIconSizes","layoutIconSize","textMaxSize","textAlongLine","keepUpright","textSize","shapedTextOrientations","textOffset","unformattedText","spacingIfAllowed","variableTextAnchor","addVerticalShapingForPointLabelIfNeeded","justifications","getAnchorJustification","singleLine","justification","icon","sdf","sdfIcons","getDefaultHorizontalShaping","generateCollisionDebugBuffers","collisionBoxArray","defaultHorizontalShaping","textMaxBoxScale","symbolMinDistance","textPadding","iconPadding","textMaxAngle","iconAlongLine","textRepeatDistance","iconTextFit","verticallyShapedIcon","addSymbolAtAnchor","iconBoxScale","lineArray","addToLineVertexArray","textBoxIndex","iconBoxIndex","verticalTextBoxIndex","verticalIconBoxIndex","textCircle","verticalTextCircle","verticalIconCircle","placedTextSymbolIndices","verticalShaping","evaluateCircleCollisionFeature","verticalTextRotation","evaluateBoxCollisionFeature","iconQuads","verticalIconQuads","MAX_GLYPH_ICON_SIZE","addSymbols","placedSymbolArray","addTextVertices","getCollisionCircleHeight","diameter","prevHeight","glyphOffsetArray","SymbolBucket","MAX_GLYPHS","addToSortKeyRanges","symbolInstances","addSymbol","anchorIsTooClose","poi","findPoleOfInaccessibility","placementTypes","placedIconIndex","glyphQuads","alongLine","textRotate","textureRect","rectBuffer","GLYPH_PBF_BORDER","rotateVerticalGlyph","halfAdvance","scaledGlyphOffset","imageOffset","builtInOffset","verticalizedLabelOffset","verticalRotation","xHalfWidthOffsetCorrection","ONE_EM","halfWidthOffsetCorrection","verticalOffsetCorrection","getGlyphQuads","placementType","horizontalShaping","shaped","rotateRadians","repeatDistance","otherAnchors","shaderOpacityAttributes","ox","oy","tx","ty","sizeVertex","pixelOffsetX","pixelOffsetY","aSizeX","aSizeY","addDynamicAttributes","dynamicLayoutVertexArray","containsRTLText","formattedText","SymbolBuffers","SymbolLayoutArray","SymbolDynamicLayoutArray","opacityVertexArray","SymbolOpacityArray","dynamicIndexBuffer","dynamicLayoutVertexBuffer","opacityVertexBuffer","itemSize","CollisionBuffers","LayoutArray","IndexArray","collisionVertexArray","CollisionVertexArray","collisionVertexArrayExt","CollisionVertexExtArray","collisionVertexBuffer","collisionVertexBufferExt","hasRTLText","sortKeyRanges","collisionCircleArray","placementInvProjMatrix","mat4","placementViewportMatrix","canOverlap","sortFeaturesByKey","sortFeaturesByY","writingModes","wm","sourceID","lineVertexArray","calculateGlyphDependencies","doesAllowVerticalWritingMode","verticalChar","charAt","textFont","textField","iconImage","hasText","hasIcon","symbolSortKey","iconDependencies","stacks","glyphDependencies","resolvedTokens","getValueAndResolveTokens","factory","globalRTLTextPlugin","sectionFont","sectionStack","leftIndex","rightIndex","mergedFeatures","mergedIndex","mergeFromRight","leftKey","rightKey","geom","mergeFromLeft","getKey","onRight","mergeLines","hasDebugData","textCollisionBox","iconCollisionBox","destroyDebugData","sumForwardLength","sumBackwardLength","tileUnitDistanceFromAnchor","vertex","arrays","labelAnchor","glyphOffsetArrayStart","_commitLayoutVertex","_addCollisionDebugVertices","boxAnchorPoint","symbolInstance","_addTextDebugCollisionBoxes","startIndex","instance","getSymbolInstanceTextSize","_addIconDebugCollisionBoxes","getSymbolInstanceIconSize","CollisionBoxLayoutArray","symbolSize","boxIndex","symbol","featureSize","_commitDebugCollisionVertexUpdate","_updateTextDebugCollisionBoxes","_updateIconDebugCollisionBoxes","updateCollisionDebugBuffers","hasTextCollisionBoxData","hasIconCollisionBoxData","_deserializeCollisionBoxesForSymbol","textStartIndex","textEndIndex","verticalTextStartIndex","verticalTextEndIndex","iconStartIndex","iconEndIndex","verticalIconStartIndex","verticalIconEndIndex","collisionArrays","textBox","textFeatureIndex","verticalTextBox","verticalTextFeatureIndex","iconBox","iconFeatureIndex","verticalIconBox","verticalIconFeatureIndex","deserializeCollisionBoxes","hasTextData","hasIconData","addIndicesForPlacedSymbol","iconOrText","placedSymbolIndex","placedSymbol","vertexIndex","getSortedSymbolIndexes","sortedAngle","symbolInstanceIndexes","rotatedYs","featureIndexes","aIndex","bIndex","symbolInstanceIndex","symbolInstanceEnd","symbolInstanceStart","sortFeatures","featureSortOrder","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","createBucket","queryRadius","queryIntersectsFeature","hasPaintOverride","overriden","override","styleExpression","_interpolationType","propertyName","hasOverrides","checkSections","checkExpression","background-color","background-pattern","background-opacity","raster-opacity","raster-hue-rotate","raster-brightness-min","raster-brightness-max","raster-saturation","raster-contrast","raster-resampling","raster-fade-duration","CustomStyleLayer","implementation","renderingMode","prerender","onAdd","painter","onRemove","sky-type","sky-atmosphere-sun","sky-atmosphere-sun-intensity","sky-gradient-center","sky-gradient-radius","sky-gradient","sky-atmosphere-halo-color","sky-atmosphere-color","sky-opacity","getCelestialDirection","azimuth","altitude","leftHanded","rotation","quat","subclasses","circleBucket","elevationHelper","alignWithMap","isAboveHorizon","translation","pixelToTileUnitsFactor","transformedSize","translatedPoint","elevation","transformedPoint","transformedPolygon","tilespaceRays","screenGeometry","adjustedSize","projectedCenter","cameraToCenterDistance","_updateColorRamp","colorRamp","colorRampTexture","heatmapFbo","pattern","outlineColor","tilespaceGeometry","fill-extrusion","terrainVisible","tile","getBucket","centroidOffset","centroidVertexObject","projected","projectedBase","projectedTop","ringBase","ringTop","heightOffset","projectExtrusion3D","baseXZ","baseYZ","baseZZ","baseWZ","topXZ","topYZ","topZZ","topWZ","sX","sY","sZ","sW","baseZ","baseW","topX","topY","topZ","topW","projectExtrusion2D","projectExtrusion","screenQuery","topA","face","checkIntersection","isPointQuery","screenBounds","gradientVersion","stepInterpolant","gradientExpression","dasharray","gradient","lineBucket","translatedPolygon","halfWidth","newRings","zero","newRing","aToB","bToC","offsetLine","multiLine","polygonIntersectsBufferedMultiLine","_skyboxInvalidated","needsSkyboxCapture","skyboxTexture","skyboxGeometry","lightPosition","_lightPosition","azimuthal","polar","getCenter","sunPosition","useLightPosition","direction","markSkyboxValid","HTMLImageElement","HTMLCanvasElement","HTMLVideoElement","Texture","useMipmap","pixelStoreUnpackFlipY","pixelStoreUnpack","pixelStoreUnpackPremultiplyAlpha","premultiply","texSubImage2D","isSizePowerOfTwo","generateMipmap","minFilter","LINEAR_MIPMAP_NEAREST","LINEAR","texParameteri","TEXTURE_MAG_FILTER","TEXTURE_MIN_FILTER","TEXTURE_WRAP_S","TEXTURE_WRAP_T","ThrottledInvoker","_callback","_triggered","MessageChannel","_channel","port2","onmessage","trigger","port1","postMessage","setTimeout","remove","RequestPerformance","_marks","measure","mark","resourceTimingData","getEntriesByName","clearMarks","clearMeasures","Scheduler","tasks","taskQueue","invoker","nextId","priority","getPriority","pick","task","minIndex","minPriority","isSymbolTile","LngLatBounds","sw","ne","setSouthWest","setNorthEast","_ne","LngLat","lng","_sw","sw2","ne2","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","latFromMercatorY","altitudeFromMercatorZ","MercatorCoordinate","lngLatLike","toLngLat","toAltitude","meterInMercatorCoordinateUnits","getMercCoords","CanonicalTileID","calculateKey","urls","scheme","quadkey","mask","getQuadkey","getTilePoint","getTileVec3","UnwrappedTileID","OverscaledTileID","overscaledZ","scaledTo","targetZ","zDifference","calculateScaledKey","withWrap","isChildOf","children","sourceMaxZoom","isLessThan","wrapped","unwrapTo","overscaleFactor","toUnwrapped","xy","DictionaryCoder","strings","_stringToNumber","_numberToString","encode","Feature","vectorTileFeature","_vectorTileFeature","_z","_x","_y","tileID","uses","tileSize","buckets","expirationTime","queryPadding","hasSymbolBuckets","dependencies","expiredRequestCount","registerFadeDuration","fadeEndTime","timeAdded","browser","wasRequested","loadVectorData","justReloaded","hasData","unloadVectorData","latestFeatureIndex","rawTileData","latestRawTileData","getLayer","lId","deserializeBucket","imageAtlas","glyphAtlasImage","imageAtlasTexture","glyphAtlasTexture","ALPHA","prepare","queryRenderedFeatures","serializedLayers","sourceFeatureState","tileResult","visualizeQueryGeometry","querySourceFeatures","vtLayers","loadVTLayers","_geojsonTileLayer","featureFilter","getId","geojsonFeature","GeoJSONFeature","patternsLoaded","setExpiryData","parsedCC","isExpired","delta","getExpiryTimeout","setFeatureState","hasLayer","sourceLayerId","sourceLayerStates","holdingForFade","symbolFadeHoldUntil","symbolFadeFinished","clearFadeHold","setHoldDuration","setDependencies","namespace","dep","hasDependency","namespaces","clearQueryDebugViz","SourceFeatureState","stateChanges","deletedStates","updateState","featureId","newState","ft","removeFeatureState","getState","reconciledState","featureDeletions","initializeTileState","coalesceChanges","tiles","featuresChanged","layerStates","MipLevel","size_","minimums","maximums","leaves","getElevation","idx","toIdx","isLeaf","aabbRayIntersect","tMin","tMax","ood","temp","triangleRayIntersect","cz","abX","abY","abZ","acX","acY","acZ","pvecX","pvecY","pvecZ","det","invDet","tvecX","tvecY","tvecZ","qvecX","qvecY","qvecZ","frac","lo","hi","decodeBounds","depth","boundsMinx","boundsMiny","boundsMaxx","boundsMaxy","outMin","outMax","rangex","rangey","DemMinMaxQuadTree","dem_","childOffsets","nodeCount","dem","_siblingOffset","mips","levelCount","blockCount","blockSize","blockSamples","exclusive","outBounds","maxx","miny","maxy","mip","blockBounds","e0","sampleElevation","e3","prevMip","l0","l1","l3","minElevation","maxElevation","canConcatenate","buildDemMipmap","maxLvl","rootMip","_addNode","_construct","raycastRoot","minx","raycast","rootMinx","rootMiny","rootMaxx","rootMaxy","tHits","sortedHits","boundsMin","boundsMax","nodex","nodey","minxUv","maxxUv","minyUv","maxyUv","dz","hitPos","bilinearLerp","hitCount","tHit","added","hitIdx","leaf","lvl","parentIdx","childLvl","childMip","firstNodeIdx","leafMask","childX","childY","nodeIdx","p00","p10","p01","p11","fx","fy","demSize","ixMin","iyMin","ixMax","iyMax","unpackVectors","mapbox","terrarium","DEMData","tree","_tree","_buildQuadTree","encoding","borderReady","buildQuadTree","_idx","clampToEdge","pixels","_unpackTerrarium","_unpackMapbox","unpackVector","vector","getUnpackVector","getPixels","backfillBorder","borderTile","xMin","xMax","yMin","yMax","onDeserialize","TileCache","reset","removedData","timeout","clearTimeout","order","expiryTimeout","dataWrapper","_getAndRemoveByKey","getAndRemove","getByKey","dataIndex","setMaxSize","filterFn","removed","IndexBuffer","dynamicDraw","createBuffer","unbindVAO","bindElementBuffer","bufferData","ELEMENT_ARRAY_BUFFER","DYNAMIC_DRAW","STATIC_DRAW","bufferSubData","deleteBuffer","AttributeType","VertexBuffer","attributes","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","attachment","DEPTH_ATTACHMENT","framebufferRenderbuffer","Framebuffer","hasDepth","fbo","framebuffer","createFramebuffer","colorAttachment","depthAttachment","renderbuffer","deleteRenderbuffer","deleteFramebuffer","DepthMode","ReadOnly","ReadWrite","disabled","StencilMode","fail","depthFail","ColorMode","blendFunction","Replace","unblended","alphaBlended","CullFaceMode","mode","backCCW","backCW","frontCW","frontCCW","SourceCache","onlySymbols","_onlySymbols","dataType","sourceDataType","_sourceLoaded","_paused","reload","_sourceErrored","_source","_tiles","_cache","_unloadTile","_timers","_cacheTimers","_maxTileCacheSize","_loadedParentTiles","_coveredTiles","_state","loaded","getSource","pause","resume","shouldReload","_shouldReloadOnResume","_loadTile","loadTile","unloadTile","_abortTile","abortTile","getIds","compareTileId","getRenderableIds","symbolLayer","renderables","_isIdRenderable","a_","b_","rotatedA","rotatedB","hasRenderableParent","parentTile","findLoadedParent","_reloadTile","_tileLoaded","previousState","refreshedUponExpiration","_setTileReloadTimer","_backfillDEM","sourceCacheId","borderId","neighboringTiles","getTileByID","fillBorder","needsHillshadePrepare","needsDEMTextureUpload","backfilled","getTile","_retainLoadedChildren","idealTiles","maxCoveringZoom","retain","topmostLoadedID","parentID","minCoveringZoom","parentTileID","_getLoadedTile","reparseOverscaled","updateCacheSize","widthInTiles","heightInTiles","viewDependentMaxSize","handleWrapJump","wrapDelta","_prevLng","updateForTerrain","freezeTileCoverage","usedForTerrain","idealTileIDs","used","getVisibleUnwrappedCoordinates","unwrapped","coveringTiles","roundZoom","useElevationData","hasTile","_updateRetainedTiles","isRasterType","parentsForFading","fadingTiles","maxOverzooming","_addTile","childTile","retainedId","keysDifference","_fadeDuration","_removeTile","_updateLoadedParentTileCache","afterUpdate","releaseSymbolFadeTiles","checked","maxUnderzooming","missingTiles","childCoord","parentWasRequested","parentId","tileKey","currentId","clearTiles","tilesIn","use3DQuery","tileResults","containsTile","getVisibleCoordinates","posMatrix","calculatePosMatrix","getFeatureState","reloadTilesForDependencies","aWrap","bWrap","DEMSampler","demTile","_demTile","_dem","_scale","_offset","useDemTile","findDEMTileFor","demTileID","FeatureIndex","featureIndexArray","vt","VectorTile","sourceLayerCoder","styleLayers","bounds","bufferedTilespaceBounds","matching","bx1","by1","bx2","by2","bufferedTilespaceGeometry","topDownFeatureComparator","previousIndex","featureGeometry","loadMatchingFeature","featureIndexData","filterLayerIDs","layerIDs","bucketLayerIDs","arraysIntersect","sourceLayerName","layerID","serializedLayer","evaluateProperties","intersectionZ","layerResult","lookupSymbolFeatures","symbolFeatureIndexes","symbolFeatureIndex","serializedProperties","styleLayerProperties","GlyphAtlas","stackPositions","glyphPadding","WorkerTile","collectResourceTiming","returnDependencies","layerIndex","layerFamilies","familiesBySource","anySymbolLayers","anyOtherLayers","recalculateLayers","iconMap","patternMap","taskMetadata","maybePrepare","glyphAtlas","DedupedRequest","scheduler","callbacks","loadVectorTile","skipParse","vectorTile","rawData","cancelCallbacks","addEventListener","receive","globalScope","targetMapId","mustQueue","callbackMetadata","buffers","hasCallback","sourceMapId","processTask","done","getWorkerSource","removeEventListener","getExtension","stencilTest","depthTest","blend","cullFaceSide","extTextureFilterAnisotropic","extTextureFilterAnisotropicMax","getParameter","MAX_TEXTURE_MAX_ANISOTROPY_EXT","extTextureFilterAnisotropicForceOff","extTextureHalfFloat","extRenderToTextureHalfFloat","extTimerQuery","maxTextureSize","MAX_TEXTURE_SIZE","createRenderbuffer","storageFormat","rbo","renderbufferStorage","stencil","COLOR_BUFFER_BIT","DEPTH_BUFFER_BIT","STENCIL_BUFFER_BIT","setCullFace","cullFaceMode","setDepthMode","depthMode","setStencilMode","stencilMode","setColorMode","colorMode","DEPTH_STENCIL_ATTACHMENT","getAtPoint","defaultIfNotLoaded","tilesAtTileZoom","getAtTileOffset","getForTilePoints","helper","getMinMaxForTile","xOffset","yOffset","childOffset","pointCoordinate","screenPoint","visibleDemTiles","pos_","dir_","D","transformRequestFn","_transformRequestFn","_createSkuToken","sessionRandomizer","tokenExpiresAt","createSkuToken","_skuToken","_skuTokenExpiresAt","_isSkuTokenExpired","normalizeStyleURL","urlObject","_makeAPIURL","normalizeSourceURL","normalizeSpriteURL","extension","normalizeTileURL","tileURL","use2x","rasterTileSize","param","getAccessToken","canonicalizeTileURL","removeAccessToken","canonicalizeTileset","tileJSON","sourceURL","help","apiUrlObject","uniform1i","uniform2f","uniform3f","uniformMatrix3fv","uniformMatrix4fv","isSpriteLoaded","loading","perf","workerTile","resourceTiming","parseTile","reloadTile","vtSource","reloadCallback","removeTile","currIdx","prevIdx","nextIdx","curr","interiorAngle","dispatcher","getActor","promise","limit","z2","xx","yx","yy","zx","zy","zz","wx","wy","wz","video","muted","onloadstart","crossOrigin","appendChild","b00","b01","b02","b03","b04","b05","b06","b07","b08","b09","b10","b11","near","far","lr","bt","nf","fovy","aspect","close","minBuf","maxBuf","a3","checkThreshold","deferred","layerObject","render","refProperties","StyleLayerIndex","layerConfigs","keyCache","_layerConfigs","_layers","removedIds","layerConfig","createStyleLayer","groups","cachedKeys","group","groupByLayout","sourceId","sourceGroup","sourceLayerFamilies","RasterDEMTileWorkerSource","rawImageData","imagePixels","offscreenCanvas","offscreenCanvasContext","rewindRings","outer","rewindRing","FeatureWrapper","_feature","EXTENT","tags","GeoJSONWrapper","rawGeometry","fromVectorTileJs","writeLayer","writeTile","keycache","valuecache","writeFeature","writeValue","writeProperties","writeGeometry","keyIndex","valueIndex","command","zigzag","swapItem","sqDist","defaultGetX","defaultGetY","KDBush","getX","getY","nodeSize","ArrayType","IndexArrayType","sortKD","select","inc","nextAxis","r2","defaultOptions","minPoints","generateId","props","fround","Supercluster","trees","load","timerId","clusters","createPointCluster","timeEnd","_cluster","getClusters","minLng","minLat","maxLng","maxLat","easternHem","westernHem","_limitZoom","lngX","latY","numPoints","getClusterJSON","getChildren","clusterId","originId","_getOriginId","originZoom","_getOriginZoom","errorMsg","getLeaves","_appendLeaves","_addTileFeatures","getClusterExpansionZoom","expansionZoom","cluster_id","skipped","point_count","isCluster","getClusterProperties","neighborIds","numPointsOrigin","neighborId","_map","numPoints2","createCluster","original","yLat","abbrev","point_count_abbreviated","getSqSegDist","createFeature","calcLineBBox","calcBBox","convertFeature","tolerance","convertPoint","convertLine","convertLines","projectX","projectY","simplify","sqTolerance","maxSqDist","minPosToMid","posToMid","k2","minAll","maxAll","clipped","newGeometry","clipPoints","clipLines","newGeom","trackMetrics","segLen","newSlice","intersect","intersectX","intersectY","exited","addPoint","shiftFeatureCoords","newFeatures","shiftCoords","newPolygon","newPoints","transformTile","transformed","transformPoint","createTile","numSimplified","numFeatures","simplified","tileFeature","isOuter","rewind","GeoJSONVT","tileCoords","indexMaxZoom","indexMaxPoints","stats","total","merged","splitTile","toID","loadGeoJSONTile","_geoJSONIndex","geoJSONTile","geojsonWrapper","vtpbf","byteOffset","k3","k4","z0","GeoJSONWorkerSource","VectorTileWorkerSource","loadGeoJSON","loadData","_pendingCallback","abandoned","_pendingLoadDataParams","_loadData","gj","superclusterOptions","mapExpressions","reduceExpressions","propertyNames","mapExpression","mapExpressionParsed","reduceExpressionParsed","pointProperties","getSuperclusterOptions","geojsonvt","geojsonVtOptions","getJSON","removeSource","getClusterChildren","getClusterLeaves","Worker","Actor","layerIndexes","workerSourceTypes","workerSources","demWorkerSources","registerWorkerSource","WorkerSource","registerRTLTextPlugin","checkIfReady","mapID","unused","setReferrer","spriteLoaded","bool","workerSource","ws","setImages","setLayers","getLayerIndex","updateLayers","loadDEMTile","getDEMWorkerSource","loadWorkerSource","importScripts","syncRTLPluginState","getAvailableImages","enforceCacheSizeLimit","getWorkerPerformanceMetrics","isSupported","lastIndexOf","reduceRight","Function","getPrototypeOf","getOwnPropertyNames","isSealed","isFrozen","isExtensible","getOwnPropertyDescriptor","defineProperties","seal","preventExtensions","workerURL","terminate","isWorkerSupported","imageData","isCanvasGetImageDataSupported","isWebGLSupportedCache","failIfMajorPerformanceCaveat","shader","webGLContextAttributes","getWebGLContext","createShader","VERTEX_SHADER","shaderSource","compileShader","getShaderParameter","COMPILE_STATUS","isWebGLSupported","documentMode","notSupportedReason","antialias","DOM","tagName","className","container","el","namespaceURI","createElementNS","docStyle","documentElement","selectProp","userSelect","disableDrag","enableDrag","setTransform","passiveSupported","capture","suppressClick","preventDefault","stopPropagation","renderStyleImage","userImage","mousePos","getBoundingClientRect","clientX","clientLeft","clientY","clientTop","touchPos","touches","mouseButton","InstallTrigger","button","ctrlKey","platform","node","parentNode","removeChild","ImageManager","callbackDispatchedThisFrame","requestors","atlasImage","setLoaded","_notify","addImage","valid","_validateStretch","_validateContent","updateImage","removeImage","listImages","getImages","hasAllDependencies","getPixelSize","getPattern","_updatePatternAtlas","atlasTexture","CLAMP_TO_EDGE","dst","beginFrame","sphericalToCartesian","intensity","Light","lightOptions","_transitionable","setLight","_transitioning","getLight","Terrain","terrainOptions","LineAtlas","nextRow","dashEntry","getDash","addDash","getDashRanges","lineAtlasWidth","isDash","zeroLength","currentDashLength","dashLength","addRoundDash","halfStretch","currIndex","distLeft","distRight","minDist","signedDistance","distMiddle","distEdge","addRegularDash","REPEAT","Dispatcher","workerPool","actors","currentActor","workers","acquire","ready","broadcast","release","pixelValue","QueryGeometry","cameraPoint","aboveHorizon","_screenRaycastCache","_cameraRaycastCache","bufferedScreenGeometry","screenGeometryMercator","pointCoordinate3D","cameraGeometry","bufferedCameraGeometry","isPointAboveHorizon","polygonizeBounds","getCameraPoint","cameraPolygon","bufferConvexPolygon","use3D","geometryForTileCheck","_bufferedCameraMercator","_bufferedScreenMercator","tilespaceVec3s","cameraMercator","getFreeCameraOptions","tilespaceCameraPosition","tileVec","Ray","getBounds","poly","vector_layers","vectorLayers","vectorLayerIds","TileBounds","validateBounds","level","RasterTileSource","eventedParent","_loaded","_options","_tileJSONRequest","loadTileJSON","_requestManager","tileBounds","_refreshExpiredTiles","getTileTexture","texParameterf","TEXTURE_MAX_ANISOTROPY_EXT","cacheEntryPossiblyAdded","saveTileTexture","ImageSource","newCoordinates","successCallback","_finishLoading","setCoordinates","cornerCoords","fromLngLat","dMax","getCoordinatesCenterTileID","_boundsArray","RasterBoundsArray","boundsBuffer","rasterBoundsAttributes","boundsSegments","simpleSegment","sourceTypes","_collectResourceTiming","_tileWorkers","_deduped","setSourceProperty","sourceCaches","_getSourceCaches","sourceCache","setTiles","setUrl","raster","raster-dem","transfer","prevPowerOfTwo","_getNeighboringTiles","pxw","nx","nxw","demTexture","_removed","_data","_resourceTiming","attribution","workerOptions","clusterMaxZoom","clusterMinPoints","clusterRadius","_updateWorkerData","setData","getVideo","loop","triggerRepaint","play","seek","seconds","seekableRange","seekable","currentTime","readyState","paused","animate","getElementById","_hasInvalidDimensions","_playing","getCanvas","getPixelPosMatrix","sortTilesIn","renderedFeatureLayers","wrappedTileID","queryResults","wrappedIDLayerMap","wrappedID","wrappedIDLayers","tileFeatures","wrappedIDFeatures","resultFeatures","mergeRenderedFeatureLayers","featureWrapper","dataTiles","dataID","idA","idB","mapboxgl","workerClass","workerUrl","PRELOAD_POOL_ID","WorkerPool","active","workerCount","WebWorker","numActive","isPreloaded","globalWorkerPool","getGlobalWorkerPool","deref","derefLayers","operations","setStyle","addLayer","removeLayer","setFilter","addSource","setGeoJSONSourceData","setLayerZoomRange","setLayerProperty","setCenter","setZoom","setBearing","setPitch","setSprite","setGlyphs","setTerrain","after","commands","sourcesRemoved","updateSource","canUpdateGeoJSON","before","isEqual","diffLayerPropertyChanges","pluckId","indexById","PathInterpolator","padding_","_distances","paddedLength","lerp","distOfCurrentIdx","distToTarget","idxOfPrevPoint","distOfPrevIdx","segmentLength","segmentT","boxCells","circleCells","xCellCount","yCellCount","circleKeys","boxKeys","circles","xScale","yScale","boxUid","circleUid","keysLength","_insertBoxCell","insertCircle","_insertCircleCell","_query","hitTest","predicate","circle","_queryCircle","_queryCellCircle","hitTestCircle","queryArgs","boxCell","circleCell","_circleAndRectCollide","_circlesCollide","_convertToXCellCoord","_convertToYCellCoord","r1","bothRadii","circleX","circleY","halfRectWidth","distX","halfRectHeight","distY","getLabelPlaneMatrix","pitchWithMap","rotateWithMap","labelPlaneMatrix","getGlCoordMatrix","glCoordMatrix","xyTransformMat4","signedDistanceFromCamera","getPerspectiveRatio","isVisible","anchorPos","clippingBuffer","updateLineLabels","isText","partiallyEvaluatedSize","placedSymbols","aspectRatio","useVertical","hideGlyphs","perspectiveRatio","pitchScaledFontSize","tileAnchorPoint","transformedTileAnchor","projectionCache","getElevationForPlacement","placeUnflipped","placeGlyphsAlongLine","needsFlipping","notEnoughRoom","placeFirstAndLastGlyph","flip","returnPathInTileCoords","glyphEndIndex","lineEndIndex","firstGlyphOffset","lastGlyphOffset","firstPlacedGlyph","placeGlyphAlongLine","lastPlacedGlyph","requiresOrientationChange","firstPoint","lastPoint","placedGlyphs","firstAndLastGlyph","orientationChange","glyphIndex","tileVertexIndex","tileSegmentEnd","projectedVertex","projectTruncatedLineSegment","singleGlyph","previousTilePoint","currentTilePoint","previousProjectedPoint","minimumLength","projectionMatrix","unitVertex","projectedUnitVertex","projectedUnitSegment","anchorSegment","endGlyph","combinedOffsetX","distanceToPrev","currentSegmentDistance","absOffsetX","pathVertices","tilePath","previousLineVertexIndex","getTruncatedLineSegment","projection","segmentInterpolationT","prevToCurrent","segmentAngle","hiddenGlyphAttributes","CollisionIndex","ignoredGrid","pitchfactor","_pitch","screenRightBoundary","screenBottomBoundary","gridRightBoundary","gridBottomBoundary","placeCollisionBox","collisionBox","allowOverlap","textPixelRatio","collisionGroupPredicate","projectAndGetPerspectiveRatio","tileToViewport","tlX","tlY","brX","brY","isClipped","isInsideGrid","offscreen","isOffscreen","placeCollisionCircles","labelToScreenMatrix","showCollisionCircles","circlePixelDiameter","textPixelPadding","placedCollisionCircles","tileUnitAnchorPoint","anchorElevation","screenAnchorPoint","labelPlaneFontScale","labelPlaneAnchorPoint","collisionDetected","inGrid","entirelyOffscreen","screenPlaneMin","screenPlaneMax","interpolator","projectedPath","circleDist","screenSpacePath","minPoint","maxPoint","seg","numCircles","circlePosition","centerX","centerY","queryRenderedSymbols","viewportQueryGeometry","gridPoint","seenFeatures","featureKey","bucketInstanceId","intersectionTests","insertCollisionBox","ignorePlacement","collisionGroupID","insertCollisionCircles","collisionCircles","pitch","getViewportMatrix","OpacityState","prevState","increment","placed","skipFade","opacity","JointOpacityState","placedText","placedIcon","JointPlacement","CollisionCircleArray","invProjMatrix","viewportMatrix","RetainedQueryData","CollisionGroups","crossSourceCollisions","maxGroupID","collisionGroups","ID","nextGroupID","calculateVariableLayoutShift","offsetShift","Placement","prevPlacement","collisionIndex","placements","opacities","variableOffsets","stale","commitTime","retainedQueryData","collisionCircleArrays","placedOrientations","getBucketParts","sortAcrossTiles","symbolBucket","bucketFeatureIndex","pixelsToTiles","textLabelPlaneMatrix","partiallyEvaluatedTextSize","partiallyEvaluatedIconSize","collisionGroup","attemptAnchorPlacement","textAllowOverlap","symbolIndex","orientation","textScale","placedGlyphBoxes","prevAnchor","markUsedJustification","markUsedOrientation","placeLayerBucketPart","bucketPart","seenCrossTileIDs","textOptional","iconOptional","iconAllowOverlap","zOrderByViewportY","alwaysShowText","alwaysShowIcon","placeSymbol","placeText","placeIcon","placedVerticalText","placedGlyphCircles","placedIconBoxes","updateElevation","updatePreviousOrientationIfNotPlaced","isPlaced","previousOrientation","prevPlacedOrientation","placeTextForPlacementModes","placeHorizontalFn","placeVerticalFn","placementMode","prevOffsets","unshift","placeBoxForVariableAnchors","collisionTextBox","collisionIconBox","variableIconBox","placedBox","placementAttempts","prevOrientation","prevOffset","placeBox","placedFeature","placeIconFeature","shiftPoint","iconScale","iconWithoutText","textWithoutIcon","circleArray","symbolIndexes","placedAnchor","autoIndex","indexes","horizontalIndexes","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","updateCollisionVertices","verticalIconUsed","hasTransitions","stillRecent","durationAdjustment","setStale","notUsed","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","roundingFactor","TileLayerIndex","indexedSymbolInstances","getScaledCoordinates","childTileID","findMatches","newTileID","zoomCrossTileIDs","indexedInstances","scaledSymbolCoord","thisTileSymbol","CrossTileIDs","maxCrossTileID","generate","CrossTileSymbolLayerIndex","usedCrossTileIDs","zoomIndexes","newZoomIndex","addBucket","crossTileIDs","removeBucketCrossTileIDs","childIndex","parentIndex","removedBucket","removeStaleBuckets","currentIDs","tilesChanged","CrossTileSymbolIndex","maxBucketInstanceId","bucketsInCurrentPlacement","symbolBucketsChanged","currentBucketIDs","pruneUnusedLayers","usedLayers","usedLayerMap","usedLayer","_emitValidationErrors","supportedDiffOperations","diffOperations","ignoredDiffOperations","empty","latest","styleKey","emptyStyle","drapedLayers","background","hillshade","getWorkerPool","glyphManager","localIdeographFontFamily","lineAtlas","crossTileSymbolIndex","_num3DLayers","_numSymbolLayers","_numCircleLayers","_serializedLayers","_sourceCaches","_otherSourceCaches","_symbolSourceCaches","_availableImages","_order","_drapedFirstOrder","_resetUpdates","_rtlTextPluginCallback","registerForPluginStateChange","elem","sourceCacheType","_validateLayer","loadURL","_request","_load","loadJSON","loadEmpty","_updateLayerCount","stylesheet","_changed","_loadSprite","_serializeLayers","_createTerrain","_updateDrapeFirstLayers","_spriteRequest","baseURL","jsonRequest","maybeComplete","imageRequest","loadSprite","_updatedSources","_optimizeForTerrain","isLayerDraped","_checkLoaded","changed","updatedIds","_updatedLayers","_removedLayers","_updateWorkerLayers","action","_reloadSource","_clearSource","_updateTilesForChangedImages","_updatedPaintProps","sourcesUsedBefore","_getLayerSourceCache","programIds","programConfiguration","programId","changedImages","_changedImages","nextState","changes","removeOrAddSourceCommands","diffSources","beforeLayers","beforeTerrain","beforeOrder","afterOrder","beforeIndex","afterIndex","tracker","clean","beforeLayer","afterLayer","insertBeforeLayerId","diffLayers","diffStyles","unimplementedOps","_afterImageUpdated","sourceInstance","createSource","isSourceLoaded","addSourceCache","_getSourceCache","validateCustomStyleLayer","_layerOrderChanged","_updateLayer","moveLayer","newIndex","hasLayerType","getFilter","cacheId","_flattenAndSortRenderedFeatures","sourceResults","isLayer3D","features3D","sourceResult","layerFeatures","topmost3D","includedSources","has3DLayer","has3DLayers","queryGeometryStruct","createFromScreenPoints","_showQueryGeometry","getLayerSourceCache","renderedSymbols","bucketQueryData","queryData","bucketSymbols","layerSymbols","sortedA","symbolFeature","layerName","addSourceType","SourceType","getSourceType","setSourceType","workerSourceURL","_update","_force3DLayerUpdate","currSpec","draped","nonDraped","_remove","rtlTextPluginEvented","_updateSources","_generateCollisionBoxes","_updatePlacement","placementCommitted","layerBucketsChanged","pauseablePlacement","_releaseSymbolFadeTiles","getResource","hasSymbolLayers","hasCircleLayers","preludeTerrain","compile","prelude","backgroundPattern","clippingMask","heatmap","heatmapTexture","collisionCircle","fillOutline","fillOutlinePattern","fillPattern","fillExtrusion","fillExtrusionPattern","hillshadePrepare","lineGradient","linePattern","lineSDF","symbolIcon","symbolSDF","symbolTextAndIcon","terrainRaster","terrainDepth","skybox","skyboxVert","skyboxGradient","skyboxCapture","fragmentSource","vertexSource","isPreludeTerrainShader","re","staticAttributes","fragmentUniforms","vertexUniforms","staticUniforms","fragmentPragmas","operation","attrType","unpackType","VertexArrayObject","boundProgram","boundLayoutVertexBuffer","boundPaintVertexBuffers","boundIndexBuffer","boundVertexOffset","boundDynamicVertexBuffer","paintVertexBuffers","dynamicVertexBuffer","dynamicVertexBuffer2","paintBuffersDiffer","boundDynamicVertexBuffer2","freshBind","numPrevAttributes","numNextAttributes","numAttributes","createVertexArrayOES","currentNumAttributes","disableVertexAttribArray","vertexBuffer","deleteVertexArrayOES","getTileLatRange","renderHillshade","prepareDrawTile","uniformValues","shadow","highlight","accent","moving","u_matrix","u_image","u_latrange","u_light","u_shadow","u_highlight","u_accent","TRIANGLES","rasterBoundsBuffer","quadTriangleIndexBuffer","rasterBoundsSegments","prepareDEMTexture","pixelData","prepareHillshade","TEXTURE1","NEAREST","renderTexture","u_dimension","u_zoom","u_unpack","terrainRasterUniforms","UniformMatrix4f","u_image0","Uniform1i","u_skirt_height","terrainRasterUniformValues","skirtHeight","vertexMorphing","newMorphing","phase","getMorphValuesForProxy","_validOp","_nextOp","shaderDefines","0","1","drawTerrainRaster","tileIDs","programMode","colorModeForRenderPass","LEQUAL","depthRangeFor3D","skirt","prevDemTile","prevTerrainTileForTile","nextDemTile","terrainTileForTile","morph","shaderMode","elevationOptions","morphing","srcDemTile","dstDemTile","isEdgeTile","renderWorldCopies","setupElevationDraw","gridBuffer","gridIndexBuffer","gridSegments","cid","numTiles","clippingMaskUniformValues","rasterFade","sinceTile","sinceParent","idealZ","coveringZoomLevel","fadeIn","childOpacity","mix","ProxySourceCache","renderCache","renderCachePool","proxyCachedFBO","incoming","freeFBO","fbos","fboIds","deallocRenderCache","fb","ProxiedTileID","proxyTileKey","Elevation","triangleGridArray","triangleGridIndices","skirtIndicesOffset","boundsArray","gridBound","bound","quad","createGrid","gridNoSkirtSegments","proxyCoords","proxiedCoords","_visibleDemTiles","_drapedRenderBatches","_sourceTilesOverlap","proxySourceCache","orthoMatrix","_overlapStencilMode","GEQUAL","REPLACE","_previousZoom","pool","_findCoveringTileCache","_tilesDirty","_useVertexMorphing","_onStyleDataEvent","_checkRenderCacheEfficiency","_style","cameraChanging","enabled","terrainProps","_exaggeration","updateSourceCache","demScale","proxyTileSize","_initializing","_emptyDEMTextureDirty","_disable","renderCacheInfo","renderCacheEfficiency","efficiency","firstUndrapedLayer","_clearRenderCacheForTile","_invalidateRenderCache","_emptyDEMTexture","_depthFBO","_depthTexture","drapeBufferSize","useVertexMorphing","updateTileBinding","sourcesCoords","psc","_centerAltitude","renderCached","zooming","rotating","forceRenderCached","cameraCoordinate","aPoint","bPoint","cameraScaled","sortByDistanceToCamera","previousProxyToSource","proxyToSource","_setupProxiedCoordsForOrtho","_assignTerrainTiles","_prepareDEMTextures","_setupDrapedRenderBatches","_setupRenderCache","renderingToTexture","_initFBOPool","_updateTimestamp","visibleKeys","_findTileCoveringTileID","_prepareDemTileUniforms","proxyTile","uniformSuffix","proxyId","demScaleBy","emptyDEMTexture","_updateEmptyDEMTexture","_getLoadedAreaMinimum","nonzero","TEXTURE2","pack","u_dem","u_dem_prev","u_dem_unpack","u_dem_tl","u_dem_tl_prev","u_dem_scale","u_dem_scale_prev","u_dem_size","u_dem_lerp","u_depth","u_depth_size_inv","u_exaggeration","morphingPhase","srcTile","dstTile","TEXTURE4","useDepthForOcclusion","TEXTURE3","useMeterToDem","labelPlaneMatrixInv","setTerrainUniformValues","renderBatch","startLayerIndex","proxies","setupRenderToScreen","drapedLayerBatch","drawAsRasterCoords","poolIndex","proxy","renderCacheIndex","currentStencilSource","currentFBO","renderedToTile","_setupStencil","renderLayer","postRender","layerCount","uncacheableLayerCount","drapedLayerCount","reachedUndrapedLayer","preparedTiles","_createFBO","bufferSize","_shouldDisableRenderCache","crossFade","_clearRasterFadeFromRenderCache","hasRasterSource","fade","batches","batchStart","currentLayer","equal","prevTiles","proxyFBO","batch","_overlapStencilType","stencilRange","EQUAL","GREATER","DEPTH_STENCIL","DepthStencilAttachment","_renderTileClippingMasks","stencilModeForRTTOverlap","_tileClippingMaskIDs","tileExtentBuffer","tileExtentSegments","pixelMatrixInverse","camera","_camera","mercatorZScale","distanceAlongRay","drawDepth","DEPTH_COMPONENT16","drawTerrainDepth","sourceCoords","_setupProxiedCoordsForImageSource","proxys","proxyTileID","proxied","_createProxiedId","hasOverlap","imageSource","aabb","tileOutsideImage","imageTileID","ix","iy","recycle","recycled","find","lookup","sourceTileID","downscale","pathToLookup","sourceTiles","getTokenizedAttributesAndUniforms","define","configuration","fixedUniforms","fixedDefines","createProgram","staticAttrInfo","dynamicAttrInfo","allAttrInfo","staticUniformsInfo","dynamicUniformsInfo","uniformList","allUniformsInfo","fragmentShader","FRAGMENT_SHADER","failedToCreate","attachShader","vertexShader","uniformLocations","bindAttribLocation","linkProgram","deleteShader","it","uniformLocation","getUniformLocation","terrainUniforms","Uniform2f","u_meter_to_dem","u_label_plane_matrix_inv","terrainUnformValues","drawMode","currentProperties","dynamicLayoutBuffer","dynamicLayoutBuffer2","primitiveSize","LINES","LINE_STRIP","drawElements","UNSIGNED_SHORT","patternUniformValues","tileRatio","tileSizeAtNearestZoom","pixelX","pixelY","u_texsize","u_scale","u_fade","u_pixel_coord_upper","u_pixel_coord_lower","fillExtrusionUniformValues","shouldUseVerticalGradient","_lp","lightPos","lightMat","lightColor","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","translatePosMatrix","u_device_pixel_ratio","u_extrude_scale","circleDefinesValues","collisionUniformValues","debugUniformValues","scaleRatio","u_color","u_overlay","u_overlay_scale","heatmapUniformValues","u_intensity","lineUniformValues","calculateMatrix","u_ratio","u_units_to_pixels","lineGradientUniformValues","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","u_tl_parent","u_scale_parent","u_buffer_scale","u_fade_t","u_image1","u_brightness_low","u_brightness_high","u_saturation_factor","saturation","u_contrast_factor","contrast","u_spin_weights","spinWeights","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_pitch_with_map","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","Uniform3f","u_inv_matrix","u_viewport_size","u_color_ramp","u_sun_direction","u_cubemap","u_temporal_offset","u_center_direction","u_radius","u_matrix_3f","UniformMatrix3f","u_sun_intensity","u_color_tint_r","u_color_tint_m","u_luminance","quadTriangles","drawCollisionDebug","tileBatches","circleCount","circleOffset","invTransform","circleProgram","vertexData","CollisionCircleLayoutArray","circleIdx","collision","quadCount","triCount","QuadTriangleArray","createQuadTriangles","identityMat4","calculateVariableRenderShift","renderTextSize","updateVariableAnchorsForBucket","tileScale","updateTextFitIcon","dynamicTextLayoutVertexArray","dynamicIconLayoutVertexArray","placedTextShifts","skipOrientation","tileAnchor","projectedAnchor","symbolProjection","shiftedAnchor","placedIcons","getSymbolProgramName","drawLayerSymbols","rotationAlignment","pitchAlignment","hasSortKey","depthModeForSublayer","tileRenderState","atlasInterpolation","atlasInterpolationIcon","atlasTextureIcon","zoomDependentSize","iconScaled","hasVariableAnchors","uLabelPlaneMatrix","uglCoordMatrix","hasHalo","oldSegments","segmentState","drawSymbolElements","drawFillTiles","isOutline","programName","atlas","tileMatrix","stencilModeForClipping","drawExtrusionTiles","flatRoofsUpdate","attrIndex","vertexAttrib2f","neighborCoord","getLoadedBucket","nid","nBucket","projectedToBorder","xjoin","yjoin","projectCombinedSpanToBorder","neighborDEMTile","neighborTileID","flatBase","edge","verticalEdge","maxOffsetFromBorder","coord3","thirdPoint","ib","ia","parta","partABorderRange","partb","saveIb","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","skyboxAttributes","SkyboxGeometry","SkyboxVertexArray","drawSkyboxFace","faceRotate","sunDirection","atmosphereColor","atmosphereHaloColor","sunIntensity","TEXTURE_CUBE_MAP_POSITIVE_X","renderPass","pixelToTileScale","updateVariableAnchors","strokeWidth","strokeOpacity","segmentsRenderStates","definesValues","segmentsState","HALF_FLOAT_OES","bindTextureToFramebuffer","textureUnit","colorRampUnit","viewportBuffer","viewportSegments","renderTextureToMap","firstTile","prevProgram","programChanged","layerGradient","gradientTexture","textureResolution","potentialOverzoom","nextPowerOfTwo","opaquePassEnabledForLayer","stencilModeFor3D","stencilModes","stencilConfigForOverlap","isInitialLoad","minTileZ","rasterFadeDuration","textureFilter","isPatternMissing","temporalOffset","frameCounter","skyboxFbo","TEXTURE_CUBE_MAP","captureSkybox","cubemap","skyboxMatrix","drawSkyboxFromCapture","centerDirection","drawSkyboxGradient","setCustomLayerDefaults","customLayerMatrix","setBaseState","Painter","Context","_tileTextures","frameCopies","loadTimeStamps","setup","numSublayers","depthEpsilon","gpuTimers","updateTerrain","_terrain","tileExtentArray","PosArray","posAttributes","debugArray","rasterBoundsArray","viewportArray","tileLineStripIndices","LineStripIndexArray","quadTriangleIndices","stencilClearMode","nextStencilID","NOTEQUAL","stencilValues","zToStencilMode","_showOverdrawInspector","CONSTANT_COLOR","opaquePassCutoff","coordsAscending","coordsDescending","coordsDescendingSymbol","showOverdrawInspector","isHorizonVisible","showTileBoundaries","showQueryGeometry","selectedSource","showPadding","centerPoint","drawCrosshair","drawDebugPadding","tileLoaded","speedIndexTiming","saveCanvasCopy","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","translatedMatrix","textures","currentGlobalDefines","rtt","allDefines","shaders","setTileLoadedFlag","flag","canvasCopy","copyTexImage2D","getCanvasCopiesAndTimestamps","canvasCopies","timeStamps","EdgeInsets","getColumn","col","setColumn","updateTransformOrientation","updateTransformPosition","orientationFromPitchBearing","orientationFromFrame","xyForward","xyUp","xyDir","FreeCameraOptions","_position","_renderWorldCopies","mercatorCoordinate","wrapCameraPosition","lookAtPoint","_elevation","setPitchBearing","FreeCamera","_transform","_orientation","mercatorPosition","getPitchBearing","getCameraToWorld","pixelsPerMeter","cameraToWorld","getWorldToCamera","invOrientation","invPosition","getCameraToClipPerspective","nearZ","farZ","Transform","minPitch","maxPitch","maxValidLatitude","_minZoom","_maxZoom","_minPitch","_maxPitch","setMaxBounds","_center","_fov","_unmodified","_edgeInsets","_posMatrixCache","_alignedPosMatrixCache","cameraElevationReference","_horizonShift","latRange","_setZoom","_cameraZoom","_calcMatrices","_updateCenterElevation","_updateCameraOnTerrain","constrainCameraOverTerrain","_terrainEnabled","_constrainCameraAltitude","centerOffset","rotationMatrix","mat2","fov","_zoom","_constrain","zoomScale","zoomFraction","elevationAtCenter","terrainElevation","_zoomFromMercatorZ","_updateZoomFromElevation","cameraZoom","mercatorElevation","_mercatorZfromZoom","minHeight","computeZoomRelativeTo","centerOnTargetAltitude","rayIntersectionCoordinate","pointRayIntersection","targetPosition","setFreeCameraOptions","_updateCameraState","_setCameraOrientation","newPosition","_setCameraPosition","_updateStateFromCamera","recenterOnTerrain","updatedOrientation","minWorldSize","maxWorldSize","distToCenter","fovAboveCenter","isPaddingEqual","interpolatePadding","scaleZoom","utl","utr","ubl","ubr","w0","w1","extraWorldCopy","actualZ","centerCoord","cameraFrustum","fromInvProjectionMatrix","cameraCoord","meterToTile","cameraAltitude","zoomSplitDistance","maxRange","newRootTile","fullyVisible","getAABBFromElevation","minmax","square","cameraHeightSqr","distToSplitScale","dzSqr","dSqr","intersectResult","shouldSplit","distanceSqr","distanceSq","unmodified","unproject","setLocationAtPoint","loc","locationCoordinate","newCenter","coordinateLocation","setLocation","locationPoint","_coordinatePoint","locationPoint3D","pointLocation","pointLocation3D","z1","screenPointToMercatorRay","rayIntersection","horizonOffset","horizonLineFromTop","clamped","threshold","rCast","horizon","sampleTerrainIn3D","pixelMatrix","_getBounds3D","clampToTop","getMaxBounds","lngRange","unwrappedTileID","aligned","posMatrixKey","unwrappedX","alignedProjMatrix","projMatrix","mercatorMatrix","metersToMerc","maxAltitude","elevationAtCamera","_minimumHeightOverTerrain","cameraHeight","cameraPos","cameraToCenter","prevDistToCamera","newDistToCamera","_constraining","sy","sx","h2","_minZoomForBounds","minZoomForDim","minLatZoom","minLngZoom","_maxCameraBoundsDistance","groundAngle","cameraToSeaLevelDistance","topHalfSurfaceDistance","furthestDistance","worldToCamera","cameraToClip","skyboxHorizonShift","xShift","yShift","angleCos","angleSin","alignedM","updatedWorldSize","_translateCameraConstrained","deltaZ","centerAltitude","_worldSizeFromZoom","isHorizonVisibleForPoints","minWX","maxWX","coordinate","radToDeg","zoomDeltaToMovement","zoomDelta","relativeZoom","Hash","hashName","_hashName","_updateHash","pending","later","throttle","_updateHashUnthrottled","addTo","_onHashChange","getHashString","mapFeedback","getZoom","getBearing","getPitch","hash","found","_getCurrentHash","keyval","dragRotate","isEnabled","touchZoomRotate","jumpTo","history","replaceState","defaultInertiaOptions","linearity","easing","defaultPanInertiaOptions","deceleration","maxSpeed","defaultZoomInertiaOptions","defaultBearingInertiaOptions","defaultPitchInertiaOptions","HandlerInertia","_inertiaBuffer","record","settings","_drainInertiaBuffer","inertia","_onMoveEnd","panInertiaOptions","deltas","pan","pinchAround","around","bearingDelta","pitchDelta","panDelta","easeOptions","calculateEasing","amount","extendDuration","noMoveStart","inertiaDuration","inertiaOptions","speed","MapMouseEvent","_defaultPrevented","defaultPrevented","originalEvent","getCanvasContainer","MapTouchEvent","changedTouches","lngLats","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","_enabled","_active","shiftKey","_startPos","_lastPos","mousemoveWindow","_box","classList","_fireEvent","mouseupWindow","cameraAnimation","fitScreenCoordinates","linear","keydown","keyCode","indexTouches","SingleTapRecognizer","numTouches","mapTouches","timeStamp","getCentroid","newTouches","prevPos","TapRecognizer","singleTap","numTaps","lastTime","lastTap","tap","soonEnough","closeEnough","TapZoomHandler","_zoomIn","_zoomOut","zoomInPoint","zoomOutPoint","easeTo","BUTTONS_FLAGS","2","MouseHandler","_moved","_lastPoint","_eventButton","_correctButton","_move","eventButton","buttons","buttonStillPressed","MousePanHandler","MouseRotateHandler","MousePitchHandler","TouchPanHandler","_minTouches","_touches","_sum","_calculateTransform","touchPointSum","touchDeltaSum","touchDeltaCount","prevPoint","TwoTouchHandler","_firstTwoTouches","_start","getTouchById","_aroundCenter","getZoomDelta","lastDistance","TouchZoomHandler","_distance","_startDistance","getBearingDelta","TouchRotateHandler","_minDiameter","_startVector","_vector","lastVector","_isBelowThreshold","bearingDeltaSinceStart","isVertical","TouchPitchHandler","_valid","_firstMove","_lastPoints","vectorA","vectorB","gestureBeginsVertically","movedA","movedB","isSameDirection","panStep","bearingStep","pitchStep","KeyboardHandler","stepOptions","_panStep","_bearingStep","_pitchStep","_rotationDisabled","altKey","metaKey","zoomDir","bearingDir","pitchDir","xDir","yDir","easeId","easeOut","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","_aroundPoint","_aroundCoord","_targetZoom","_triggerRenderFrame","renderFrame","startingZoom","startZoom","startScale","_startZoom","_easing","_smoothOutEasing","targetZoom","finished","noInertia","needsRenderFrame","aroundCoord","_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","TrackingEllipsoid","pointOnSurface","centerToSurface","projectRay","intersection","hasChange","HandlerManager","_handlers","_handlersById","_changes","_inertia","_bearingSnap","bearingSnap","_previousActiveHandlers","_trackingEllipsoid","_dragOrigin","_eventsInProgress","_addDefaultHandlers","passive","listenerOptions","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","toVec3","preZoom","panVec","startRay","endRay","startPoint","endPoint","originalZoom","zoomVec","pickedPosition","aroundRay","centerRay","pickedAltitude","centerOnTargetPlane","movement","newEventsInProgress","wasMoving","nowMoving","startEvents","endEvents","originalEndEvent","stillMoving","inertialEase","shouldSnapToNorth","resetNorth","_requestFrame","_renderTaskQueue","Camera","_moving","panBy","panTo","zoomTo","zoomIn","zoomOut","getPadding","setPadding","rotateTo","resetNorthPitch","snapToNorth","cameraForBounds","_cameraForBoxAndBearing","_extendCameraOptions","defaultPadding","eOptions","edgePadding","p0world","p1world","p0rotated","p1rotated","upperRight","lowerLeft","scaleX","scaleY","rotatedPaddingOffset","offsetAtFinalZoom","_cameraForBox","minAltitude","focus","focusAltitude","coord0","coord1","centerIntersectionPoint","centerIntersectionCoord","centerMercatorRay","halfDistanceToGround","steps","cameraPositionToGround","fitBounds","_fitInternal","_raycastElevationBox","point0","point1","point2","point3","r0","r3","m0","m3","minLngLat","maxLngLat","lngLat0","lngLat1","calculatedOptions","flyTo","zoomChanged","bearingChanged","pitchChanged","prevZoom","prevPitch","prevBearing","defaultEasing","essential","startBearing","startPitch","startPadding","_normalizeBearing","offsetAsPoint","pointAtOffset","locationAtOffset","_normalizeCenter","finalScale","aroundPoint","currently","_rotating","pitching","_pitching","_padding","_easeId","_prepareEase","speedup","_fireMoveEvents","interruptingEaseId","_afterEase","wasZooming","wasRotating","wasPitching","coercedOptions","curve","rho","u1","wMax","rho2","sinh","cosh","S","screenSpeed","maxDuration","isEasing","_easeFrameId","allowGestures","_cancelRenderFrame","_onEaseFrame","_onEaseEnd","onEaseEnd","handlers","_easeStart","_easeOptions","_requestRenderFrame","_renderFrameCallback","currentBearing","diff","AttributionControl","getDefaultPosition","compact","_compactButton","_toggleAttribution","_setElementTitle","_innerContainer","setAttribute","_updateAttributions","_updateEditLink","_updateData","_updateCompact","_attribHTML","element","title","_getUIString","editLink","_editLink","querySelector","styleOwner","styleId","paramString","_hash","rel","attributions","customAttribution","owner","attrib","attribHTML","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","HTMLElement","attributionControl","preserveDrawingBuffer","trackResize","optimizeForTerrain","refreshExpiredTiles","maxTileCacheSize","showCompass","showZoom","visualizePitch","MouseRotateWrapper","down","move","offTemp","targetTouches","priorPos","withinWrap","anchorTranslate","top-left","top-right","bottom-left","bottom-right","applyAnchorClass","prefix","Marker","legacyOptions","_anchor","_color","_draggable","draggable","_isDragging","_rotation","_rotationAlignment","_pitchAlignment","_element","_defaultMarker","svg","createNS","defaultHeight","defaultWidth","setAttributeNS","markerLarge","page1","ellipses","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","markerHeight","markerRadius","linearOffset","getAttribute","legacyCode","charCode","togglePopup","targetElement","getPopup","isOpen","_updateOcclusion","_occlusionTimer","_onOcclusionTimer","_transformedOffset","raycastLoc","raycastDistance","posDistance","toggle","smartWrap","getOffset","setOffset","_pointerdownPos","_positionDelta","pointerEvents","shouldBeDraggable","isDraggable","setRotation","getRotation","setRotationAlignment","getRotationAlignment","setPitchAlignment","getPitchAlignment","positionOptions","enableHighAccuracy","maximumAge","fitBoundsOptions","trackUserLocation","showAccuracyCircle","showUserLocation","supportsGeolocation","numberOfWatches","noTimeout","updateScale","clientHeight","maxMeters","maxFeet","setScale","maxDistance","pow10","multiplier","getDecimalRoundNum","getRoundNum","closeButton","closeOnClick","focusAfterOpen","focusQuerySelector","setRTLTextPlugin","Map","_interactive","_failIfMajorPerformanceCaveat","_preserveDrawingBuffer","_antialias","_trackResize","_isInitialLoad","_crossSourceCollisions","_crossFadingFactor","_controls","_mapId","_locale","RequestManager","maxBounds","_setupContainer","_setupPainter","_onWindowOnline","_onWindowResize","_localFontFamily","_localIdeographFontFamily","addControl","_logoControl","logoPosition","_getMapId","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","delegate","delegatedListener","_delegatedListeners","delegatedListeners","_diffStyle","_updateStyle","_updateTerrain","_lazyInitEmptyStyle","_updateDiff","getStyle","isStyleLoaded","sc","areTilesLoaded","existingImage","hasImage","loadImage","beforeId","_canvasContainer","_canvas","clientWidth","_detectMissingCSS","getComputedStyle","_missingCSSCanary","getPropertyValue","canvasContainer","_contextLost","_contextRestored","controlContainer","_controlContainer","positionName","_onMapScroll","_frame","scrollTop","scrollLeft","_styleDirty","_sourcesDirty","updateStyle","_render","paintStartTimeStamp","frameStartTime","crossFading","_placementDirty","renderCPUTime","renderGPUTime","frameLayerQueries","renderedLayerTimes","layerTimes","somethingDirty","_repaint","_triggerFrame","_authenticate","speedIndexNumber","_calculateSpeedIndex","speedIndex","_fullyLoaded","AUTH_ERR_MSG","finalFrame","canvasCopyInstances","read","readPixels","_canvasPixelComparison","allFrames","finalScore","numPixels","cnt","loseContext","_renderNextFrame","isRenderFrame","_showTileBoundaries","_speedIndexTiming","_showPadding","repaint","_vertices","_setCacheLimits","setCacheLimits","NavigationControl","_zoomInButton","_createButton","_zoomOutButton","_compass","_compassIcon","_updateZoomButtons","isMax","isMin","_rotateCompassArrow","_setButtonTitle","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","setUnit","FullscreenControl","_fullscreen","_fullscreenchange","_checkFullscreenSupport","_changeIcon","fullscreenEnabled","webkitFullscreenEnabled","_fullscreenButton","_updateTitle","_onClickFullscreen","_getTitle","_isFullscreen","fullscreenElement","webkitFullscreenElement","exitFullscreen","webkitCancelFullScreen","requestFullscreen","webkitRequestFullscreen","Popup","_onClose","closeOnMove","_focusFirstElement","_trackPointer","_onMouseMove","_onMouseUp","_content","_onDrag","trackPointer","setText","setDOMContent","createTextNode","setHTML","html","frag","createDocumentFragment","getMaxWidth","setMaxWidth","htmlNode","hasChildNodes","_createCloseButton","addClassName","removeClassName","toggleClassName","_closeButton","cursor","_tip","normalizeOffset","cornerOffset","convertedOffset","offsetHeight","anchorComponents","offsetedPos","firstFocusable","prewarm","clearPrewarmedResources","baseApiUrl","maxParallelImageRequests","numRequests","clearStorage","clearTileCache"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;mDA4BiBA,EAEjB,SAASA,EAAWC,EAAKC,EAAKC,EAAKC,GAE/BC,KAAKC,GAAK,EAAML,EAChBI,KAAKE,GAAK,GAAOJ,EAAMF,GAAOI,KAAKC,GACnCD,KAAKG,GAAK,EAAMH,KAAKC,GAAKD,KAAKE,GAE/BF,KAAKI,GAAK,EAAMP,EAChBG,KAAKK,GAAK,GAAON,EAAMF,GAAOG,KAAKI,GACnCJ,KAAKM,GAAK,EAAMN,KAAKI,GAAKJ,KAAKK,GAE/BL,KAAKJ,IAAMA,EACXI,KAAKH,IAAME,EACXC,KAAKF,IAAMA,EACXE,KAAKD,IAAMA,GAGfJ,EAAWY,UAAUC,aAAe,SAASC,GAEzC,cAAcN,GAAKM,EAAIT,KAAKE,IAAMO,EAAIT,KAAKC,IAAMQ,GAGrDd,EAAWY,UAAUG,aAAe,SAASD,GACzC,cAAcH,GAAKG,EAAIT,KAAKK,IAAMI,EAAIT,KAAKI,IAAMK,GAGrDd,EAAWY,UAAUI,uBAAyB,SAASF,GACnD,UAAcT,KAAKG,GAAKM,EAAI,EAAMT,KAAKE,IAAMO,EAAIT,KAAKC,IAG1DN,EAAWY,UAAUK,YAAc,SAASC,EAAGC,GAG3C,IAAIC,EAAIC,EAAIC,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